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

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

fix #19698 - Refactoring: make private fields final

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