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

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

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