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