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

Last change on this file since 10008 was 9995, checked in by bastiK, 8 years ago

fixed #12264 - Add own CA's to Java cert-store

  • Property svn:eol-style set to native
File size: 30.8 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 gnu.getopt.Getopt;
7import gnu.getopt.LongOpt;
8
9import java.awt.Dimension;
10import java.awt.Image;
11import java.awt.Toolkit;
12import java.awt.event.WindowAdapter;
13import java.awt.event.WindowEvent;
14import java.io.File;
15import java.io.IOException;
16import java.io.InputStream;
17import java.net.Authenticator;
18import java.net.Inet6Address;
19import java.net.InetAddress;
20import java.net.InetSocketAddress;
21import java.net.ProxySelector;
22import java.net.Socket;
23import java.net.URL;
24import java.security.AllPermission;
25import java.security.CodeSource;
26import java.security.KeyStoreException;
27import java.security.NoSuchAlgorithmException;
28import java.security.PermissionCollection;
29import java.security.Permissions;
30import java.security.Policy;
31import java.security.cert.CertificateException;
32import java.util.ArrayList;
33import java.util.Arrays;
34import java.util.Collection;
35import java.util.EnumMap;
36import java.util.LinkedList;
37import java.util.List;
38import java.util.Locale;
39import java.util.Map;
40import java.util.Set;
41import java.util.TreeSet;
42import java.util.concurrent.Callable;
43
44import javax.swing.JFrame;
45import javax.swing.JOptionPane;
46import javax.swing.RepaintManager;
47import javax.swing.SwingUtilities;
48
49import org.jdesktop.swinghelper.debug.CheckThreadViolationRepaintManager;
50import org.openstreetmap.josm.Main;
51import org.openstreetmap.josm.actions.PreferencesAction;
52import org.openstreetmap.josm.actions.RestartAction;
53import org.openstreetmap.josm.data.AutosaveTask;
54import org.openstreetmap.josm.data.CustomConfigurator;
55import org.openstreetmap.josm.data.Version;
56import org.openstreetmap.josm.gui.download.DownloadDialog;
57import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
58import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
59import org.openstreetmap.josm.gui.util.GuiHelper;
60import org.openstreetmap.josm.io.CertificateAmendment;
61import org.openstreetmap.josm.io.DefaultProxySelector;
62import org.openstreetmap.josm.io.MessageNotifier;
63import org.openstreetmap.josm.io.OnlineResource;
64import org.openstreetmap.josm.io.auth.CredentialsManager;
65import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
66import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
67import org.openstreetmap.josm.plugins.PluginHandler;
68import org.openstreetmap.josm.plugins.PluginInformation;
69import org.openstreetmap.josm.tools.BugReportExceptionHandler;
70import org.openstreetmap.josm.tools.FontsManager;
71import org.openstreetmap.josm.tools.HttpClient;
72import org.openstreetmap.josm.tools.I18n;
73import org.openstreetmap.josm.tools.ImageProvider;
74import org.openstreetmap.josm.tools.OsmUrlToBounds;
75import org.openstreetmap.josm.tools.PlatformHookWindows;
76import org.openstreetmap.josm.tools.Utils;
77
78/**
79 * Main window class application.
80 *
81 * @author imi
82 */
83public class MainApplication extends Main {
84
85 /**
86 * Constructs a new {@code MainApplication}.
87 */
88 public MainApplication() {
89 // Allow subclassing (see JOSM.java)
90 }
91
92 /**
93 * Constructs a main frame, ready sized and operating. Does not display the frame.
94 * @param mainFrame The main JFrame of the application
95 */
96 public MainApplication(JFrame mainFrame) {
97 addListener();
98 mainFrame.setContentPane(contentPanePrivate);
99 mainFrame.setJMenuBar(menu);
100 geometry.applySafe(mainFrame);
101 List<Image> l = new LinkedList<>();
102 l.add(ImageProvider.get("logo_16x16x32").getImage());
103 l.add(ImageProvider.get("logo_16x16x8").getImage());
104 l.add(ImageProvider.get("logo_32x32x32").getImage());
105 l.add(ImageProvider.get("logo_32x32x8").getImage());
106 l.add(ImageProvider.get("logo_48x48x32").getImage());
107 l.add(ImageProvider.get("logo_48x48x8").getImage());
108 l.add(ImageProvider.get("logo").getImage());
109 mainFrame.setIconImages(l);
110 mainFrame.addWindowListener(new WindowAdapter() {
111 @Override
112 public void windowClosing(final WindowEvent arg0) {
113 Main.exitJosm(true, 0);
114 }
115 });
116 mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
117 }
118
119 /**
120 * Displays help on the console
121 * @since 2748
122 */
123 public static void showHelp() {
124 // TODO: put in a platformHook for system that have no console by default
125 System.out.println(tr("Java OpenStreetMap Editor")+" ["
126 +Version.getInstance().getAgentString()+"]\n\n"+
127 tr("usage")+":\n"+
128 "\tjava -jar josm.jar <options>...\n\n"+
129 tr("options")+":\n"+
130 "\t--help|-h "+tr("Show this help")+'\n'+
131 "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+'\n'+
132 "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+'\n'+
133 "\t[--download=]<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z)")+'\n'+
134 "\t[--download=]<filename> "+tr("Open a file (any file type that can be opened with File/Open)")+'\n'+
135 "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw GPS")+'\n'+
136 "\t--downloadgps=<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z) as raw GPS")+'\n'+
137 "\t--selection=<searchstring> "+tr("Select with the given search")+'\n'+
138 "\t--[no-]maximize "+tr("Launch in maximized mode")+'\n'+
139 "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+
140 "\t--load-preferences=<url-to-xml> "+tr("Changes preferences according to the XML file")+"\n\n"+
141 "\t--set=<key>=<value> "+tr("Set preference key to value")+"\n\n"+
142 "\t--language=<language> "+tr("Set the language")+"\n\n"+
143 "\t--version "+tr("Displays the JOSM version and exits")+"\n\n"+
144 "\t--debug "+tr("Print debugging messages to console")+"\n\n"+
145 "\t--skip-plugins "+tr("Skip loading plugins")+"\n\n"+
146 "\t--offline=<osm_api|josm_website|all> "+tr("Disable access to the given resource(s), separated by comma")+"\n\n"+
147 tr("options provided as Java system properties")+":\n"+
148 "\t-Djosm.pref=" +tr("/PATH/TO/JOSM/PREF ")+tr("Set the preferences directory")+"\n\n"+
149 "\t-Djosm.userdata="+tr("/PATH/TO/JOSM/USERDATA")+tr("Set the user data directory")+"\n\n"+
150 "\t-Djosm.cache=" +tr("/PATH/TO/JOSM/CACHE ")+tr("Set the cache directory")+"\n\n"+
151 "\t-Djosm.home=" +tr("/PATH/TO/JOSM/HOMEDIR ")+
152 tr("Relocate all 3 directories to homedir. Cache directory will be in homedir/cache")+"\n\n"+
153 tr("-Djosm.home has lower precedence, i.e. the specific setting overrides the general one")+"\n\n"+
154 tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
155 " Java option to specify the maximum size of allocated memory in megabytes")+":\n"+
156 "\t-Xmx...m\n\n"+
157 tr("examples")+":\n"+
158 "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
159 "\tjava -jar josm.jar "+OsmUrlToBounds.getURL(43.2, 11.1, 13)+'\n'+
160 "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
161 "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
162 "\tjava -Djosm.pref=$XDG_CONFIG_HOME -Djosm.userdata=$XDG_DATA_HOME -Djosm.cache=$XDG_CACHE_HOME -jar josm.jar\n"+
163 "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
164 "\tjava -Xmx1024m -jar josm.jar\n\n"+
165 tr("Parameters --download, --downloadgps, and --selection are processed in this order.")+'\n'+
166 tr("Make sure you load some data if you use --selection.")+'\n'
167 );
168 }
169
170 /**
171 * JOSM command line options.
172 * @see <a href="https://josm.openstreetmap.de/wiki/Help/CommandLineOptions">Help/CommandLineOptions</a>
173 * @since 5279
174 */
175 public enum Option {
176 /** --help|-h Show this help */
177 HELP(false),
178 /** --version Displays the JOSM version and exits */
179 VERSION(false),
180 /** --debug Print debugging messages to console */
181 DEBUG(false),
182 /** --trace Print detailed debugging messages to console */
183 TRACE(false),
184 /** --language=&lt;language&gt; Set the language */
185 LANGUAGE(true),
186 /** --reset-preferences Reset the preferences to default */
187 RESET_PREFERENCES(false),
188 /** --load-preferences=&lt;url-to-xml&gt; Changes preferences according to the XML file */
189 LOAD_PREFERENCES(true),
190 /** --set=&lt;key&gt;=&lt;value&gt; Set preference key to value */
191 SET(true),
192 /** --geometry=widthxheight(+|-)x(+|-)y Standard unix geometry argument */
193 GEOMETRY(true),
194 /** --no-maximize Do not launch in maximized mode */
195 NO_MAXIMIZE(false),
196 /** --maximize Launch in maximized mode */
197 MAXIMIZE(false),
198 /** --download=minlat,minlon,maxlat,maxlon Download the bounding box <br>
199 * --download=&lt;URL&gt; Download the location at the URL (with lat=x&amp;lon=y&amp;zoom=z) <br>
200 * --download=&lt;filename&gt; Open a file (any file type that can be opened with File/Open) */
201 DOWNLOAD(true),
202 /** --downloadgps=minlat,minlon,maxlat,maxlon Download the bounding box as raw GPS <br>
203 * --downloadgps=&lt;URL&gt; Download the location at the URL (with lat=x&amp;lon=y&amp;zoom=z) as raw GPS */
204 DOWNLOADGPS(true),
205 /** --selection=&lt;searchstring&gt; Select with the given search */
206 SELECTION(true),
207 /** --offline=&lt;osm_api|josm_website|all&gt; Disable access to the given resource(s), delimited by comma */
208 OFFLINE(true),
209 /** --skip-plugins */
210 SKIP_PLUGINS(false);
211
212 private final String name;
213 private final boolean requiresArg;
214
215 Option(boolean requiresArgument) {
216 this.name = name().toLowerCase(Locale.ENGLISH).replace('_', '-');
217 this.requiresArg = requiresArgument;
218 }
219
220 /**
221 * Replies the option name
222 * @return The option name, in lowercase
223 */
224 public String getName() {
225 return name;
226 }
227
228 /**
229 * Determines if this option requires an argument.
230 * @return {@code true} if this option requires an argument, {@code false} otherwise
231 */
232 public boolean requiresArgument() {
233 return requiresArg;
234 }
235 }
236
237 private static Map<Option, Collection<String>> buildCommandLineArgumentMap(String[] args) {
238
239 List<LongOpt> los = new ArrayList<>();
240 for (Option o : Option.values()) {
241 los.add(new LongOpt(o.getName(), o.requiresArgument() ? LongOpt.REQUIRED_ARGUMENT : LongOpt.NO_ARGUMENT, null, 0));
242 }
243
244 Getopt g = new Getopt("JOSM", args, "hv", los.toArray(new LongOpt[los.size()]));
245
246 Map<Option, Collection<String>> argMap = new EnumMap<>(Option.class);
247
248 int c;
249 while ((c = g.getopt()) != -1) {
250 Option opt = null;
251 switch (c) {
252 case 'h':
253 opt = Option.HELP;
254 break;
255 case 'v':
256 opt = Option.VERSION;
257 break;
258 case 0:
259 opt = Option.values()[g.getLongind()];
260 break;
261 }
262 if (opt != null) {
263 Collection<String> values = argMap.get(opt);
264 if (values == null) {
265 values = new ArrayList<>();
266 argMap.put(opt, values);
267 }
268 values.add(g.getOptarg());
269 } else
270 throw new IllegalArgumentException("Invalid option: "+c);
271 }
272 // positional arguments are a shortcut for the --download ... option
273 for (int i = g.getOptind(); i < args.length; ++i) {
274 Collection<String> values = argMap.get(Option.DOWNLOAD);
275 if (values == null) {
276 values = new ArrayList<>();
277 argMap.put(Option.DOWNLOAD, values);
278 }
279 values.add(args[i]);
280 }
281
282 return argMap;
283 }
284
285 /**
286 * Main application Startup
287 * @param argArray Command-line arguments
288 */
289 public static void main(final String[] argArray) {
290 I18n.init();
291 Main.checkJavaVersion();
292
293 // construct argument table
294 Map<Option, Collection<String>> args = null;
295 try {
296 args = buildCommandLineArgumentMap(argArray);
297 } catch (IllegalArgumentException e) {
298 System.exit(1);
299 return;
300 }
301
302 final boolean languageGiven = args.containsKey(Option.LANGUAGE);
303
304 if (languageGiven) {
305 I18n.set(args.get(Option.LANGUAGE).iterator().next());
306 }
307
308 initApplicationPreferences();
309
310 Policy.setPolicy(new Policy() {
311 // Permissions for plug-ins loaded when josm is started via webstart
312 private PermissionCollection pc;
313
314 {
315 pc = new Permissions();
316 pc.add(new AllPermission());
317 }
318
319 @Override
320 public PermissionCollection getPermissions(CodeSource codesource) {
321 return pc;
322 }
323 });
324
325 Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
326
327 // initialize the platform hook, and
328 Main.determinePlatformHook();
329 // call the really early hook before we do anything else
330 Main.platform.preStartupHook();
331
332 Main.COMMAND_LINE_ARGS.addAll(Arrays.asList(argArray));
333
334 if (args.containsKey(Option.VERSION)) {
335 System.out.println(Version.getInstance().getAgentString());
336 System.exit(0);
337 }
338
339 if (args.containsKey(Option.DEBUG) || args.containsKey(Option.TRACE)) {
340 // Enable JOSM debug level
341 logLevel = 4;
342 Main.info(tr("Printing debugging messages to console"));
343 }
344
345 boolean skipLoadingPlugins = false;
346 if (args.containsKey(Option.SKIP_PLUGINS)) {
347 skipLoadingPlugins = true;
348 Main.info(tr("Plugin loading skipped"));
349 }
350
351 if (args.containsKey(Option.TRACE)) {
352 // Enable JOSM debug level
353 logLevel = 5;
354 // Enable debug in OAuth signpost via system preference, but only at trace level
355 Utils.updateSystemProperty("debug", "true");
356 Main.info(tr("Enabled detailed debug level (trace)"));
357 }
358
359 Main.pref.init(args.containsKey(Option.RESET_PREFERENCES));
360
361 if (args.containsKey(Option.SET)) {
362 for (String i : args.get(Option.SET)) {
363 String[] kv = i.split("=", 2);
364 Main.pref.put(kv[0], "null".equals(kv[1]) ? null : kv[1]);
365 }
366 }
367
368 if (!languageGiven) {
369 I18n.set(Main.pref.get("language", null));
370 }
371 Main.pref.updateSystemProperties();
372
373 checkIPv6();
374
375 // asking for help? show help and exit
376 if (args.containsKey(Option.HELP)) {
377 showHelp();
378 System.exit(0);
379 }
380
381 processOffline(args);
382
383 Main.platform.afterPrefStartupHook();
384
385 FontsManager.initialize();
386
387 I18n.setupLanguageFonts();
388
389 final JFrame mainFrame = new JFrame(tr("Java OpenStreetMap Editor"));
390 Main.parent = mainFrame;
391
392 if (args.containsKey(Option.LOAD_PREFERENCES)) {
393 CustomConfigurator.XMLCommandProcessor config = new CustomConfigurator.XMLCommandProcessor(Main.pref);
394 for (String i : args.get(Option.LOAD_PREFERENCES)) {
395 info("Reading preferences from " + i);
396 try (InputStream is = HttpClient.create(new URL(i)).connect().getContent()) {
397 config.openAndReadXML(is);
398 } catch (Exception ex) {
399 throw new RuntimeException(ex);
400 }
401 }
402 }
403
404 try {
405 CertificateAmendment.addMissingCertificates();
406 } catch (IOException ex) {
407 ex.printStackTrace();
408 Main.warn(getErrorMessage(Utils.getRootCause(ex)));
409 }
410 Authenticator.setDefault(DefaultAuthenticator.getInstance());
411 DefaultProxySelector proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
412 ProxySelector.setDefault(proxySelector);
413 OAuthAccessTokenHolder.getInstance().init(Main.pref, CredentialsManager.getInstance());
414
415 final SplashScreen splash = GuiHelper.runInEDTAndWaitAndReturn(new Callable<SplashScreen>() {
416 @Override
417 public SplashScreen call() {
418 return new SplashScreen();
419 }
420 });
421 final SplashScreen.SplashProgressMonitor monitor = splash.getProgressMonitor();
422 monitor.beginTask(tr("Initializing"));
423 GuiHelper.runInEDT(new Runnable() {
424 @Override
425 public void run() {
426 splash.setVisible(Main.pref.getBoolean("draw.splashscreen", true));
427 }
428 });
429 Main.setInitStatusListener(new InitStatusListener() {
430
431 @Override
432 public Object updateStatus(String event) {
433 monitor.beginTask(event);
434 return event;
435 }
436
437 @Override
438 public void finish(Object status) {
439 if (status instanceof String) {
440 monitor.finishTask((String) status);
441 }
442 }
443 });
444
445 Collection<PluginInformation> pluginsToLoad = null;
446
447
448 if (!skipLoadingPlugins) {
449 pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
450 if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
451 monitor.subTask(tr("Updating plugins"));
452 pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
453 }
454
455 monitor.indeterminateSubTask(tr("Installing updated plugins"));
456 PluginHandler.installDownloadedPlugins(true);
457
458 monitor.indeterminateSubTask(tr("Loading early plugins"));
459 PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
460 }
461
462 monitor.indeterminateSubTask(tr("Setting defaults"));
463 preConstructorInit(args);
464
465 monitor.indeterminateSubTask(tr("Creating main GUI"));
466 final Main main = new MainApplication(mainFrame);
467
468 if (!skipLoadingPlugins) {
469 monitor.indeterminateSubTask(tr("Loading plugins"));
470 PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
471 toolbar.refreshToolbarControl();
472 }
473
474 // Wait for splash disappearance (fix #9714)
475 GuiHelper.runInEDTAndWait(new Runnable() {
476 @Override
477 public void run() {
478 splash.setVisible(false);
479 splash.dispose();
480 mainFrame.setVisible(true);
481 }
482 });
483
484 Main.MasterWindowListener.setup();
485
486 boolean maximized = Main.pref.getBoolean("gui.maximized", false);
487 if ((!args.containsKey(Option.NO_MAXIMIZE) && maximized) || args.containsKey(Option.MAXIMIZE)) {
488 if (Toolkit.getDefaultToolkit().isFrameStateSupported(JFrame.MAXIMIZED_BOTH)) {
489 Main.windowState = JFrame.MAXIMIZED_BOTH;
490 mainFrame.setExtendedState(Main.windowState);
491 } else {
492 Main.debug("Main window: maximizing not supported");
493 }
494 }
495 if (main.menu.fullscreenToggleAction != null) {
496 main.menu.fullscreenToggleAction.initial();
497 }
498
499 SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
500
501 if (Main.isPlatformWindows()) {
502 try {
503 // Check for insecure certificates to remove.
504 // This is Windows-dependant code but it can't go to preStartupHook (need i18n)
505 // neither startupHook (need to be called before remote control)
506 PlatformHookWindows.removeInsecureCertificates();
507 } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
508 error(e);
509 }
510 }
511
512 if (RemoteControl.PROP_REMOTECONTROL_ENABLED.get()) {
513 RemoteControl.start();
514 }
515
516 if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
517 MessageNotifier.start();
518 }
519
520 if (Main.pref.getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
521 // Repaint manager is registered so late for a reason - there is lots of violation during startup process
522 // but they don't seem to break anything and are difficult to fix
523 info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
524 RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
525 }
526 }
527
528 private static void processOffline(Map<Option, Collection<String>> args) {
529 if (args.containsKey(Option.OFFLINE)) {
530 for (String s : args.get(Option.OFFLINE).iterator().next().split(",")) {
531 try {
532 Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
533 } catch (IllegalArgumentException e) {
534 Main.error(tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
535 s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())));
536 System.exit(1);
537 return;
538 }
539 }
540 Set<OnlineResource> offline = Main.getOfflineResources();
541 if (!offline.isEmpty()) {
542 Main.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
543 "JOSM is running in offline mode. These resources will not be available: {0}",
544 offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
545 }
546 }
547 }
548
549 /**
550 * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
551 * disabling or enabling IPV6 may only be done with next start.
552 */
553 private static void checkIPv6() {
554 if ("auto".equals(Main.pref.get("prefer.ipv6", "auto"))) {
555 new Thread(new Runnable() { /* this may take some time (DNS, Connect) */
556 public void run() {
557 boolean hasv6 = false;
558 boolean wasv6 = Main.pref.getBoolean("validated.ipv6", false);
559 try {
560 /* Use the check result from last run of the software, as after the test, value
561 changes have no effect anymore */
562 if (wasv6) {
563 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
564 }
565 for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
566 if (a instanceof Inet6Address) {
567 if (a.isReachable(1000)) {
568 /* be sure it REALLY works */
569 Socket s = new Socket();
570 s.connect(new InetSocketAddress(a, 80), 1000);
571 s.close();
572 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
573 if (!wasv6) {
574 Main.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4 after next restart."));
575 } else {
576 Main.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4."));
577 }
578 hasv6 = true;
579 }
580 break; /* we're done */
581 }
582 }
583 } catch (IOException | SecurityException e) {
584 if (Main.isDebugEnabled()) {
585 Main.debug("Exception while checking IPv6 connectivity: "+e);
586 }
587 }
588 if (wasv6 && !hasv6) {
589 Main.info(tr("Detected no useable IPv6 network, prefering IPv4 over IPv6 after next restart."));
590 Main.pref.put("validated.ipv6", hasv6); // be sure it is stored before the restart!
591 new RestartAction().actionPerformed(null);
592 }
593 Main.pref.put("validated.ipv6", hasv6);
594 }
595 }, "IPv6-checker").start();
596 }
597 }
598
599 private static class GuiFinalizationWorker implements Runnable {
600
601 private final Map<Option, Collection<String>> args;
602 private final DefaultProxySelector proxySelector;
603
604 GuiFinalizationWorker(Map<Option, Collection<String>> args, DefaultProxySelector proxySelector) {
605 this.args = args;
606 this.proxySelector = proxySelector;
607 }
608
609 @Override
610 public void run() {
611
612 // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
613 if (!handleProxyErrors()) {
614 handleNetworkErrors();
615 }
616
617 // Restore autosave layers after crash and start autosave thread
618 handleAutosave();
619
620 // Handle command line instructions
621 postConstructorProcessCmdLine(args);
622
623 // Show download dialog if autostart is enabled
624 DownloadDialog.autostartIfNeeded();
625 }
626
627 private static void handleAutosave() {
628 if (AutosaveTask.PROP_AUTOSAVE_ENABLED.get()) {
629 AutosaveTask autosaveTask = new AutosaveTask();
630 List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
631 if (!unsavedLayerFiles.isEmpty()) {
632 ExtendedDialog dialog = new ExtendedDialog(
633 Main.parent,
634 tr("Unsaved osm data"),
635 new String[] {tr("Restore"), tr("Cancel"), tr("Discard")}
636 );
637 dialog.setContent(
638 trn("JOSM found {0} unsaved osm data layer. ",
639 "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
640 tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
641 dialog.setButtonIcons(new String[] {"ok", "cancel", "dialogs/delete"});
642 int selection = dialog.showDialog().getValue();
643 if (selection == 1) {
644 autosaveTask.recoverUnsavedLayers();
645 } else if (selection == 3) {
646 autosaveTask.discardUnsavedLayers();
647 }
648 }
649 autosaveTask.schedule();
650 }
651 }
652
653 private boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
654 if (hasErrors) {
655 ExtendedDialog ed = new ExtendedDialog(
656 Main.parent, title,
657 new String[]{tr("Change proxy settings"), tr("Cancel")});
658 ed.setButtonIcons(new String[]{"dialogs/settings", "cancel"}).setCancelButton(2);
659 ed.setMinimumSize(new Dimension(460, 260));
660 ed.setIcon(JOptionPane.WARNING_MESSAGE);
661 ed.setContent(message);
662
663 if (ed.showDialog().getValue() == 1) {
664 PreferencesAction.forPreferenceSubTab(null, null, ProxyPreference.class).run();
665 }
666 }
667 return hasErrors;
668 }
669
670 private boolean handleProxyErrors() {
671 return handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
672 tr("JOSM tried to access the following resources:<br>" +
673 "{0}" +
674 "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
675 "{1}" +
676 "Would you like to change your proxy settings now?",
677 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
678 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
679 ));
680 }
681
682 private boolean handleNetworkErrors() {
683 boolean condition = !NETWORK_ERRORS.isEmpty();
684 if (condition) {
685 Set<String> errors = new TreeSet<>();
686 for (Throwable t : NETWORK_ERRORS.values()) {
687 errors.add(t.toString());
688 }
689 return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
690 tr("JOSM tried to access the following resources:<br>" +
691 "{0}" +
692 "but <b>failed</b> to do so, because of the following network errors:<br>" +
693 "{1}" +
694 "It may be due to a missing proxy configuration.<br>" +
695 "Would you like to change your proxy settings now?",
696 Utils.joinAsHtmlUnorderedList(NETWORK_ERRORS.keySet()),
697 Utils.joinAsHtmlUnorderedList(errors)
698 ));
699 }
700 return false;
701 }
702 }
703}
Note: See TracBrowser for help on using the repository browser.