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

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

fix Checkstyle issues

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