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

Last change on this file since 17534 was 17512, checked in by Don-vip, 3 years ago

fix #20456 - use correct classloader when loading look-and-feel from plugins (patch by DevCharly)

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