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

Last change on this file since 16155 was 16120, checked in by Don-vip, 4 years ago

fix #18920 - load AC RAIZ FNMT-RCM from Spanish Royal Mint

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