source: josm/trunk/src/org/openstreetmap/josm/gui/MainApplication.java

Last change on this file was 19050, checked in by taylor.smock, 3 days ago

Revert most var changes from r19048, fix most new compile warnings and checkstyle issues

Also, document why various ErrorProne checks were originally disabled and fix
generic SonarLint issues.

  • Property svn:eol-style set to native
File size: 73.2 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[283]2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
[19019]5import static org.openstreetmap.josm.tools.I18n.trc;
[3461]6import static org.openstreetmap.josm.tools.I18n.trn;
[13647]7import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
[283]8
[14177]9import java.awt.AWTError;
[17487]10import java.awt.Color;
[12808]11import java.awt.Container;
[6523]12import java.awt.Dimension;
[12923]13import java.awt.Font;
[12634]14import java.awt.GraphicsEnvironment;
[12766]15import java.awt.GridBagLayout;
[17866]16import java.awt.RenderingHints;
[13021]17import java.awt.Toolkit;
[3435]18import java.io.File;
[7335]19import java.io.IOException;
[7033]20import java.io.InputStream;
[13021]21import java.lang.reflect.Field;
[2641]22import java.net.Authenticator;
[8356]23import java.net.Inet6Address;
[8296]24import java.net.InetAddress;
[2641]25import java.net.ProxySelector;
[5201]26import java.net.URL;
[13443]27import java.nio.file.InvalidPathException;
[13402]28import java.nio.file.Paths;
[3232]29import java.security.AllPermission;
30import java.security.CodeSource;
[10235]31import java.security.GeneralSecurityException;
[3232]32import java.security.PermissionCollection;
33import java.security.Permissions;
34import java.security.Policy;
[11650]35import java.util.ArrayList;
[7434]36import java.util.Arrays;
[283]37import java.util.Collection;
[11650]38import java.util.Collections;
[283]39import java.util.List;
[8404]40import java.util.Locale;
[11650]41import java.util.Map;
[12792]42import java.util.Objects;
[10899]43import java.util.Optional;
[13021]44import java.util.ResourceBundle;
[6642]45import java.util.Set;
46import java.util.TreeSet;
[12634]47import java.util.concurrent.ExecutorService;
[12695]48import java.util.concurrent.Executors;
[12633]49import java.util.concurrent.Future;
[10899]50import java.util.logging.Level;
[11255]51import java.util.stream.Collectors;
52import java.util.stream.Stream;
[283]53
[11455]54import javax.net.ssl.SSLSocketFactory;
[12639]55import javax.swing.Action;
56import javax.swing.InputMap;
[12128]57import javax.swing.JComponent;
[19012]58import javax.swing.JDialog;
[12766]59import javax.swing.JLabel;
[6523]60import javax.swing.JOptionPane;
[12766]61import javax.swing.JPanel;
[18985]62import javax.swing.JTextPane;
[12639]63import javax.swing.KeyStroke;
[12637]64import javax.swing.LookAndFeel;
[4720]65import javax.swing.RepaintManager;
[3679]66import javax.swing.SwingUtilities;
[12637]67import javax.swing.UIManager;
68import javax.swing.UnsupportedLookAndFeelException;
[16961]69import javax.swing.plaf.FontUIResource;
[283]70
[12749]71import org.openstreetmap.josm.actions.DeleteAction;
[12639]72import org.openstreetmap.josm.actions.JosmAction;
[12633]73import org.openstreetmap.josm.actions.OpenFileAction;
[12695]74import org.openstreetmap.josm.actions.OpenFileAction.OpenFileTask;
[6523]75import org.openstreetmap.josm.actions.PreferencesAction;
[9238]76import org.openstreetmap.josm.actions.RestartAction;
[17637]77import org.openstreetmap.josm.actions.ShowStatusReportAction;
[12633]78import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
79import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
[13927]80import org.openstreetmap.josm.actions.downloadtasks.DownloadParams;
[12633]81import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
82import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
83import org.openstreetmap.josm.actions.search.SearchAction;
[14118]84import org.openstreetmap.josm.cli.CLIModule;
[12749]85import org.openstreetmap.josm.command.DeleteCommand;
[12828]86import org.openstreetmap.josm.command.SplitWayCommand;
[12631]87import org.openstreetmap.josm.data.Bounds;
[14149]88import org.openstreetmap.josm.data.Preferences;
[12641]89import org.openstreetmap.josm.data.UndoRedoHandler;
[12718]90import org.openstreetmap.josm.data.UndoRedoHandler.CommandQueueListener;
[4259]91import org.openstreetmap.josm.data.Version;
[12686]92import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
[12766]93import org.openstreetmap.josm.data.osm.UserInfo;
[12659]94import org.openstreetmap.josm.data.osm.search.SearchMode;
[13021]95import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
[14119]96import org.openstreetmap.josm.data.preferences.JosmUrls;
[12825]97import org.openstreetmap.josm.data.preferences.sources.SourceType;
[14120]98import org.openstreetmap.josm.data.projection.ProjectionBoundsProvider;
[12792]99import org.openstreetmap.josm.data.projection.ProjectionCLI;
[14120]100import org.openstreetmap.josm.data.projection.ProjectionRegistry;
[12777]101import org.openstreetmap.josm.data.projection.datum.NTV2GridShiftFileSource;
102import org.openstreetmap.josm.data.projection.datum.NTV2GridShiftFileWrapper;
103import org.openstreetmap.josm.data.projection.datum.NTV2Proj4DirGridShiftFileSource;
[18365]104import org.openstreetmap.josm.data.validation.ValidatorCLI;
[12825]105import org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker;
[10899]106import org.openstreetmap.josm.gui.ProgramArguments.Option;
[10093]107import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
[12770]108import org.openstreetmap.josm.gui.bugreport.BugReportDialog;
[14176]109import org.openstreetmap.josm.gui.bugreport.DefaultBugReportSendingHandler;
[4906]110import org.openstreetmap.josm.gui.download.DownloadDialog;
[12821]111import org.openstreetmap.josm.gui.io.CredentialDialog;
[12634]112import org.openstreetmap.josm.gui.io.CustomConfigurator.XMLCommandProcessor;
[12636]113import org.openstreetmap.josm.gui.io.SaveLayersDialog;
[17556]114import org.openstreetmap.josm.gui.io.importexport.Options;
[12634]115import org.openstreetmap.josm.gui.layer.AutosaveTask;
[12718]116import org.openstreetmap.josm.gui.layer.Layer;
117import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
118import org.openstreetmap.josm.gui.layer.LayerManager.LayerChangeListener;
119import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
120import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
[12636]121import org.openstreetmap.josm.gui.layer.MainLayerManager;
[12718]122import org.openstreetmap.josm.gui.layer.OsmDataLayer;
[12906]123import org.openstreetmap.josm.gui.mappaint.RenderingCLI;
[12825]124import org.openstreetmap.josm.gui.mappaint.loader.MapPaintStyleLoader;
[12803]125import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
[12637]126import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
127import org.openstreetmap.josm.gui.preferences.display.LafPreference;
[12645]128import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
[6523]129import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
[12675]130import org.openstreetmap.josm.gui.progress.swing.ProgressMonitorExecutor;
[16050]131import org.openstreetmap.josm.gui.util.CheckThreadViolationRepaintManager;
[5796]132import org.openstreetmap.josm.gui.util.GuiHelper;
[12636]133import org.openstreetmap.josm.gui.util.RedirectInputMap;
[12678]134import org.openstreetmap.josm.gui.util.WindowGeometry;
[18985]135import org.openstreetmap.josm.gui.widgets.TextContextualPopupMenu;
[12766]136import org.openstreetmap.josm.gui.widgets.UrlLabel;
[12777]137import org.openstreetmap.josm.io.CachedFile;
[9995]138import org.openstreetmap.josm.io.CertificateAmendment;
[14326]139import org.openstreetmap.josm.io.ChangesetUpdater;
[2641]140import org.openstreetmap.josm.io.DefaultProxySelector;
[12825]141import org.openstreetmap.josm.io.FileWatcher;
[6349]142import org.openstreetmap.josm.io.MessageNotifier;
[14121]143import org.openstreetmap.josm.io.NetworkManager;
[7434]144import org.openstreetmap.josm.io.OnlineResource;
[12803]145import org.openstreetmap.josm.io.OsmConnection;
[12695]146import org.openstreetmap.josm.io.OsmTransferException;
[12821]147import org.openstreetmap.josm.io.auth.AbstractCredentialsAgent;
[4245]148import org.openstreetmap.josm.io.auth.CredentialsManager;
[2641]149import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
[10931]150import org.openstreetmap.josm.io.protocols.data.Handler;
[3707]151import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
[1326]152import org.openstreetmap.josm.plugins.PluginHandler;
[2817]153import org.openstreetmap.josm.plugins.PluginInformation;
[14125]154import org.openstreetmap.josm.spi.lifecycle.InitStatusListener;
155import org.openstreetmap.josm.spi.lifecycle.Lifecycle;
[12845]156import org.openstreetmap.josm.spi.preferences.Config;
[7383]157import org.openstreetmap.josm.tools.FontsManager;
[12766]158import org.openstreetmap.josm.tools.GBC;
[15229]159import org.openstreetmap.josm.tools.Http1Client;
160import org.openstreetmap.josm.tools.HttpClient;
[2017]161import org.openstreetmap.josm.tools.I18n;
[12637]162import org.openstreetmap.josm.tools.ImageProvider;
[12887]163import org.openstreetmap.josm.tools.JosmRuntimeException;
[10899]164import org.openstreetmap.josm.tools.Logging;
[6453]165import org.openstreetmap.josm.tools.OsmUrlToBounds;
[12695]166import org.openstreetmap.josm.tools.PlatformHook.NativeOsCallback;
[7335]167import org.openstreetmap.josm.tools.PlatformHookWindows;
[14138]168import org.openstreetmap.josm.tools.PlatformManager;
[14977]169import org.openstreetmap.josm.tools.ReflectionUtils;
[12629]170import org.openstreetmap.josm.tools.Shortcut;
[5868]171import org.openstreetmap.josm.tools.Utils;
[10055]172import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
[12770]173import org.openstreetmap.josm.tools.bugreport.BugReportQueue;
[12790]174import org.openstreetmap.josm.tools.bugreport.BugReportSender;
[12695]175import org.xml.sax.SAXException;
[1058]176
[283]177/**
178 * Main window class application.
179 *
180 * @author imi
181 */
[14253]182public class MainApplication {
[8415]183
[11650]184 /**
185 * Command-line arguments used to run the application.
186 */
[12869]187 private static volatile List<String> commandLineArgs;
[19012]188 /**
189 * The preference key for the startup failure counter
190 */
191 private static final String PREF_STARTUP_FAILURE_COUNTER = "josm.startup.failure.count";
[11650]192
[12630]193 /**
[12643]194 * The main menu bar at top of screen.
195 */
196 static MainMenu menu;
197
198 /**
[12642]199 * The main panel, required to be static for {@link MapFrameListener} handling.
[12639]200 */
201 static MainPanel mainPanel;
202
203 /**
204 * The private content pane of {@link MainFrame}, required to be static for shortcut handling.
205 */
206 static JComponent contentPanePrivate;
207
208 /**
[12630]209 * The MapFrame.
210 */
211 static MapFrame map;
212
[12637]213 /**
214 * The toolbar preference control to register new actions.
215 */
216 static volatile ToolbarPreferences toolbar;
217
[14153]218 private static MainFrame mainFrame;
[10340]219
[1169]220 /**
[12634]221 * The worker thread slave. This is for executing all long and intensive
222 * calculations. The executed runnables are guaranteed to be executed separately and sequential.
223 * @since 12634 (as a replacement to {@code Main.worker})
224 */
225 public static final ExecutorService worker = new ProgressMonitorExecutor("main-worker-%d", Thread.NORM_PRIORITY);
226
227 /**
[12642]228 * Provides access to the layers displayed in the main view.
[12641]229 */
[12642]230 private static final MainLayerManager layerManager = new MainLayerManager();
[12641]231
[12726]232 private static final LayerChangeListener undoRedoCleaner = new LayerChangeListener() {
233 @Override
234 public void layerRemoving(LayerRemoveEvent e) {
235 Layer layer = e.getRemovedLayer();
236 if (layer instanceof OsmDataLayer) {
[17399]237 UndoRedoHandler.getInstance().clean(((OsmDataLayer) layer).getDataSet());
[12726]238 }
239 }
240
241 @Override
242 public void layerOrderChanged(LayerOrderChangeEvent e) {
243 // Do nothing
244 }
245
246 @Override
247 public void layerAdded(LayerAddEvent e) {
248 // Do nothing
249 }
250 };
251
[14120]252 private static final ProjectionBoundsProvider mainBoundsProvider = new ProjectionBoundsProvider() {
253 @Override
254 public Bounds getRealBounds() {
255 return isDisplayingMapView() ? map.mapView.getRealBounds() : null;
256 }
257
258 @Override
259 public void restoreOldBounds(Bounds oldBounds) {
260 if (isDisplayingMapView()) {
261 map.mapView.zoomTo(oldBounds);
262 }
263 }
264 };
265
[12792]266 private static final List<CLIModule> cliModules = new ArrayList<>();
267
[12636]268 /**
[12792]269 * Default JOSM command line interface.
270 * <p>
271 * Runs JOSM and performs some action, depending on the options and positional
272 * arguments.
273 */
274 public static final CLIModule JOSM_CLI_MODULE = new CLIModule() {
275 @Override
276 public String getActionKeyword() {
277 return "runjosm";
278 }
279
280 @Override
281 public void processArguments(String[] argArray) {
282 try {
[18484]283 // construct argument table
284 ProgramArguments args = new ProgramArguments(argArray);
285 mainJOSM(args);
[12792]286 } catch (IllegalArgumentException e) {
287 System.err.println(e.getMessage());
[18366]288 Lifecycle.exitJosm(true, 1);
[12792]289 }
290 }
291 };
292
293 /**
[12638]294 * Listener that sets the enabled state of undo/redo menu entries.
295 */
[14139]296 final CommandQueueListener redoUndoListener = (queueSize, redoSize) -> {
[12638]297 menu.undo.setEnabled(queueSize > 0);
298 menu.redo.setEnabled(redoSize > 0);
299 };
300
301 /**
[12777]302 * Source of NTV2 shift files: Download from JOSM website.
303 * @since 12777
304 */
305 public static final NTV2GridShiftFileSource JOSM_WEBSITE_NTV2_SOURCE = gridFileName -> {
[14119]306 String location = Config.getUrls().getJOSMWebsite() + "/proj/" + gridFileName;
[12777]307 // Try to load grid file
[14125]308 @SuppressWarnings("resource")
[12777]309 CachedFile cf = new CachedFile(location);
310 try {
311 return cf.getInputStream();
312 } catch (IOException ex) {
313 Logging.warn(ex);
314 return null;
315 }
316 };
317
[12792]318 static {
[12886]319 registerCLIModule(JOSM_CLI_MODULE);
320 registerCLIModule(ProjectionCLI.INSTANCE);
[12906]321 registerCLIModule(RenderingCLI.INSTANCE);
[18365]322 registerCLIModule(ValidatorCLI.INSTANCE);
[12792]323 }
324
[12777]325 /**
[12792]326 * Register a command line interface module.
327 * @param module the module
[12886]328 * @since 12886
[12792]329 */
[12886]330 public static void registerCLIModule(CLIModule module) {
[12792]331 cliModules.add(module);
332 }
333
334 /**
[10340]335 * Constructs a new {@code MainApplication} without a window.
[1169]336 */
[8415]337 public MainApplication() {
[10340]338 this(null);
[8415]339 }
[1023]340
[1169]341 /**
[5829]342 * Constructs a main frame, ready sized and operating. Does not display the frame.
343 * @param mainFrame The main JFrame of the application
[10340]344 * @since 10340
[1169]345 */
[16623]346 @SuppressWarnings("StaticAssignmentInConstructor")
[10340]347 public MainApplication(MainFrame mainFrame) {
[14153]348 MainApplication.mainFrame = mainFrame;
[12726]349 getLayerManager().addLayerChangeListener(undoRedoCleaner);
[14120]350 ProjectionRegistry.setboundsProvider(mainBoundsProvider);
[14153]351 Lifecycle.setShutdownSequence(new MainTermination());
[1169]352 }
[283]353
[17679]354 private static void askUpdate(String title, String update, String property, String icon, StringBuilder content, String url) {
355 ExtendedDialog ed = new ExtendedDialog(mainFrame, title, tr("OK"), update, tr("Cancel"));
[12670]356 // Check if the dialog has not already been permanently hidden by user
[17679]357 if (!ed.toggleEnable(property).toggleCheckState()) {
358 ed.setButtonIcons("ok", icon, "cancel").setCancelButton(3);
[12670]359 ed.setMinimumSize(new Dimension(480, 300));
360 ed.setIcon(JOptionPane.WARNING_MESSAGE);
361 ed.setContent(content.toString());
362
363 if (ed.showDialog().getValue() == 2) {
364 try {
[14138]365 PlatformManager.getPlatform().openUrl(url);
[12670]366 } catch (IOException e) {
367 Logging.warn(e);
368 }
369 }
370 }
371 }
372
[12647]373 /**
[17679]374 * Asks user to update its version of Java.
375 * @param updVersion target update version
376 * @param url download URL
377 * @param major true for a migration towards a major version of Java (8:11), false otherwise
378 * @param eolDate the EOL/expiration date
379 * @since 12270
380 */
381 public static void askUpdateJava(String updVersion, String url, String eolDate, boolean major) {
[17793]382 StringBuilder content = new StringBuilder(256);
383 content.append(tr("You are running version {0} of Java.",
[17679]384 "<b>"+getSystemProperty("java.version")+"</b>")).append("<br><br>");
385 if ("Sun Microsystems Inc.".equals(getSystemProperty("java.vendor")) && !PlatformManager.getPlatform().isOpenJDK()) {
386 content.append("<b>").append(tr("This version is no longer supported by {0} since {1} and is not recommended for use.",
387 "Oracle", eolDate)).append("</b><br><br>");
388 }
389 content.append("<b>")
390 .append(major ?
391 tr("JOSM will soon stop working with this version; we highly recommend you to update to Java {0}.", updVersion) :
392 tr("You may face critical Java bugs; we highly recommend you to update to Java {0}.", updVersion))
393 .append("</b><br><br>")
394 .append(tr("Would you like to update now ?"));
[18115]395 askUpdate(tr("Outdated Java version"), tr("Update Java"), "askUpdateJava"+updVersion, /* ICON */"java", content, url);
[17679]396 }
397
398 /**
399 * Asks user to migrate to OpenWebStart
400 * @param url download URL
401 * @since 17679
402 */
403 public static void askMigrateWebStart(String url) {
404 // CHECKSTYLE.OFF: LineLength
405 StringBuilder content = new StringBuilder(tr("You are running an <b>Oracle</b> implementation of Java WebStart."))
406 .append("<br><br>")
407 .append(tr("It was for years the recommended way to use JOSM. Oracle removed WebStart from Java 11,<br>but the open source community reimplemented the Java Web Start technology as a new product: <b>OpenWebStart</b>"))
408 .append("<br><br>")
409 .append(tr("OpenWebStart is now considered mature enough by JOSM developers to ask everyone to move away from an Oracle implementation,<br>allowing you to benefit from a recent version of Java, and allowing JOSM developers to move forward by planning the Java {0} migration.", "11"))
410 .append("<br><br>")
411 .append(tr("Would you like to <b>download OpenWebStart now</b>? (Please do!)"));
[18115]412 askUpdate(tr("Outdated Java WebStart version"), tr("Update to OpenWebStart"), "askUpdateWebStart", /* ICON */"presets/transport/rocket", content, url);
[17679]413 // CHECKSTYLE.ON: LineLength
414 }
415
416 /**
[18985]417 * Tells the user that a sanity check failed
418 * @param title The title of the message to show
419 * @param canContinue {@code true} if the failed sanity check(s) will not instantly kill JOSM when the user edits
420 * @param message The message parts to show the user (as a list)
421 */
422 public static void sanityCheckFailed(String title, boolean canContinue, String... message) {
423 final ExtendedDialog ed;
424 if (canContinue) {
[19019]425 ed = new ExtendedDialog(mainFrame, title, trc("dialog", "Stop"), tr("Continue"));
[18986]426 ed.setButtonIcons("cancel", "apply");
[18985]427 } else {
[19019]428 ed = new ExtendedDialog(mainFrame, title, trc("dialog", "Stop"));
[18985]429 ed.setButtonIcons("cancel");
430 }
431 ed.setDefaultButton(1).setCancelButton(1);
432 // Check if the dialog has not already been permanently hidden by user
[18999]433 ed.toggleEnable("sanityCheckFailed");
434 final String content = Arrays.stream(message).collect(Collectors.joining("</li><li>",
435 "<html><body><ul><li>", "</li></ul></body></html>"));
436 final JTextPane textField = new JTextPane();
437 textField.setContentType("text/html");
438 textField.setText(content);
439 TextContextualPopupMenu.enableMenuFor(textField, true);
440 ed.setMinimumSize(new Dimension(480, 300));
441 ed.setIcon(JOptionPane.WARNING_MESSAGE);
442 ed.setContent(textField);
443 ed.showDialog(); // This won't show the dialog if the user has previously saved their response
[18985]444 if (!canContinue || ed.getValue() <= 1) { // 0 == cancel (we want to stop) and 1 == stop
[18998]445 // Never store cancel/stop -- this would otherwise lead to the user never seeing the window again, and JOSM just stopping.
446 if (ConditionalOptionPaneUtil.getDialogReturnValue("sanityCheckFailed") != -1) {
447 Config.getPref().put("message.sanityCheckFailed", null);
448 Config.getPref().put("message.sanityCheckFailed.value", null);
449 }
[18985]450 Lifecycle.exitJosm(true, -1);
451 }
452 }
453
454 /**
[12647]455 * Called once at startup to initialize the main window content.
456 * Should set {@link #menu} and {@link #mainPanel}
457 */
[10340]458 protected void initializeMainWindow() {
459 if (mainFrame != null) {
[12642]460 mainPanel = mainFrame.getPanel();
[10340]461 mainFrame.initialize();
462 menu = mainFrame.getMenu();
463 } else {
464 // required for running some tests.
[12642]465 mainPanel = new MainPanel(layerManager);
[10340]466 menu = new MainMenu();
467 }
[12642]468 mainPanel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
469 mainPanel.reAddListeners();
[10340]470 }
471
[14140]472 /**
473 * Returns the JOSM main frame.
474 * @return the JOSM main frame
475 * @since 14140
476 */
[14153]477 public static MainFrame getMainFrame() {
[14140]478 return mainFrame;
[10340]479 }
480
[14143]481 /**
[11650]482 * Returns the command-line arguments used to run the application.
483 * @return the command-line arguments used to run the application
484 * @since 11650
485 */
486 public static List<String> getCommandLineArgs() {
[16225]487 return commandLineArgs == null
488 ? Collections.emptyList()
489 : Collections.unmodifiableList(commandLineArgs);
[11650]490 }
491
492 /**
[12636]493 * Returns the main layer manager that is used by the map view.
494 * @return The layer manager. The value returned will never change.
[12637]495 * @since 12636 (as a replacement to {@code Main.getLayerManager()})
[12636]496 */
497 public static MainLayerManager getLayerManager() {
498 return layerManager;
499 }
500
501 /**
[12630]502 * Returns the MapFrame.
503 * <p>
504 * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
505 * @return the MapFrame
506 * @see MainPanel
[14143]507 * @since 12630
[12630]508 */
509 public static MapFrame getMap() {
510 return map;
511 }
512
513 /**
[12642]514 * Returns the main panel.
515 * @return the main panel
[14143]516 * @since 12642
[12642]517 */
518 public static MainPanel getMainPanel() {
519 return mainPanel;
520 }
521
522 /**
[12643]523 * Returns the main menu, at top of screen.
524 * @return the main menu
525 * @since 12643 (as a replacement to {@code MainApplication.getMenu()})
526 */
527 public static MainMenu getMenu() {
528 return menu;
529 }
530
531 /**
[12637]532 * Returns the toolbar preference control to register new actions.
533 * @return the toolbar preference control
[14143]534 * @since 12637
[12637]535 */
536 public static ToolbarPreferences getToolbar() {
537 return toolbar;
538 }
539
540 /**
[12630]541 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
542 * it only shows the MOTD panel.
543 * <p>
544 * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
545 *
546 * @return <code>true</code> if JOSM currently displays a map view
547 * @since 12630 (as a replacement to {@code Main.isDisplayingMapView()})
548 */
549 public static boolean isDisplayingMapView() {
550 return map != null && map.mapView != null;
551 }
552
553 /**
[12636]554 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
555 * If there are some unsaved data layers, asks first for user confirmation.
556 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
557 * @param exitCode The return code
558 * @param reason the reason for exiting
559 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
[14146]560 * @since 12636 (specialized version of {@link Lifecycle#exitJosm})
[12636]561 */
562 public static boolean exitJosm(boolean exit, int exitCode, SaveLayersDialog.Reason reason) {
[18570]563 final boolean proceed = layerManager.getLayers().isEmpty() ||
564 Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
[12637]565 SaveLayersDialog.saveUnsavedModifications(layerManager.getLayers(),
[12636]566 reason != null ? reason : SaveLayersDialog.Reason.EXIT)));
567 if (proceed) {
[14140]568 return Lifecycle.exitJosm(exit, exitCode);
[12636]569 }
570 return false;
571 }
572
[14125]573 /**
574 * Redirects the key inputs from {@code source} to main content pane.
575 * @param source source component from which key inputs are redirected
576 */
[12636]577 public static void redirectToMainContentPane(JComponent source) {
578 RedirectInputMap.redirect(source, contentPanePrivate);
579 }
580
581 /**
[12639]582 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes.
583 * <p>
584 * It will fire an initial mapFrameInitialized event when the MapFrame is present.
585 * Otherwise will only fire when the MapFrame is created or destroyed.
586 * @param listener The MapFrameListener
587 * @return {@code true} if the listeners collection changed as a result of the call
588 * @see #addMapFrameListener
589 * @since 12639 (as a replacement to {@code Main.addAndFireMapFrameListener})
590 */
591 public static boolean addAndFireMapFrameListener(MapFrameListener listener) {
592 return mainPanel != null && mainPanel.addAndFireMapFrameListener(listener);
593 }
594
595 /**
596 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
597 * @param listener The MapFrameListener
598 * @return {@code true} if the listeners collection changed as a result of the call
599 * @see #addAndFireMapFrameListener
600 * @since 12639 (as a replacement to {@code Main.addMapFrameListener})
601 */
602 public static boolean addMapFrameListener(MapFrameListener listener) {
603 return mainPanel != null && mainPanel.addMapFrameListener(listener);
604 }
605
606 /**
607 * Unregisters the given {@code MapFrameListener} from MapFrame changes
608 * @param listener The MapFrameListener
609 * @return {@code true} if the listeners collection changed as a result of the call
610 * @since 12639 (as a replacement to {@code Main.removeMapFrameListener})
611 */
612 public static boolean removeMapFrameListener(MapFrameListener listener) {
613 return mainPanel != null && mainPanel.removeMapFrameListener(listener);
614 }
615
616 /**
617 * Registers a {@code JosmAction} and its shortcut.
618 * @param action action defining its own shortcut
619 * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
620 */
621 public static void registerActionShortcut(JosmAction action) {
622 registerActionShortcut(action, action.getShortcut());
623 }
624
625 /**
626 * Registers an action and its shortcut.
627 * @param action action to register
628 * @param shortcut shortcut to associate to {@code action}
629 * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
630 */
631 public static void registerActionShortcut(Action action, Shortcut shortcut) {
632 KeyStroke keyStroke = shortcut.getKeyStroke();
633 if (keyStroke == null)
634 return;
635
636 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
637 Object existing = inputMap.get(keyStroke);
638 if (existing != null && !existing.equals(action)) {
639 Logging.info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
640 }
641 inputMap.put(keyStroke, action);
642
643 contentPanePrivate.getActionMap().put(action, action);
644 }
645
646 /**
647 * Unregisters a shortcut.
648 * @param shortcut shortcut to unregister
649 * @since 12639 (as a replacement to {@code Main.unregisterShortcut})
650 */
651 public static void unregisterShortcut(Shortcut shortcut) {
652 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
653 }
654
655 /**
656 * Unregisters a {@code JosmAction} and its shortcut.
657 * @param action action to unregister
658 * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
659 */
660 public static void unregisterActionShortcut(JosmAction action) {
661 unregisterActionShortcut(action, action.getShortcut());
662 }
663
664 /**
665 * Unregisters an action and its shortcut.
666 * @param action action to unregister
667 * @param shortcut shortcut to unregister
668 * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
669 */
670 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
671 unregisterShortcut(shortcut);
672 contentPanePrivate.getActionMap().remove(action);
673 }
674
675 /**
676 * Replies the registered action for the given shortcut
677 * @param shortcut The shortcut to look for
678 * @return the registered action for the given shortcut
679 * @since 12639 (as a replacement to {@code Main.getRegisteredActionShortcut})
680 */
681 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
682 KeyStroke keyStroke = shortcut.getKeyStroke();
683 if (keyStroke == null)
684 return null;
685 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
686 if (action instanceof Action)
687 return (Action) action;
688 return null;
689 }
690
691 /**
[2748]692 * Displays help on the console
[6143]693 * @since 2748
[2748]694 */
695 public static void showHelp() {
696 // TODO: put in a platformHook for system that have no console by default
[10983]697 System.out.println(getHelp());
698 }
699
700 static String getHelp() {
[16446]701 // IMPORTANT: when changing the help texts, also update:
702 // - native/linux/tested/usr/share/man/man1/josm.1
703 // - native/linux/latest/usr/share/man/man1/josm-latest.1
[10983]704 return tr("Java OpenStreetMap Editor")+" ["
[5363]705 +Version.getInstance().getAgentString()+"]\n\n"+
[2748]706 tr("usage")+":\n"+
[12911]707 "\tjava -jar josm.jar [<command>] <options>...\n\n"+
708 tr("commands")+":\n"+
709 "\trunjosm "+tr("launch JOSM (default, performed when no command is specified)")+'\n'+
710 "\trender "+tr("render data and save the result to an image file")+'\n'+
[18365]711 "\tproject " + tr("convert coordinates from one coordinate reference system to another")+ '\n' +
712 "\tvalidate " + tr("validate data") + "\n\n" +
[12911]713 tr("For details on the {0} and {1} commands, run them with the {2} option.", "render", "project", "--help")+'\n'+
714 tr("The remainder of this help page documents the {0} command.", "runjosm")+"\n\n"+
[2748]715 tr("options")+":\n"+
[8846]716 "\t--help|-h "+tr("Show this help")+'\n'+
717 "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+'\n'+
718 "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+'\n'+
719 "\t[--download=]<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z)")+'\n'+
720 "\t[--download=]<filename> "+tr("Open a file (any file type that can be opened with File/Open)")+'\n'+
721 "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw GPS")+'\n'+
722 "\t--downloadgps=<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z) as raw GPS")+'\n'+
723 "\t--selection=<searchstring> "+tr("Select with the given search")+'\n'+
724 "\t--[no-]maximize "+tr("Launch in maximized mode")+'\n'+
[2748]725 "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+
[5201]726 "\t--load-preferences=<url-to-xml> "+tr("Changes preferences according to the XML file")+"\n\n"+
[4789]727 "\t--set=<key>=<value> "+tr("Set preference key to value")+"\n\n"+
[2800]728 "\t--language=<language> "+tr("Set the language")+"\n\n"+
[5365]729 "\t--version "+tr("Displays the JOSM version and exits")+"\n\n"+
[17637]730 "\t--status-report "+ShowStatusReportAction.ACTION_DESCRIPTION+"\n\n"+
[6730]731 "\t--debug "+tr("Print debugging messages to console")+"\n\n"+
[8169]732 "\t--skip-plugins "+tr("Skip loading plugins")+"\n\n"+
[16430]733 "\t--offline=" + Arrays.stream(OnlineResource.values()).map(OnlineResource::name).collect(
734 Collectors.joining("|", "<", ">")) + "\n" +
735 "\t "+tr("Disable access to the given resource(s), separated by comma") + "\n" +
736 "\t "+Arrays.stream(OnlineResource.values()).map(OnlineResource::getLocName).collect(
737 Collectors.joining("|", "<", ">")) + "\n\n" +
[2748]738 tr("options provided as Java system properties")+":\n"+
[11255]739 align("\t-Djosm.dir.name=JOSM") + tr("Change the JOSM directory name") + "\n\n" +
740 align("\t-Djosm.pref=" + tr("/PATH/TO/JOSM/PREF ")) + tr("Set the preferences directory") + "\n" +
[14138]741 align("\t") + tr("Default: {0}", PlatformManager.getPlatform().getDefaultPrefDirectory()) + "\n\n" +
[11255]742 align("\t-Djosm.userdata=" + tr("/PATH/TO/JOSM/USERDATA")) + tr("Set the user data directory") + "\n" +
[14138]743 align("\t") + tr("Default: {0}", PlatformManager.getPlatform().getDefaultUserDataDirectory()) + "\n\n" +
[11255]744 align("\t-Djosm.cache=" + tr("/PATH/TO/JOSM/CACHE ")) + tr("Set the cache directory") + "\n" +
[14138]745 align("\t") + tr("Default: {0}", PlatformManager.getPlatform().getDefaultCacheDirectory()) + "\n\n" +
[11255]746 align("\t-Djosm.home=" + tr("/PATH/TO/JOSM/HOMEDIR ")) +
747 tr("Set the preferences+data+cache directory (cache directory will be josm.home/cache)")+"\n\n"+
[7843]748 tr("-Djosm.home has lower precedence, i.e. the specific setting overrides the general one")+"\n\n"+
[2748]749 tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
[4720]750 " Java option to specify the maximum size of allocated memory in megabytes")+":\n"+
751 "\t-Xmx...m\n\n"+
[10983]752 tr("examples")+":\n"+
753 "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
754 "\tjava -jar josm.jar "+OsmUrlToBounds.getURL(43.2, 11.1, 13)+'\n'+
755 "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
756 "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
757 "\tjava -Djosm.pref=$XDG_CONFIG_HOME -Djosm.userdata=$XDG_DATA_HOME -Djosm.cache=$XDG_CACHE_HOME -jar josm.jar\n"+
[11255]758 "\tjava -Djosm.dir.name=josm_dev -jar josm.jar\n"+
[10983]759 "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
760 "\tjava -Xmx1024m -jar josm.jar\n\n"+
761 tr("Parameters --download, --downloadgps, and --selection are processed in this order.")+'\n'+
762 tr("Make sure you load some data if you use --selection.")+'\n';
[2748]763 }
764
[11255]765 private static String align(String str) {
766 return str + Stream.generate(() -> " ").limit(Math.max(0, 43 - str.length())).collect(Collectors.joining(""));
767 }
768
[6143]769 /**
[2856]770 * Main application Startup
[5829]771 * @param argArray Command-line arguments
[2856]772 */
773 public static void main(final String[] argArray) {
774 I18n.init();
[12792]775 commandLineArgs = Arrays.asList(Arrays.copyOf(argArray, argArray.length));
[6108]776
[12792]777 if (argArray.length > 0) {
778 String moduleStr = argArray[0];
779 for (CLIModule module : cliModules) {
780 if (Objects.equals(moduleStr, module.getActionKeyword())) {
781 String[] argArrayCdr = Arrays.copyOfRange(argArray, 1, argArray.length);
782 module.processArguments(argArrayCdr);
783 return;
784 }
785 }
[6108]786 }
[12792]787 // no module specified, use default (josm)
788 JOSM_CLI_MODULE.processArguments(argArray);
789 }
[6830]790
[12792]791 /**
792 * Main method to run the JOSM GUI.
793 * @param args program arguments
794 */
795 public static void mainJOSM(ProgramArguments args) {
796
[12770]797 if (!GraphicsEnvironment.isHeadless()) {
798 BugReportQueue.getInstance().setBugReportHandler(BugReportDialog::showFor);
[14176]799 BugReportSender.setBugReportSendingHandler(new DefaultBugReportSendingHandler());
[12770]800 }
801
[10899]802 Level logLevel = args.getLogLevel();
803 Logging.setLogLevel(logLevel);
[17637]804 if (!args.hasOption(Option.VERSION) && !args.hasOption(Option.STATUS_REPORT) && !args.showHelp()) {
[12620]805 Logging.info(tr("Log level is at {0} ({1}, {2})", logLevel.getLocalizedName(), logLevel.getName(), logLevel.intValue()));
[10983]806 }
[6108]807
[10899]808 Optional<String> language = args.getSingle(Option.LANGUAGE);
809 I18n.set(language.orElse(null));
[6108]810
[13647]811 try {
812 Policy.setPolicy(new Policy() {
813 // Permissions for plug-ins loaded when josm is started via webstart
[16913]814 private final PermissionCollection pc;
[3232]815
[13647]816 {
817 pc = new Permissions();
818 pc.add(new AllPermission());
819 }
[3232]820
[13647]821 @Override
822 public PermissionCollection getPermissions(CodeSource codesource) {
823 return pc;
824 }
825 });
826 } catch (SecurityException e) {
827 Logging.log(Logging.LEVEL_ERROR, "Unable to set permissions", e);
828 }
[3232]829
[13647]830 try {
831 Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
832 } catch (SecurityException e) {
833 Logging.log(Logging.LEVEL_ERROR, "Unable to set uncaught exception handler", e);
834 }
[2856]835
[3815]836 // initialize the platform hook, and
[14138]837 PlatformManager.getPlatform().setNativeOsCallback(new DefaultNativeOsCallback());
[4259]838 // call the really early hook before we do anything else
[14138]839 PlatformManager.getPlatform().preStartupHook();
[2856]840
[14149]841 Preferences prefs = Preferences.main();
842 Config.setPreferencesInstance(prefs);
[13396]843 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
[14119]844 Config.setUrlsProvider(JosmUrls.getInstance());
[13396]845
[17637]846 if (args.hasOption(Option.VERSION)) {
[4259]847 System.out.println(Version.getInstance().getAgentString());
[10983]848 return;
[17637]849 } else if (args.hasOption(Option.STATUS_REPORT)) {
[17668]850 Preferences.main().enableSaveOnPut(false);
851 Preferences.main().init(false);
[17637]852 System.out.println(ShowStatusReportAction.getReportHeader());
853 return;
[10899]854 } else if (args.showHelp()) {
855 showHelp();
[10983]856 return;
[6108]857 }
[4259]858
[12150]859 boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
[10899]860 if (skipLoadingPlugins) {
[12620]861 Logging.info(tr("Plugin loading skipped"));
[8169]862 }
863
[10899]864 if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
865 // Enable debug in OAuth signpost via system preference, but only at trace level
866 Utils.updateSystemProperty("debug", "true");
[12620]867 Logging.info(tr("Enabled detailed debug level (trace)"));
[8296]868 }
869
[13647]870 try {
[14149]871 Preferences.main().init(args.hasOption(Option.RESET_PREFERENCES));
[13647]872 } catch (SecurityException e) {
873 Logging.log(Logging.LEVEL_ERROR, "Unable to initialize preferences", e);
874 }
[10899]875
[14149]876 args.getPreferencesToSet().forEach(prefs::put);
[10899]877
878 if (!language.isPresent()) {
[12845]879 I18n.set(Config.getPref().get("language", null));
[2025]880 }
[13021]881 updateSystemProperties();
[14154]882 Preferences.main().addPreferenceChangeListener(e -> updateSystemProperties());
[1326]883
[8296]884 checkIPv6();
885
[19012]886 // After IPv6 check since that may restart JOSM, must be after Preferences.main().init()
887 final int failures = prefs.getInt(PREF_STARTUP_FAILURE_COUNTER, 0);
888 // Always increment failures
889 prefs.putInt(PREF_STARTUP_FAILURE_COUNTER, failures + 1);
890 if (failures > 3) {
891 final int selection = JOptionPane.showOptionDialog(new JDialog(),
892 tr("JOSM has failed to start up {0} times. Reset JOSM?", failures),
893 tr("Reset JOSM?"),
894 JOptionPane.YES_NO_OPTION,
895 JOptionPane.ERROR_MESSAGE,
896 null,
897 null,
898 null);
899 if (selection == JOptionPane.YES_OPTION) {
900 Preferences.main().init(true);
901 }
902 }
903
[7434]904 processOffline(args);
905
[14138]906 PlatformManager.getPlatform().afterPrefStartupHook();
[8015]907
[7383]908 FontsManager.initialize();
[7434]909
[12644]910 GuiHelper.setupLanguageFonts();
[7896]911
[10931]912 Handler.install();
913
[17704]914 WindowGeometry geometry = WindowGeometry.mainWindow(WindowGeometry.PREF_KEY_GUI_GEOMETRY,
[10899]915 args.getSingle(Option.GEOMETRY).orElse(null),
[12845]916 !args.hasOption(Option.NO_MAXIMIZE) && Config.getPref().getBoolean("gui.maximized", false));
[14177]917 final MainFrame mainFrame = createMainFrame(geometry);
[12808]918 final Container contentPane = mainFrame.getContentPane();
919 if (contentPane instanceof JComponent) {
920 contentPanePrivate = (JComponent) contentPane;
[12133]921 }
[18561]922 // This should never happen, but it does. See #22183.
923 // Hopefully this code block will be temporary until we figure out what is actually going on.
924 if (!GraphicsEnvironment.isHeadless() && contentPanePrivate == null) {
925 throw new JosmRuntimeException("MainFrame contentPane is " + (contentPane == null ? "null" : contentPane.getClass().getName()));
926 }
[12639]927 mainPanel = mainFrame.getPanel();
[5201]928
[10899]929 if (args.hasOption(Option.LOAD_PREFERENCES)) {
[14149]930 XMLCommandProcessor config = new XMLCommandProcessor(prefs);
[5279]931 for (String i : args.get(Option.LOAD_PREFERENCES)) {
[13402]932 try {
[13445]933 URL url = i.contains(":/") ? new URL(i) : Paths.get(i).toUri().toURL();
[13402]934 Logging.info("Reading preferences from " + url);
935 try (InputStream is = Utils.openStream(url)) {
936 config.openAndReadXML(is);
937 }
[13443]938 } catch (IOException | InvalidPathException ex) {
[13402]939 Logging.error(ex);
940 return;
[5201]941 }
942 }
943 }
944
[9995]945 try {
946 CertificateAmendment.addMissingCertificates();
[17079]947 } catch (IOException | GeneralSecurityException | SecurityException | ExceptionInInitializerError ex) {
[12620]948 Logging.warn(ex);
949 Logging.warn(Logging.getErrorMessage(Utils.getRootCause(ex)));
[9995]950 }
[13647]951 try {
952 Authenticator.setDefault(DefaultAuthenticator.getInstance());
953 } catch (SecurityException e) {
954 Logging.log(Logging.LEVEL_ERROR, "Unable to set default authenticator", e);
955 }
956 DefaultProxySelector proxySelector = null;
957 try {
958 proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
959 } catch (SecurityException e) {
960 Logging.log(Logging.LEVEL_ERROR, "Unable to get default proxy selector", e);
961 }
962 try {
963 if (proxySelector != null) {
964 ProxySelector.setDefault(proxySelector);
965 }
966 } catch (SecurityException e) {
967 Logging.log(Logging.LEVEL_ERROR, "Unable to set default proxy selector", e);
968 }
[12928]969 OAuthAccessTokenHolder.getInstance().init(CredentialsManager.getInstance());
[2641]970
[12749]971 setupCallbacks();
972
[16974]973 if (!skipLoadingPlugins) {
974 PluginHandler.loadVeryEarlyPlugins();
975 }
[16498]976 // Configure Look and feel before showing SplashScreen (#19290)
977 setupUIManager();
[18751]978 // Then apply LaF workarounds
979 applyLaFWorkarounds();
[17796]980 // MainFrame created before setting look and feel and not updated (#20771)
981 SwingUtilities.updateComponentTreeUI(mainFrame);
[16498]982
[10611]983 final SplashScreen splash = GuiHelper.runInEDTAndWaitAndReturn(SplashScreen::new);
[13960]984 // splash can be null sometimes on Linux, in this case try to load JOSM silently
985 final SplashProgressMonitor monitor = splash != null ? splash.getProgressMonitor() : new SplashProgressMonitor(null, e -> {
[13963]986 if (e != null) {
987 Logging.debug(e.toString());
988 }
[13960]989 });
[2817]990 monitor.beginTask(tr("Initializing"));
[13960]991 if (splash != null) {
992 GuiHelper.runInEDT(() -> splash.setVisible(Config.getPref().getBoolean("draw.splashscreen", true)));
993 }
[14125]994 Lifecycle.setInitStatusListener(new InitStatusListener() {
[1023]995
[4681]996 @Override
[8497]997 public Object updateStatus(String event) {
998 monitor.beginTask(event);
999 return event;
[4681]1000 }
[8497]1001
1002 @Override
1003 public void finish(Object status) {
1004 if (status instanceof String) {
1005 monitor.finishTask((String) status);
1006 }
1007 }
[4681]1008 });
1009
[8169]1010 Collection<PluginInformation> pluginsToLoad = null;
[283]1011
[8169]1012 if (!skipLoadingPlugins) {
[10093]1013 pluginsToLoad = updateAndLoadEarlyPlugins(splash, monitor);
[8169]1014 }
1015
[4681]1016 monitor.indeterminateSubTask(tr("Setting defaults"));
[12637]1017 toolbar = new ToolbarPreferences();
[12645]1018 ProjectionPreference.setProjection();
[12795]1019 setupNadGridSources();
[12644]1020 GuiHelper.translateJavaInternalMessages();
[2817]1021
1022 monitor.indeterminateSubTask(tr("Creating main GUI"));
[14139]1023 Lifecycle.initialize(new MainInitialization(new MainApplication(mainFrame)));
[2817]1024
[8169]1025 if (!skipLoadingPlugins) {
[10093]1026 loadLatePlugins(splash, monitor, pluginsToLoad);
[8169]1027 }
[5796]1028
[6866]1029 // Wait for splash disappearance (fix #9714)
[10611]1030 GuiHelper.runInEDTAndWait(() -> {
[13960]1031 if (splash != null) {
1032 splash.setVisible(false);
1033 splash.dispose();
1034 }
[10611]1035 mainFrame.setVisible(true);
[19012]1036 Config.getPref().put(PREF_STARTUP_FAILURE_COUNTER, null);
[5796]1037 });
1038
[12845]1039 boolean maximized = Config.getPref().getBoolean("gui.maximized", false);
[10899]1040 if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
[10340]1041 mainFrame.setMaximized(true);
[2025]1042 }
[13173]1043 if (menu.fullscreenToggleAction != null) {
1044 menu.fullscreenToggleAction.initial();
[4720]1045 }
[1023]1046
[6523]1047 SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
[5279]1048
[19050]1049 if (Boolean.TRUE.equals(RemoteControl.PROP_REMOTECONTROL_ENABLED.get())) {
[3959]1050 RemoteControl.start();
1051 }
[6830]1052
[19050]1053 if (Boolean.TRUE.equals(MessageNotifier.PROP_NOTIFIER_ENABLED.get())) {
[6349]1054 MessageNotifier.start();
1055 }
[3959]1056
[14326]1057 ChangesetUpdater.start();
1058
[12845]1059 if (Config.getPref().getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
[18801]1060 // Repaint manager is registered so late for a reason - there are lots of violations during startup process
[8509]1061 // but they don't seem to break anything and are difficult to fix
[12620]1062 Logging.info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
[4720]1063 RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
1064 }
[1169]1065 }
[6523]1066
[14177]1067 private static MainFrame createMainFrame(WindowGeometry geometry) {
1068 try {
1069 return new MainFrame(geometry);
1070 } catch (AWTError e) {
1071 // #12022 #16666 On Debian, Ubuntu and Linux Mint the first AWT toolkit access can fail because of ATK wrapper
1072 // Good news: the error happens after the toolkit initialization so we can just try again and it will work
1073 Logging.error(e);
1074 return new MainFrame(geometry);
1075 }
1076 }
1077
[12795]1078 /**
[13021]1079 * Updates system properties with the current values in the preferences.
1080 */
1081 private static void updateSystemProperties() {
1082 if ("true".equals(Config.getPref().get("prefer.ipv6", "auto"))
1083 && !"true".equals(Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true"))) {
1084 // never set this to false, only true!
[14273]1085 Logging.info(tr("Try enabling IPv6 network, preferring IPv6 over IPv4 (only works on early startup)."));
[13021]1086 }
1087 Utils.updateSystemProperty("http.agent", Version.getInstance().getAgentString());
1088 Utils.updateSystemProperty("user.language", Config.getPref().get("language"));
1089 // Workaround to fix a Java bug. This ugly hack comes from Sun bug database: https://bugs.openjdk.java.net/browse/JDK-6292739
1090 // Force AWT toolkit to update its internal preferences (fix #6345).
1091 // Does not work anymore with Java 9, to remove with Java 9 migration
1092 if (Utils.getJavaVersion() < 9 && !GraphicsEnvironment.isHeadless()) {
1093 try {
1094 Field field = Toolkit.class.getDeclaredField("resources");
[14977]1095 ReflectionUtils.setObjectsAccessible(field);
[13021]1096 field.set(null, ResourceBundle.getBundle("sun.awt.resources.awt"));
1097 } catch (ReflectiveOperationException | RuntimeException e) { // NOPMD
1098 // Catch RuntimeException in order to catch InaccessibleObjectException, new in Java 9
[13647]1099 Logging.log(Logging.LEVEL_WARN, null, e);
[13021]1100 }
1101 }
1102 // Possibility to disable SNI (not by default) in case of misconfigured https servers
1103 // See #9875 + http://stackoverflow.com/a/14884941/2257172
1104 // then https://josm.openstreetmap.de/ticket/12152#comment:5 for details
1105 if (Config.getPref().getBoolean("jdk.tls.disableSNIExtension", false)) {
1106 Utils.updateSystemProperty("jsse.enableSNIExtension", "false");
1107 }
[15222]1108 // Disable automatic POST retry after 5 minutes, see #17882 / https://bugs.openjdk.java.net/browse/JDK-6382788
1109 Utils.updateSystemProperty("sun.net.http.retryPost", "false");
[18322]1110 if (Utils.getJavaVersion() >= 17) {
1111 // Allow security manager, otherwise it raises a warning in Java 17 and throws an error with Java 18+
1112 // See https://bugs.openjdk.java.net/browse/JDK-8271301 / https://bugs.openjdk.java.net/browse/JDK-8270380
1113 Utils.updateSystemProperty("java.security.manager", "allow");
1114 }
[13021]1115 }
1116
1117 /**
[12795]1118 * Setup the sources for NTV2 grid shift files for projection support.
1119 * @since 12795
1120 */
1121 public static void setupNadGridSources() {
1122 NTV2GridShiftFileWrapper.registerNTV2GridShiftFileSource(
1123 NTV2GridShiftFileWrapper.NTV2_SOURCE_PRIORITY_LOCAL,
1124 NTV2Proj4DirGridShiftFileSource.getInstance());
1125 NTV2GridShiftFileWrapper.registerNTV2GridShiftFileSource(
1126 NTV2GridShiftFileWrapper.NTV2_SOURCE_PRIORITY_DOWNLOAD,
1127 JOSM_WEBSITE_NTV2_SOURCE);
1128 }
1129
[18751]1130 /**
1131 * Apply workarounds for LaF and platform specific issues. This must be called <i>after</i> the
1132 * LaF is set.
1133 */
1134 static void applyLaFWorkarounds() {
[17681]1135 final String laf = UIManager.getLookAndFeel().getID();
1136 final int javaVersion = Utils.getJavaVersion();
[12744]1137 // Workaround for JDK-8180379: crash on Windows 10 1703 with Windows L&F and java < 8u141 / 9+172
1138 // To remove during Java 9 migration
[13647]1139 if (getSystemProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows 10") &&
[14138]1140 PlatformManager.getPlatform().getDefaultStyle().equals(LafPreference.LAF.get())) {
[12744]1141 try {
[13651]1142 String build = PlatformHookWindows.getCurrentBuild();
1143 if (build != null) {
1144 final int currentBuild = Integer.parseInt(build);
1145 final int javaUpdate = Utils.getJavaUpdate();
1146 final int javaBuild = Utils.getJavaBuild();
1147 // See https://technet.microsoft.com/en-us/windows/release-info.aspx
1148 if (currentBuild >= 15_063 && ((javaVersion == 8 && javaUpdate < 141)
1149 || (javaVersion == 9 && javaUpdate == 0 && javaBuild < 173))) {
1150 // Workaround from https://bugs.openjdk.java.net/browse/JDK-8179014
1151 UIManager.put("FileChooser.useSystemExtensionHiding", Boolean.FALSE);
1152 }
[12744]1153 }
[12887]1154 } catch (NumberFormatException | ReflectiveOperationException | JosmRuntimeException e) {
[12744]1155 Logging.error(e);
[13647]1156 } catch (ExceptionInInitializerError e) {
1157 Logging.log(Logging.LEVEL_ERROR, null, e);
[12744]1158 }
[17835]1159 } else if (PlatformManager.isPlatformOsx() && javaVersion < 17) {
1160 // Workaround for JDK-8251377: JTabPanel active tab is unreadable in Big Sur, see #20075, see #20821
[17488]1161 // os.version will return 10.16, or 11.0 depending on environment variable
1162 // https://twitter.com/BriceDutheil/status/1330926649269956612
[17487]1163 final String macOSVersion = getSystemProperty("os.version");
[17545]1164 if ((laf.contains("Mac") || laf.contains("Aqua"))
[17488]1165 && (macOSVersion.startsWith("10.16") || macOSVersion.startsWith("11"))) {
[17487]1166 UIManager.put("TabbedPane.foreground", Color.BLACK);
1167 }
[12744]1168 }
[17681]1169 // Workaround for JDK-8262085
1170 if ("Metal".equals(laf) && javaVersion >= 11 && javaVersion < 17) {
1171 UIManager.put("ToolTipUI", JosmMetalToolTipUI.class.getCanonicalName());
1172 }
[18751]1173
1174 // See #20850. The upstream bug (JDK-6396936) is unlikely to ever be fixed due to potential compatibility
1175 // issues. This affects Windows LaF only (includes Windows Classic, a sub-LaF of Windows LaF).
1176 if ("Windows".equals(laf) && "Monospaced".equals(UIManager.getFont("TextArea.font").getFamily())) {
1177 UIManager.put("TextArea.font", UIManager.getFont("TextField.font"));
1178 }
[12744]1179 }
1180
[12749]1181 static void setupCallbacks() {
[15229]1182 HttpClient.setFactory(Http1Client::new);
[12803]1183 OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);
[12821]1184 AbstractCredentialsAgent.setCredentialsProvider(CredentialDialog::promptCredentials);
[12766]1185 MessageNotifier.setNotifierCallback(MainApplication::notifyNewMessages);
[12760]1186 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
[12828]1187 SplitWayCommand.setWarningNotifier(msg -> new Notification(msg).setIcon(JOptionPane.WARNING_MESSAGE).show());
[12825]1188 FileWatcher.registerLoader(SourceType.MAP_PAINT_STYLE, MapPaintStyleLoader::reloadStyle);
1189 FileWatcher.registerLoader(SourceType.TAGCHECKER_RULE, MapCSSTagChecker::reloadRule);
[12796]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 });
[12749]1198 }
1199
[18598]1200 /**
1201 * Set up the UI manager
1202 */
1203 // We want to catch all exceptions here to reset LaF to defaults and report it.
1204 @SuppressWarnings("squid:S2221")
[12637]1205 static void setupUIManager() {
[14138]1206 String defaultlaf = PlatformManager.getPlatform().getDefaultStyle();
[12637]1207 String laf = LafPreference.LAF.get();
1208 try {
1209 UIManager.setLookAndFeel(laf);
1210 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
1211 // Try to find look and feel in plugin classloaders
1212 Logging.trace(e);
1213 Class<?> klass = null;
[17512]1214 for (ClassLoader cl : PluginHandler.getPluginClassLoaders()) {
[12637]1215 try {
1216 klass = cl.loadClass(laf);
1217 break;
1218 } catch (ClassNotFoundException ex) {
1219 Logging.trace(ex);
1220 }
1221 }
1222 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
1223 try {
1224 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
1225 } catch (ReflectiveOperationException ex) {
1226 Logging.log(Logging.LEVEL_WARN, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage(), ex);
1227 } catch (UnsupportedLookAndFeelException ex) {
1228 Logging.info("Look and Feel not supported: " + laf);
1229 LafPreference.LAF.put(defaultlaf);
1230 Logging.trace(ex);
[18598]1231 } catch (Exception ex) {
1232 // We do not want to silently exit if there is an exception.
1233 // Put the default laf in place so that the user can use JOSM.
1234 LafPreference.LAF.put(defaultlaf);
1235 BugReportExceptionHandler.handleException(ex);
[12637]1236 }
1237 } else {
1238 Logging.info("Look and Feel not found: " + laf);
1239 LafPreference.LAF.put(defaultlaf);
1240 }
1241 } catch (UnsupportedLookAndFeelException e) {
1242 Logging.info("Look and Feel not supported: " + laf);
1243 LafPreference.LAF.put(defaultlaf);
1244 Logging.trace(e);
1245 } catch (InstantiationException | IllegalAccessException e) {
1246 Logging.error(e);
[18598]1247 } catch (Exception e) {
1248 // We do not want to silently exit if there is an exception.
1249 // Put the default laf in place.
1250 LafPreference.LAF.put(defaultlaf);
1251 BugReportExceptionHandler.handleException(e);
[12637]1252 }
1253
[13647]1254 UIManager.put("OptionPane.okIcon", ImageProvider.getIfAvailable("ok"));
[12637]1255 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
[13647]1256 UIManager.put("OptionPane.cancelIcon", ImageProvider.getIfAvailable("cancel"));
[12637]1257 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
[18801]1258 // Ensures caret color is the same as text foreground color, see #12257
[14695]1259 // See https://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
[12637]1260 for (String p : Arrays.asList(
1261 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
1262 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
1263 }
[12923]1264
[16961]1265 scaleFonts(Config.getPref().getDouble("gui.scale.menu.font", 1.0),
1266 "Menu.font", "MenuItem.font", "CheckBoxMenuItem.font", "RadioButtonMenuItem.font", "MenuItem.acceleratorFont");
1267 scaleFonts(Config.getPref().getDouble("gui.scale.list.font", 1.0),
1268 "List.font");
1269 // "Table.font" see org.openstreetmap.josm.gui.util.TableHelper.setFont
[17866]1270
1271 setupTextAntiAliasing();
[16961]1272 }
1273
1274 private static void scaleFonts(double factor, String... fonts) {
1275 if (factor == 1.0) {
1276 return;
1277 }
1278 for (String key : fonts) {
1279 Font font = UIManager.getFont(key);
1280 if (font != null) {
1281 font = font.deriveFont((float) (font.getSize2D() * factor));
1282 UIManager.put(key, new FontUIResource(font));
[12923]1283 }
1284 }
[12637]1285 }
1286
[17866]1287 private static void setupTextAntiAliasing() {
1288 // On Linux and running on Java 9+, enable text anti aliasing
1289 // if not yet enabled and if neither running on Gnome or KDE desktop
1290 if (PlatformManager.isPlatformUnixoid()
1291 && Utils.getJavaVersion() >= 9
1292 && UIManager.getLookAndFeelDefaults().get(RenderingHints.KEY_TEXT_ANTIALIASING) == null
1293 && System.getProperty("awt.useSystemAAFontSettings") == null
1294 && Toolkit.getDefaultToolkit().getDesktopProperty("gnome.Xft/Antialias") == null
1295 && Toolkit.getDefaultToolkit().getDesktopProperty("fontconfig/Antialias") == null) {
1296 UIManager.getLookAndFeelDefaults().put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
1297 }
1298 }
1299
[10093]1300 static Collection<PluginInformation> updateAndLoadEarlyPlugins(SplashScreen splash, SplashProgressMonitor monitor) {
1301 Collection<PluginInformation> pluginsToLoad;
1302 pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
1303 if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
1304 monitor.subTask(tr("Updating plugins"));
1305 pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
1306 }
1307
1308 monitor.indeterminateSubTask(tr("Installing updated plugins"));
[13647]1309 try {
1310 PluginHandler.installDownloadedPlugins(pluginsToLoad, true);
1311 } catch (SecurityException e) {
1312 Logging.log(Logging.LEVEL_ERROR, "Unable to install plugins", e);
1313 }
[10093]1314
1315 monitor.indeterminateSubTask(tr("Loading early plugins"));
1316 PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
1317 return pluginsToLoad;
1318 }
1319
1320 static void loadLatePlugins(SplashScreen splash, SplashProgressMonitor monitor, Collection<PluginInformation> pluginsToLoad) {
1321 monitor.indeterminateSubTask(tr("Loading plugins"));
1322 PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
[18361]1323 GuiHelper.runInEDTAndWait(() -> {
1324 toolbar.enableInfoAboutMissingAction();
1325 toolbar.refreshToolbarControl();
1326 });
[10093]1327 }
1328
[10899]1329 private static void processOffline(ProgramArguments args) {
1330 for (String offlineNames : args.get(Option.OFFLINE)) {
[16643]1331 for (String s : offlineNames.split(",", -1)) {
[7434]1332 try {
[14121]1333 NetworkManager.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
[7434]1334 } catch (IllegalArgumentException e) {
[12620]1335 Logging.log(Logging.LEVEL_ERROR,
1336 tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
1337 s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())), e);
[18366]1338 Lifecycle.exitJosm(true, 1);
[7434]1339 return;
1340 }
1341 }
1342 }
[14121]1343 Set<OnlineResource> offline = NetworkManager.getOfflineResources();
[10899]1344 if (!offline.isEmpty()) {
[12620]1345 Logging.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
[10899]1346 "JOSM is running in offline mode. These resources will not be available: {0}",
[16429]1347 offline.size(), offline.stream().map(OnlineResource::getLocName).collect(Collectors.joining(", "))));
[10899]1348 }
[7434]1349 }
1350
[8296]1351 /**
1352 * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
1353 * disabling or enabling IPV6 may only be done with next start.
1354 */
1355 private static void checkIPv6() {
[12845]1356 if ("auto".equals(Config.getPref().get("prefer.ipv6", "auto"))) {
[10611]1357 new Thread((Runnable) () -> { /* this may take some time (DNS, Connect) */
1358 boolean hasv6 = false;
[12845]1359 boolean wasv6 = Config.getPref().getBoolean("validated.ipv6", false);
[10611]1360 try {
1361 /* Use the check result from last run of the software, as after the test, value
1362 changes have no effect anymore */
1363 if (wasv6) {
1364 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1365 }
1366 for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
1367 if (a instanceof Inet6Address) {
1368 if (a.isReachable(1000)) {
1369 /* be sure it REALLY works */
[11455]1370 SSLSocketFactory.getDefault().createSocket(a, 443).close();
[15320]1371 hasv6 = true;
1372 /* in case of routing problems to the main openstreetmap domain don't enable IPv6 */
1373 for (InetAddress b : InetAddress.getAllByName("api.openstreetmap.org")) {
1374 if (b instanceof Inet6Address) {
[18492]1375 //if (b.isReachable(1000)) {
1376 SSLSocketFactory.getDefault().createSocket(b, 443).close();
1377 //} else {
1378 // hasv6 = false;
1379 //}
[15320]1380 break; /* we're done */
1381 }
1382 }
[18493]1383 if (hasv6) {
[18492]1384 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1385 if (!wasv6) {
1386 Logging.info(tr("Detected usable IPv6 network, preferring IPv6 over IPv4 after next restart."));
1387 } else {
1388 Logging.info(tr("Detected usable IPv6 network, preferring IPv6 over IPv4."));
1389 }
[8296]1390 }
1391 }
[10611]1392 break; /* we're done */
[8296]1393 }
1394 }
[10611]1395 } catch (IOException | SecurityException e) {
[12620]1396 Logging.debug("Exception while checking IPv6 connectivity: {0}", e);
[15321]1397 hasv6 = false;
[12620]1398 Logging.trace(e);
[8296]1399 }
[18492]1400 Config.getPref().putBoolean("validated.ipv6", hasv6); // be sure it is stored before the restart!
[10611]1401 if (wasv6 && !hasv6) {
[17786]1402 Logging.info(tr("Detected no usable IPv6 network, preferring IPv4 over IPv6 after next restart."));
[17390]1403 RestartAction.restartJOSM();
[10611]1404 }
[8736]1405 }, "IPv6-checker").start();
[8296]1406 }
1407 }
[8356]1408
[12633]1409 /**
1410 * Download area specified as Bounds value.
1411 * @param rawGps Flag to download raw GPS tracks
1412 * @param b The bounds value
1413 * @return the complete download task (including post-download handler)
1414 */
1415 static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
1416 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1417 // asynchronously launch the download task ...
[13927]1418 Future<?> future = task.download(new DownloadParams().withNewLayer(true), b, null);
[12633]1419 // ... and the continuation when the download is finished (this will wait for the download to finish)
[12634]1420 return Collections.singletonList(MainApplication.worker.submit(new PostDownloadHandler(task, future)));
[12633]1421 }
1422
1423 /**
1424 * Handle command line instructions after GUI has been initialized.
1425 * @param args program arguments
1426 * @return the list of submitted tasks
1427 */
1428 static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
1429 List<Future<?>> tasks = new ArrayList<>();
1430 List<File> fileList = new ArrayList<>();
1431 for (String s : args.get(Option.DOWNLOAD)) {
1432 tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
1433 }
1434 if (!fileList.isEmpty()) {
[17556]1435 tasks.add(OpenFileAction.openFiles(fileList, Options.RECORD_HISTORY));
[12633]1436 }
1437 for (String s : args.get(Option.DOWNLOADGPS)) {
1438 tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
1439 }
1440 final Collection<String> selectionArguments = args.get(Option.SELECTION);
1441 if (!selectionArguments.isEmpty()) {
[12634]1442 tasks.add(MainApplication.worker.submit(() -> {
[12633]1443 for (String s : selectionArguments) {
[12659]1444 SearchAction.search(s, SearchMode.add);
[12633]1445 }
1446 }));
1447 }
1448 return tasks;
1449 }
1450
[6523]1451 private static class GuiFinalizationWorker implements Runnable {
1452
[10899]1453 private final ProgramArguments args;
[6523]1454 private final DefaultProxySelector proxySelector;
1455
[10899]1456 GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
[6523]1457 this.args = args;
1458 this.proxySelector = proxySelector;
1459 }
1460
1461 @Override
1462 public void run() {
1463
[6642]1464 // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
1465 if (!handleProxyErrors()) {
1466 handleNetworkErrors();
1467 }
[6523]1468
1469 // Restore autosave layers after crash and start autosave thread
1470 handleAutosave();
1471
1472 // Handle command line instructions
1473 postConstructorProcessCmdLine(args);
1474
1475 // Show download dialog if autostart is enabled
1476 DownloadDialog.autostartIfNeeded();
1477 }
1478
[8870]1479 private static void handleAutosave() {
[19050]1480 if (Boolean.TRUE.equals(AutosaveTask.PROP_AUTOSAVE_ENABLED.get())) {
[6523]1481 AutosaveTask autosaveTask = new AutosaveTask();
1482 List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
1483 if (!unsavedLayerFiles.isEmpty()) {
1484 ExtendedDialog dialog = new ExtendedDialog(
[14153]1485 mainFrame,
[6523]1486 tr("Unsaved osm data"),
[12279]1487 tr("Restore"), tr("Cancel"), tr("Discard")
[6523]1488 );
1489 dialog.setContent(
1490 trn("JOSM found {0} unsaved osm data layer. ",
1491 "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
1492 tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
[12279]1493 dialog.setButtonIcons("ok", "cancel", "dialogs/delete");
[6523]1494 int selection = dialog.showDialog().getValue();
1495 if (selection == 1) {
1496 autosaveTask.recoverUnsavedLayers();
1497 } else if (selection == 3) {
[6995]1498 autosaveTask.discardUnsavedLayers();
[6523]1499 }
1500 }
[13647]1501 try {
1502 autosaveTask.schedule();
1503 } catch (SecurityException e) {
1504 Logging.log(Logging.LEVEL_ERROR, "Unable to schedule autosave!", e);
1505 }
[6523]1506 }
1507 }
1508
[10043]1509 private static boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
[6642]1510 if (hasErrors) {
[6523]1511 ExtendedDialog ed = new ExtendedDialog(
[14153]1512 mainFrame, title,
[12279]1513 tr("Change proxy settings"), tr("Cancel"));
[16800]1514 ed.setButtonIcons("preference", "cancel").setCancelButton(2);
[6523]1515 ed.setMinimumSize(new Dimension(460, 260));
1516 ed.setIcon(JOptionPane.WARNING_MESSAGE);
[6642]1517 ed.setContent(message);
[6523]1518
1519 if (ed.showDialog().getValue() == 1) {
[17160]1520 PreferencesAction.forPreferenceTab(null, null, ProxyPreference.class).run();
[6523]1521 }
1522 }
[6642]1523 return hasErrors;
[6523]1524 }
[6642]1525
1526 private boolean handleProxyErrors() {
[13647]1527 return proxySelector != null &&
1528 handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
[6642]1529 tr("JOSM tried to access the following resources:<br>" +
1530 "{0}" +
1531 "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
1532 "{1}" +
1533 "Would you like to change your proxy settings now?",
1534 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
1535 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
1536 ));
1537 }
1538
[10755]1539 private static boolean handleNetworkErrors() {
[14121]1540 Map<String, Throwable> networkErrors = NetworkManager.getNetworkErrors();
[11650]1541 boolean condition = !networkErrors.isEmpty();
[6642]1542 if (condition) {
[16438]1543 Set<String> errors = networkErrors.values().stream()
1544 .map(Throwable::toString)
1545 .collect(Collectors.toCollection(TreeSet::new));
[6642]1546 return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
1547 tr("JOSM tried to access the following resources:<br>" +
1548 "{0}" +
1549 "but <b>failed</b> to do so, because of the following network errors:<br>" +
1550 "{1}" +
[7187]1551 "It may be due to a missing proxy configuration.<br>" +
[6642]1552 "Would you like to change your proxy settings now?",
[11650]1553 Utils.joinAsHtmlUnorderedList(networkErrors.keySet()),
[6642]1554 Utils.joinAsHtmlUnorderedList(errors)
1555 ));
1556 }
1557 return false;
1558 }
[6523]1559 }
[12695]1560
[19050]1561 private static final class DefaultNativeOsCallback implements NativeOsCallback {
[12695]1562 @Override
1563 public void openFiles(List<File> files) {
1564 Executors.newSingleThreadExecutor(Utils.newThreadFactory("openFiles-%d", Thread.NORM_PRIORITY)).submit(
1565 new OpenFileTask(files, null) {
1566 @Override
1567 protected void realRun() throws SAXException, IOException, OsmTransferException {
1568 // Wait for JOSM startup is advanced enough to load a file
[14153]1569 while (mainFrame == null || !mainFrame.isVisible()) {
[12695]1570 try {
1571 Thread.sleep(25);
1572 } catch (InterruptedException e) {
1573 Logging.warn(e);
1574 Thread.currentThread().interrupt();
1575 }
1576 }
1577 super.realRun();
1578 }
1579 });
1580 }
1581
1582 @Override
1583 public boolean handleQuitRequest() {
1584 return MainApplication.exitJosm(false, 0, null);
1585 }
1586
1587 @Override
1588 public void handleAbout() {
1589 MainApplication.getMenu().about.actionPerformed(null);
1590 }
1591
1592 @Override
1593 public void handlePreferences() {
1594 MainApplication.getMenu().preferences.actionPerformed(null);
1595 }
1596 }
[12766]1597
1598 static void notifyNewMessages(UserInfo userInfo) {
1599 GuiHelper.runInEDT(() -> {
1600 JPanel panel = new JPanel(new GridBagLayout());
1601 panel.add(new JLabel(trn("You have {0} unread message.", "You have {0} unread messages.",
1602 userInfo.getUnreadMessages(), userInfo.getUnreadMessages())),
1603 GBC.eol());
[14119]1604 panel.add(new UrlLabel(Config.getUrls().getBaseUserUrl() + '/' + userInfo.getDisplayName() + "/inbox",
[12766]1605 tr("Click here to see your inbox.")), GBC.eol());
1606 panel.setOpaque(false);
1607 new Notification().setContent(panel)
1608 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1609 .setDuration(Notification.TIME_LONG)
1610 .show();
1611 });
1612 }
[1677]1613}
Note: See TracBrowser for help on using the repository browser.