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

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

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