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

Last change on this file since 18999 was 18999, checked in by taylor.smock, 3 months ago

See #23355: Ensure that the dialog has read the preference key for the sanity check

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