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

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

Fix #23437: Offer to reset JOSM if JOSM fails to finish startup multiple times

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