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

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

see #14741 - rework initialization of Main.contentPanePrivate

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