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