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

Last change on this file since 10482 was 10467, checked in by Don-vip, 8 years ago

fix #13037 - Small fixes for unit tests (patch by michael2402) - gsoc-core

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