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

Last change on this file since 18366 was 18366, checked in by taylor.smock, 2 years ago

Replace usages of System.exit with Lifecycle.exitJosm

This fixes some coverity scan issues (spotbugs) with respect to exiting the VM.

See #15182: Standalone JOSM validator

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