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

Last change on this file since 17824 was 17807, checked in by simon04, 3 years ago

see #20706 - Revert "Enable text antialiasing for more JosmEditorPane"

This reverts r17798.

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