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

Last change on this file since 17994 was 17868, checked in by simon04, 3 years ago

see #20706 - Remove unneeded KEY_ANTIALIASING (patch by nvarner and DevCharly)

Fixup r17866

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