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

Last change on this file since 12600 was 12279, checked in by Don-vip, 7 years ago

sonar - squid:S3878 - Arrays should not be created for varargs parameters

  • Property svn:eol-style set to native
File size: 27.1 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;
[283]6
[6523]7import java.awt.Dimension;
[3435]8import java.io.File;
[7335]9import java.io.IOException;
[7033]10import java.io.InputStream;
[2641]11import java.net.Authenticator;
[8356]12import java.net.Inet6Address;
[8296]13import java.net.InetAddress;
[2641]14import java.net.ProxySelector;
[5201]15import java.net.URL;
[3232]16import java.security.AllPermission;
17import java.security.CodeSource;
[10235]18import java.security.GeneralSecurityException;
[7335]19import java.security.KeyStoreException;
20import java.security.NoSuchAlgorithmException;
[3232]21import java.security.PermissionCollection;
22import java.security.Permissions;
23import java.security.Policy;
[7335]24import java.security.cert.CertificateException;
[11650]25import java.util.ArrayList;
[7434]26import java.util.Arrays;
[283]27import java.util.Collection;
[11650]28import java.util.Collections;
[283]29import java.util.List;
[8404]30import java.util.Locale;
[11650]31import java.util.Map;
[10899]32import java.util.Optional;
[6642]33import java.util.Set;
34import java.util.TreeSet;
[10899]35import java.util.logging.Level;
[11255]36import java.util.stream.Collectors;
37import java.util.stream.Stream;
[283]38
[11455]39import javax.net.ssl.SSLSocketFactory;
[12128]40import javax.swing.JComponent;
[6523]41import javax.swing.JOptionPane;
[4720]42import javax.swing.RepaintManager;
[3679]43import javax.swing.SwingUtilities;
[283]44
[4720]45import org.jdesktop.swinghelper.debug.CheckThreadViolationRepaintManager;
[283]46import org.openstreetmap.josm.Main;
[6523]47import org.openstreetmap.josm.actions.PreferencesAction;
[9238]48import org.openstreetmap.josm.actions.RestartAction;
[3378]49import org.openstreetmap.josm.data.AutosaveTask;
[5201]50import org.openstreetmap.josm.data.CustomConfigurator;
[4259]51import org.openstreetmap.josm.data.Version;
[10899]52import org.openstreetmap.josm.gui.ProgramArguments.Option;
[10093]53import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
[4906]54import org.openstreetmap.josm.gui.download.DownloadDialog;
[2748]55import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
[6523]56import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
[5796]57import org.openstreetmap.josm.gui.util.GuiHelper;
[9995]58import org.openstreetmap.josm.io.CertificateAmendment;
[2641]59import org.openstreetmap.josm.io.DefaultProxySelector;
[6349]60import org.openstreetmap.josm.io.MessageNotifier;
[7434]61import org.openstreetmap.josm.io.OnlineResource;
[4245]62import org.openstreetmap.josm.io.auth.CredentialsManager;
[2641]63import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
[10931]64import org.openstreetmap.josm.io.protocols.data.Handler;
[3707]65import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
[1326]66import org.openstreetmap.josm.plugins.PluginHandler;
[2817]67import org.openstreetmap.josm.plugins.PluginInformation;
[7383]68import org.openstreetmap.josm.tools.FontsManager;
[9171]69import org.openstreetmap.josm.tools.HttpClient;
[2017]70import org.openstreetmap.josm.tools.I18n;
[10899]71import org.openstreetmap.josm.tools.Logging;
[6453]72import org.openstreetmap.josm.tools.OsmUrlToBounds;
[7335]73import org.openstreetmap.josm.tools.PlatformHookWindows;
[5868]74import org.openstreetmap.josm.tools.Utils;
[10340]75import org.openstreetmap.josm.tools.WindowGeometry;
[10899]76import org.openstreetmap.josm.tools.bugreport.BugReport;
[10055]77import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
[1058]78
[283]79/**
80 * Main window class application.
81 *
82 * @author imi
83 */
84public class MainApplication extends Main {
[8415]85
[11650]86 /**
87 * Command-line arguments used to run the application.
88 */
89 private static final List<String> COMMAND_LINE_ARGS = new ArrayList<>();
90
[12125]91 private final MainFrame mainFrame;
[10340]92
[1169]93 /**
[10340]94 * Constructs a new {@code MainApplication} without a window.
[1169]95 */
[8415]96 public MainApplication() {
[10340]97 // Allow subclassing (see JOSM.java)
98 this(null);
[8415]99 }
[1023]100
[1169]101 /**
[5829]102 * Constructs a main frame, ready sized and operating. Does not display the frame.
103 * @param mainFrame The main JFrame of the application
[10340]104 * @since 10340
[1169]105 */
[10340]106 public MainApplication(MainFrame mainFrame) {
107 this.mainFrame = mainFrame;
[1169]108 }
[283]109
[10340]110 @Override
111 protected void initializeMainWindow() {
112 if (mainFrame != null) {
[12125]113 panel = mainFrame.getPanel();
[10340]114 mainFrame.initialize();
115 menu = mainFrame.getMenu();
116 } else {
117 // required for running some tests.
[12125]118 panel = new MainPanel(Main.getLayerManager());
[10340]119 menu = new MainMenu();
120 }
[12125]121 panel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
122 panel.reAddListeners();
[10340]123 }
124
125 @Override
126 protected void shutdown() {
[11103]127 if (mainFrame != null) {
128 mainFrame.storeState();
129 }
[10340]130 super.shutdown();
131 }
132
[1169]133 /**
[11650]134 * Returns the command-line arguments used to run the application.
135 * @return the command-line arguments used to run the application
136 * @since 11650
137 */
138 public static List<String> getCommandLineArgs() {
139 return Collections.unmodifiableList(COMMAND_LINE_ARGS);
140 }
141
142 /**
[2748]143 * Displays help on the console
[6143]144 * @since 2748
[2748]145 */
146 public static void showHelp() {
147 // TODO: put in a platformHook for system that have no console by default
[10983]148 System.out.println(getHelp());
149 }
150
151 static String getHelp() {
152 return tr("Java OpenStreetMap Editor")+" ["
[5363]153 +Version.getInstance().getAgentString()+"]\n\n"+
[2748]154 tr("usage")+":\n"+
155 "\tjava -jar josm.jar <options>...\n\n"+
156 tr("options")+":\n"+
[8846]157 "\t--help|-h "+tr("Show this help")+'\n'+
158 "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+'\n'+
159 "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+'\n'+
160 "\t[--download=]<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z)")+'\n'+
161 "\t[--download=]<filename> "+tr("Open a file (any file type that can be opened with File/Open)")+'\n'+
162 "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw GPS")+'\n'+
163 "\t--downloadgps=<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z) as raw GPS")+'\n'+
164 "\t--selection=<searchstring> "+tr("Select with the given search")+'\n'+
165 "\t--[no-]maximize "+tr("Launch in maximized mode")+'\n'+
[2748]166 "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+
[5201]167 "\t--load-preferences=<url-to-xml> "+tr("Changes preferences according to the XML file")+"\n\n"+
[4789]168 "\t--set=<key>=<value> "+tr("Set preference key to value")+"\n\n"+
[2800]169 "\t--language=<language> "+tr("Set the language")+"\n\n"+
[5365]170 "\t--version "+tr("Displays the JOSM version and exits")+"\n\n"+
[6730]171 "\t--debug "+tr("Print debugging messages to console")+"\n\n"+
[8169]172 "\t--skip-plugins "+tr("Skip loading plugins")+"\n\n"+
[7434]173 "\t--offline=<osm_api|josm_website|all> "+tr("Disable access to the given resource(s), separated by comma")+"\n\n"+
[2748]174 tr("options provided as Java system properties")+":\n"+
[11255]175 align("\t-Djosm.dir.name=JOSM") + tr("Change the JOSM directory name") + "\n\n" +
176 align("\t-Djosm.pref=" + tr("/PATH/TO/JOSM/PREF ")) + tr("Set the preferences directory") + "\n" +
177 align("\t") + tr("Default: {0}", platform.getDefaultPrefDirectory()) + "\n\n" +
178 align("\t-Djosm.userdata=" + tr("/PATH/TO/JOSM/USERDATA")) + tr("Set the user data directory") + "\n" +
179 align("\t") + tr("Default: {0}", platform.getDefaultUserDataDirectory()) + "\n\n" +
180 align("\t-Djosm.cache=" + tr("/PATH/TO/JOSM/CACHE ")) + tr("Set the cache directory") + "\n" +
181 align("\t") + tr("Default: {0}", platform.getDefaultCacheDirectory()) + "\n\n" +
182 align("\t-Djosm.home=" + tr("/PATH/TO/JOSM/HOMEDIR ")) +
183 tr("Set the preferences+data+cache directory (cache directory will be josm.home/cache)")+"\n\n"+
[7843]184 tr("-Djosm.home has lower precedence, i.e. the specific setting overrides the general one")+"\n\n"+
[2748]185 tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
[4720]186 " Java option to specify the maximum size of allocated memory in megabytes")+":\n"+
187 "\t-Xmx...m\n\n"+
[10983]188 tr("examples")+":\n"+
189 "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
190 "\tjava -jar josm.jar "+OsmUrlToBounds.getURL(43.2, 11.1, 13)+'\n'+
191 "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
192 "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
193 "\tjava -Djosm.pref=$XDG_CONFIG_HOME -Djosm.userdata=$XDG_DATA_HOME -Djosm.cache=$XDG_CACHE_HOME -jar josm.jar\n"+
[11255]194 "\tjava -Djosm.dir.name=josm_dev -jar josm.jar\n"+
[10983]195 "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
196 "\tjava -Xmx1024m -jar josm.jar\n\n"+
197 tr("Parameters --download, --downloadgps, and --selection are processed in this order.")+'\n'+
198 tr("Make sure you load some data if you use --selection.")+'\n';
[2748]199 }
200
[11255]201 private static String align(String str) {
202 return str + Stream.generate(() -> " ").limit(Math.max(0, 43 - str.length())).collect(Collectors.joining(""));
203 }
204
[6143]205 /**
[2856]206 * Main application Startup
[5829]207 * @param argArray Command-line arguments
[2856]208 */
209 public static void main(final String[] argArray) {
210 I18n.init();
[6108]211
[12150]212 ProgramArguments args = null;
[6108]213 // construct argument table
214 try {
[10899]215 args = new ProgramArguments(argArray);
[6108]216 } catch (IllegalArgumentException e) {
[10983]217 System.err.println(e.getMessage());
[6108]218 System.exit(1);
[7434]219 return;
[6108]220 }
[6830]221
[10899]222 Level logLevel = args.getLogLevel();
223 Logging.setLogLevel(logLevel);
[10983]224 if (!args.showVersion() && !args.showHelp()) {
225 Main.info(tr("Log level is at {0} ({1}, {2})", logLevel.getLocalizedName(), logLevel.getName(), logLevel.intValue()));
226 }
[6108]227
[10899]228 Optional<String> language = args.getSingle(Option.LANGUAGE);
229 I18n.set(language.orElse(null));
[6108]230
[3232]231 Policy.setPolicy(new Policy() {
232 // Permissions for plug-ins loaded when josm is started via webstart
233 private PermissionCollection pc;
234
235 {
236 pc = new Permissions();
237 pc.add(new AllPermission());
238 }
239
240 @Override
241 public PermissionCollection getPermissions(CodeSource codesource) {
242 return pc;
243 }
244 });
245
[2856]246 Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
247
[3815]248 // initialize the platform hook, and
[2856]249 Main.determinePlatformHook();
[4259]250 // call the really early hook before we do anything else
[2856]251 Main.platform.preStartupHook();
252
[10899]253 if (args.showVersion()) {
[4259]254 System.out.println(Version.getInstance().getAgentString());
[10983]255 return;
[10899]256 } else if (args.showHelp()) {
257 showHelp();
[10983]258 return;
[6108]259 }
[4259]260
[11650]261 COMMAND_LINE_ARGS.addAll(Arrays.asList(argArray));
[10983]262
[12150]263 boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
[10899]264 if (skipLoadingPlugins) {
[8175]265 Main.info(tr("Plugin loading skipped"));
[8169]266 }
267
[10899]268 if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
269 // Enable debug in OAuth signpost via system preference, but only at trace level
270 Utils.updateSystemProperty("debug", "true");
271 Main.info(tr("Enabled detailed debug level (trace)"));
[8296]272 }
273
[10899]274 Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
275
276 args.getPreferencesToSet().forEach(Main.pref::put);
277
278 if (!language.isPresent()) {
[1802]279 I18n.set(Main.pref.get("language", null));
[2025]280 }
[2358]281 Main.pref.updateSystemProperties();
[1326]282
[8296]283 checkIPv6();
284
[7434]285 processOffline(args);
286
[8015]287 Main.platform.afterPrefStartupHook();
288
[7383]289 FontsManager.initialize();
[7434]290
[8282]291 I18n.setupLanguageFonts();
[7896]292
[10931]293 Handler.install();
294
[10340]295 WindowGeometry geometry = WindowGeometry.mainWindow("gui.geometry",
[10899]296 args.getSingle(Option.GEOMETRY).orElse(null),
297 !args.hasOption(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
[12128]298 final MainFrame mainFrame = new MainFrame(geometry);
[12133]299 if (mainFrame.getContentPane() instanceof JComponent) {
300 Main.contentPanePrivate = (JComponent) mainFrame.getContentPane();
301 }
[12127]302 Main.mainPanel = mainFrame.getPanel();
[5201]303 Main.parent = mainFrame;
304
[10899]305 if (args.hasOption(Option.LOAD_PREFERENCES)) {
[5201]306 CustomConfigurator.XMLCommandProcessor config = new CustomConfigurator.XMLCommandProcessor(Main.pref);
[5279]307 for (String i : args.get(Option.LOAD_PREFERENCES)) {
[6248]308 info("Reading preferences from " + i);
[11509]309 try (InputStream is = openStream(new URL(i))) {
[7033]310 config.openAndReadXML(is);
[10212]311 } catch (IOException ex) {
[10899]312 throw BugReport.intercept(ex).put("file", i);
[5201]313 }
314 }
315 }
316
[9995]317 try {
318 CertificateAmendment.addMissingCertificates();
[10235]319 } catch (IOException | GeneralSecurityException ex) {
[10296]320 Main.warn(ex);
[9995]321 Main.warn(getErrorMessage(Utils.getRootCause(ex)));
322 }
[2748]323 Authenticator.setDefault(DefaultAuthenticator.getInstance());
[6523]324 DefaultProxySelector proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
325 ProxySelector.setDefault(proxySelector);
[4245]326 OAuthAccessTokenHolder.getInstance().init(Main.pref, CredentialsManager.getInstance());
[2641]327
[10611]328 final SplashScreen splash = GuiHelper.runInEDTAndWaitAndReturn(SplashScreen::new);
[8497]329 final SplashScreen.SplashProgressMonitor monitor = splash.getProgressMonitor();
[2817]330 monitor.beginTask(tr("Initializing"));
[10611]331 GuiHelper.runInEDT(() -> splash.setVisible(Main.pref.getBoolean("draw.splashscreen", true)));
[4681]332 Main.setInitStatusListener(new InitStatusListener() {
[1023]333
[4681]334 @Override
[8497]335 public Object updateStatus(String event) {
336 monitor.beginTask(event);
337 return event;
[4681]338 }
[8497]339
340 @Override
341 public void finish(Object status) {
342 if (status instanceof String) {
343 monitor.finishTask((String) status);
344 }
345 }
[4681]346 });
347
[8169]348 Collection<PluginInformation> pluginsToLoad = null;
[283]349
[8169]350 if (!skipLoadingPlugins) {
[10093]351 pluginsToLoad = updateAndLoadEarlyPlugins(splash, monitor);
[8169]352 }
353
[4681]354 monitor.indeterminateSubTask(tr("Setting defaults"));
[10962]355 preConstructorInit();
[2817]356
357 monitor.indeterminateSubTask(tr("Creating main GUI"));
358 final Main main = new MainApplication(mainFrame);
[10340]359 main.initialize();
[2817]360
[8169]361 if (!skipLoadingPlugins) {
[10093]362 loadLatePlugins(splash, monitor, pluginsToLoad);
[8169]363 }
[5796]364
[6866]365 // Wait for splash disappearance (fix #9714)
[10611]366 GuiHelper.runInEDTAndWait(() -> {
367 splash.setVisible(false);
368 splash.dispose();
369 mainFrame.setVisible(true);
[5796]370 });
371
[6578]372 boolean maximized = Main.pref.getBoolean("gui.maximized", false);
[10899]373 if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
[10340]374 mainFrame.setMaximized(true);
[2025]375 }
[6246]376 if (main.menu.fullscreenToggleAction != null) {
[4139]377 main.menu.fullscreenToggleAction.initial();
[4720]378 }
[1023]379
[6523]380 SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
[5279]381
[7335]382 if (Main.isPlatformWindows()) {
383 try {
384 // Check for insecure certificates to remove.
[8509]385 // This is Windows-dependant code but it can't go to preStartupHook (need i18n)
386 // neither startupHook (need to be called before remote control)
[7343]387 PlatformHookWindows.removeInsecureCertificates();
[7335]388 } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
389 error(e);
390 }
391 }
392
[3959]393 if (RemoteControl.PROP_REMOTECONTROL_ENABLED.get()) {
394 RemoteControl.start();
395 }
[6830]396
[6349]397 if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
398 MessageNotifier.start();
399 }
[3959]400
[4720]401 if (Main.pref.getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
[8509]402 // Repaint manager is registered so late for a reason - there is lots of violation during startup process
403 // but they don't seem to break anything and are difficult to fix
[6248]404 info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
[4720]405 RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
406 }
[1169]407 }
[6523]408
[11509]409 private static InputStream openStream(URL url) throws IOException {
410 if ("file".equals(url.getProtocol())) {
411 return url.openStream();
412 } else {
413 return HttpClient.create(url).connect().getContent();
414 }
415 }
416
[10093]417 static Collection<PluginInformation> updateAndLoadEarlyPlugins(SplashScreen splash, SplashProgressMonitor monitor) {
418 Collection<PluginInformation> pluginsToLoad;
419 pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
420 if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
421 monitor.subTask(tr("Updating plugins"));
422 pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
423 }
424
425 monitor.indeterminateSubTask(tr("Installing updated plugins"));
426 PluginHandler.installDownloadedPlugins(true);
427
428 monitor.indeterminateSubTask(tr("Loading early plugins"));
429 PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
430 return pluginsToLoad;
431 }
432
433 static void loadLatePlugins(SplashScreen splash, SplashProgressMonitor monitor, Collection<PluginInformation> pluginsToLoad) {
434 monitor.indeterminateSubTask(tr("Loading plugins"));
435 PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
[12135]436 GuiHelper.runInEDTAndWait(() -> toolbar.refreshToolbarControl());
[10093]437 }
438
[10899]439 private static void processOffline(ProgramArguments args) {
440 for (String offlineNames : args.get(Option.OFFLINE)) {
441 for (String s : offlineNames.split(",")) {
[7434]442 try {
[8404]443 Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
[7434]444 } catch (IllegalArgumentException e) {
[10627]445 Main.error(e, tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
[8404]446 s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())));
[7434]447 System.exit(1);
448 return;
449 }
450 }
451 }
[10899]452 Set<OnlineResource> offline = Main.getOfflineResources();
453 if (!offline.isEmpty()) {
454 Main.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
455 "JOSM is running in offline mode. These resources will not be available: {0}",
456 offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
457 }
[7434]458 }
459
[8296]460 /**
461 * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
462 * disabling or enabling IPV6 may only be done with next start.
463 */
464 private static void checkIPv6() {
[8510]465 if ("auto".equals(Main.pref.get("prefer.ipv6", "auto"))) {
[10611]466 new Thread((Runnable) () -> { /* this may take some time (DNS, Connect) */
467 boolean hasv6 = false;
468 boolean wasv6 = Main.pref.getBoolean("validated.ipv6", false);
469 try {
470 /* Use the check result from last run of the software, as after the test, value
471 changes have no effect anymore */
472 if (wasv6) {
473 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
474 }
475 for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
476 if (a instanceof Inet6Address) {
477 if (a.isReachable(1000)) {
478 /* be sure it REALLY works */
[11455]479 SSLSocketFactory.getDefault().createSocket(a, 443).close();
[10611]480 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
481 if (!wasv6) {
482 Main.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4 after next restart."));
483 } else {
484 Main.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4."));
[8296]485 }
[10611]486 hasv6 = true;
[8296]487 }
[10611]488 break; /* we're done */
[8296]489 }
490 }
[10611]491 } catch (IOException | SecurityException e) {
492 if (Main.isDebugEnabled()) {
493 Main.debug("Exception while checking IPv6 connectivity: "+e);
[8296]494 }
[10645]495 Main.trace(e);
[8296]496 }
[10611]497 if (wasv6 && !hasv6) {
498 Main.info(tr("Detected no useable IPv6 network, prefering IPv4 over IPv6 after next restart."));
499 Main.pref.put("validated.ipv6", hasv6); // be sure it is stored before the restart!
[12273]500 try {
501 RestartAction.restartJOSM();
502 } catch (IOException e) {
503 Main.error(e);
504 }
[10611]505 }
506 Main.pref.put("validated.ipv6", hasv6);
[8736]507 }, "IPv6-checker").start();
[8296]508 }
509 }
[8356]510
[6523]511 private static class GuiFinalizationWorker implements Runnable {
512
[10899]513 private final ProgramArguments args;
[6523]514 private final DefaultProxySelector proxySelector;
515
[10899]516 GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
[6523]517 this.args = args;
518 this.proxySelector = proxySelector;
519 }
520
521 @Override
522 public void run() {
523
[6642]524 // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
525 if (!handleProxyErrors()) {
526 handleNetworkErrors();
527 }
[6523]528
529 // Restore autosave layers after crash and start autosave thread
530 handleAutosave();
531
532 // Handle command line instructions
533 postConstructorProcessCmdLine(args);
534
535 // Show download dialog if autostart is enabled
536 DownloadDialog.autostartIfNeeded();
537 }
538
[8870]539 private static void handleAutosave() {
[6523]540 if (AutosaveTask.PROP_AUTOSAVE_ENABLED.get()) {
541 AutosaveTask autosaveTask = new AutosaveTask();
542 List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
543 if (!unsavedLayerFiles.isEmpty()) {
544 ExtendedDialog dialog = new ExtendedDialog(
545 Main.parent,
546 tr("Unsaved osm data"),
[12279]547 tr("Restore"), tr("Cancel"), tr("Discard")
[6523]548 );
549 dialog.setContent(
550 trn("JOSM found {0} unsaved osm data layer. ",
551 "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
552 tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
[12279]553 dialog.setButtonIcons("ok", "cancel", "dialogs/delete");
[6523]554 int selection = dialog.showDialog().getValue();
555 if (selection == 1) {
556 autosaveTask.recoverUnsavedLayers();
557 } else if (selection == 3) {
[6995]558 autosaveTask.discardUnsavedLayers();
[6523]559 }
560 }
561 autosaveTask.schedule();
562 }
563 }
564
[10043]565 private static boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
[6642]566 if (hasErrors) {
[6523]567 ExtendedDialog ed = new ExtendedDialog(
[6642]568 Main.parent, title,
[12279]569 tr("Change proxy settings"), tr("Cancel"));
570 ed.setButtonIcons("dialogs/settings", "cancel").setCancelButton(2);
[6523]571 ed.setMinimumSize(new Dimension(460, 260));
572 ed.setIcon(JOptionPane.WARNING_MESSAGE);
[6642]573 ed.setContent(message);
[6523]574
575 if (ed.showDialog().getValue() == 1) {
576 PreferencesAction.forPreferenceSubTab(null, null, ProxyPreference.class).run();
577 }
578 }
[6642]579 return hasErrors;
[6523]580 }
[6642]581
582 private boolean handleProxyErrors() {
583 return handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
584 tr("JOSM tried to access the following resources:<br>" +
585 "{0}" +
586 "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
587 "{1}" +
588 "Would you like to change your proxy settings now?",
589 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
590 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
591 ));
592 }
593
[10755]594 private static boolean handleNetworkErrors() {
[11650]595 Map<String, Throwable> networkErrors = Main.getNetworkErrors();
596 boolean condition = !networkErrors.isEmpty();
[6642]597 if (condition) {
[7005]598 Set<String> errors = new TreeSet<>();
[11650]599 for (Throwable t : networkErrors.values()) {
[6642]600 errors.add(t.toString());
601 }
602 return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
603 tr("JOSM tried to access the following resources:<br>" +
604 "{0}" +
605 "but <b>failed</b> to do so, because of the following network errors:<br>" +
606 "{1}" +
[7187]607 "It may be due to a missing proxy configuration.<br>" +
[6642]608 "Would you like to change your proxy settings now?",
[11650]609 Utils.joinAsHtmlUnorderedList(networkErrors.keySet()),
[6642]610 Utils.joinAsHtmlUnorderedList(errors)
611 ));
612 }
613 return false;
614 }
[6523]615 }
[1677]616}
Note: See TracBrowser for help on using the repository browser.