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

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

see #14741 - rework initialization of Main.Panel so that it is done after PlatformHook.preStartupHook, as any other Swing code

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