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

Last change on this file since 16530 was 16498, checked in by simon04, 4 years ago

fix #19290 - Configure Look and feel before showing splash screen (patch by hiddewie)

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