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

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

see #8334 - Add advanced option to scale the list font

Advanced preference key gui.scale.list.font

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