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

Last change on this file since 17545 was 17545, checked in by Don-vip, 3 years ago

see #20257 - JDK-8251377 is fixed in Java 16, make sure we don't mess with default LAF in Java 16+

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