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

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

fix many checkstyle violations

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