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

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

see #15182 - introduce Main.getEditDataSet to avoid unneeded GUI dependence in validator tests and tagging presets

  • Property svn:eol-style set to native
File size: 51.2 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.BorderLayout;
8import java.awt.Dimension;
9import java.awt.GraphicsEnvironment;
10import java.awt.event.KeyEvent;
11import java.io.File;
12import java.io.IOException;
13import java.io.InputStream;
14import java.net.Authenticator;
15import java.net.Inet6Address;
16import java.net.InetAddress;
17import java.net.ProxySelector;
18import java.net.URL;
19import java.security.AllPermission;
20import java.security.CodeSource;
21import java.security.GeneralSecurityException;
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.Collections;
32import java.util.List;
33import java.util.Locale;
34import java.util.Map;
35import java.util.Optional;
36import java.util.Set;
37import java.util.TreeSet;
38import java.util.concurrent.Callable;
39import java.util.concurrent.ExecutorService;
40import java.util.concurrent.Future;
41import java.util.logging.Level;
42import java.util.stream.Collectors;
43import java.util.stream.Stream;
44
45import javax.net.ssl.SSLSocketFactory;
46import javax.swing.Action;
47import javax.swing.InputMap;
48import javax.swing.JComponent;
49import javax.swing.JOptionPane;
50import javax.swing.KeyStroke;
51import javax.swing.LookAndFeel;
52import javax.swing.RepaintManager;
53import javax.swing.SwingUtilities;
54import javax.swing.UIManager;
55import javax.swing.UnsupportedLookAndFeelException;
56
57import org.jdesktop.swinghelper.debug.CheckThreadViolationRepaintManager;
58import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
59import org.openstreetmap.josm.Main;
60import org.openstreetmap.josm.actions.JosmAction;
61import org.openstreetmap.josm.actions.OpenFileAction;
62import org.openstreetmap.josm.actions.PreferencesAction;
63import org.openstreetmap.josm.actions.RestartAction;
64import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
65import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
66import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
67import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
68import org.openstreetmap.josm.actions.mapmode.DrawAction;
69import org.openstreetmap.josm.actions.search.SearchAction;
70import org.openstreetmap.josm.data.Bounds;
71import org.openstreetmap.josm.data.UndoRedoHandler;
72import org.openstreetmap.josm.data.Version;
73import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
74import org.openstreetmap.josm.data.osm.DataSet;
75import org.openstreetmap.josm.data.osm.OsmPrimitive;
76import org.openstreetmap.josm.data.osm.search.SearchMode;
77import org.openstreetmap.josm.data.validation.OsmValidator;
78import org.openstreetmap.josm.gui.ProgramArguments.Option;
79import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
80import org.openstreetmap.josm.gui.download.DownloadDialog;
81import org.openstreetmap.josm.gui.io.CustomConfigurator.XMLCommandProcessor;
82import org.openstreetmap.josm.gui.io.SaveLayersDialog;
83import org.openstreetmap.josm.gui.layer.AutosaveTask;
84import org.openstreetmap.josm.gui.layer.MainLayerManager;
85import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
86import org.openstreetmap.josm.gui.layer.TMSLayer;
87import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
88import org.openstreetmap.josm.gui.preferences.display.LafPreference;
89import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
90import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
91import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
92import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
93import org.openstreetmap.josm.gui.progress.swing.ProgressMonitorExecutor;
94import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
95import org.openstreetmap.josm.gui.util.GuiHelper;
96import org.openstreetmap.josm.gui.util.RedirectInputMap;
97import org.openstreetmap.josm.gui.util.WindowGeometry;
98import org.openstreetmap.josm.io.CertificateAmendment;
99import org.openstreetmap.josm.io.DefaultProxySelector;
100import org.openstreetmap.josm.io.MessageNotifier;
101import org.openstreetmap.josm.io.OnlineResource;
102import org.openstreetmap.josm.io.OsmApi;
103import org.openstreetmap.josm.io.OsmApiInitializationException;
104import org.openstreetmap.josm.io.OsmTransferCanceledException;
105import org.openstreetmap.josm.io.auth.CredentialsManager;
106import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
107import org.openstreetmap.josm.io.protocols.data.Handler;
108import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
109import org.openstreetmap.josm.plugins.PluginHandler;
110import org.openstreetmap.josm.plugins.PluginInformation;
111import org.openstreetmap.josm.tools.FontsManager;
112import org.openstreetmap.josm.tools.HttpClient;
113import org.openstreetmap.josm.tools.I18n;
114import org.openstreetmap.josm.tools.ImageProvider;
115import org.openstreetmap.josm.tools.Logging;
116import org.openstreetmap.josm.tools.OpenBrowser;
117import org.openstreetmap.josm.tools.OsmUrlToBounds;
118import org.openstreetmap.josm.tools.OverpassTurboQueryWizard;
119import org.openstreetmap.josm.tools.PlatformHookWindows;
120import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
121import org.openstreetmap.josm.tools.Shortcut;
122import org.openstreetmap.josm.tools.Territories;
123import org.openstreetmap.josm.tools.Utils;
124import org.openstreetmap.josm.tools.bugreport.BugReport;
125import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
126
127/**
128 * Main window class application.
129 *
130 * @author imi
131 */
132@SuppressWarnings("deprecation")
133public class MainApplication extends Main {
134
135 /**
136 * Command-line arguments used to run the application.
137 */
138 private static final List<String> COMMAND_LINE_ARGS = new ArrayList<>();
139
140 /**
141 * The main menu bar at top of screen.
142 */
143 static MainMenu menu;
144
145 /**
146 * The main panel, required to be static for {@link MapFrameListener} handling.
147 */
148 static MainPanel mainPanel;
149
150 /**
151 * The private content pane of {@link MainFrame}, required to be static for shortcut handling.
152 */
153 static JComponent contentPanePrivate;
154
155 /**
156 * The MapFrame.
157 */
158 static MapFrame map;
159
160 /**
161 * The toolbar preference control to register new actions.
162 */
163 static volatile ToolbarPreferences toolbar;
164
165 private final MainFrame mainFrame;
166
167 /**
168 * The worker thread slave. This is for executing all long and intensive
169 * calculations. The executed runnables are guaranteed to be executed separately and sequential.
170 * @since 12634 (as a replacement to {@code Main.worker})
171 */
172 public static final ExecutorService worker = new ProgressMonitorExecutor("main-worker-%d", Thread.NORM_PRIORITY);
173 static {
174 Main.worker = worker;
175 }
176
177 /**
178 * Provides access to the layers displayed in the main view.
179 */
180 private static final MainLayerManager layerManager = new MainLayerManager();
181
182 /**
183 * The commands undo/redo handler.
184 * @since 12641 (as a replacement to {@code Main.main.undoRedo})
185 */
186 public static final UndoRedoHandler undoRedo = new UndoRedoHandler(); // Must be declared after layerManager
187
188 /**
189 * Listener that sets the enabled state of undo/redo menu entries.
190 */
191 private final CommandQueueListener redoUndoListener = (queueSize, redoSize) -> {
192 menu.undo.setEnabled(queueSize > 0);
193 menu.redo.setEnabled(redoSize > 0);
194 };
195
196 /**
197 * Constructs a new {@code MainApplication} without a window.
198 */
199 public MainApplication() {
200 this(null);
201 }
202
203 /**
204 * Constructs a main frame, ready sized and operating. Does not display the frame.
205 * @param mainFrame The main JFrame of the application
206 * @since 10340
207 */
208 public MainApplication(MainFrame mainFrame) {
209 this.mainFrame = mainFrame;
210 }
211
212 /**
213 * Asks user to update its version of Java.
214 * @param updVersion target update version
215 * @param url download URL
216 * @param major true for a migration towards a major version of Java (8:9), false otherwise
217 * @param eolDate the EOL/expiration date
218 * @since 12270
219 */
220 public static void askUpdateJava(String updVersion, String url, String eolDate, boolean major) {
221 ExtendedDialog ed = new ExtendedDialog(
222 Main.parent,
223 tr("Outdated Java version"),
224 tr("OK"), tr("Update Java"), tr("Cancel"));
225 // Check if the dialog has not already been permanently hidden by user
226 if (!ed.toggleEnable("askUpdateJava"+updVersion).toggleCheckState()) {
227 ed.setButtonIcons("ok", "java", "cancel").setCancelButton(3);
228 ed.setMinimumSize(new Dimension(480, 300));
229 ed.setIcon(JOptionPane.WARNING_MESSAGE);
230 StringBuilder content = new StringBuilder(tr("You are running version {0} of Java.",
231 "<b>"+System.getProperty("java.version")+"</b>")).append("<br><br>");
232 if ("Sun Microsystems Inc.".equals(System.getProperty("java.vendor")) && !platform.isOpenJDK()) {
233 content.append("<b>").append(tr("This version is no longer supported by {0} since {1} and is not recommended for use.",
234 "Oracle", eolDate)).append("</b><br><br>");
235 }
236 content.append("<b>")
237 .append(major ?
238 tr("JOSM will soon stop working with this version; we highly recommend you to update to Java {0}.", updVersion) :
239 tr("You may face critical Java bugs; we highly recommend you to update to Java {0}.", updVersion))
240 .append("</b><br><br>")
241 .append(tr("Would you like to update now ?"));
242 ed.setContent(content.toString());
243
244 if (ed.showDialog().getValue() == 2) {
245 try {
246 platform.openUrl(url);
247 } catch (IOException e) {
248 Logging.warn(e);
249 }
250 }
251 }
252 }
253
254 @Override
255 protected List<InitializationTask> beforeInitializationTasks() {
256 return Arrays.asList(
257 new InitializationTask(tr("Starting file watcher"), fileWatcher::start),
258 new InitializationTask(tr("Executing platform startup hook"), () -> platform.startupHook(MainApplication::askUpdateJava)),
259 new InitializationTask(tr("Building main menu"), this::initializeMainWindow),
260 new InitializationTask(tr("Updating user interface"), () -> {
261 undoRedo.addCommandQueueListener(redoUndoListener);
262 // creating toolbar
263 GuiHelper.runInEDTAndWait(() -> contentPanePrivate.add(toolbar.control, BorderLayout.NORTH));
264 // help shortcut
265 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
266 KeyEvent.VK_F1, Shortcut.DIRECT));
267 }),
268 // This needs to be done before RightAndLefthandTraffic::initialize is called
269 new InitializationTask(tr("Initializing internal boundaries data"), Territories::initialize)
270 );
271 }
272
273 @Override
274 protected Collection<InitializationTask> parallelInitializationTasks() {
275 return Arrays.asList(
276 new InitializationTask(tr("Initializing OSM API"), () -> {
277 // We try to establish an API connection early, so that any API
278 // capabilities are already known to the editor instance. However
279 // if it goes wrong that's not critical at this stage.
280 try {
281 OsmApi.getOsmApi().initialize(null, true);
282 } catch (OsmTransferCanceledException | OsmApiInitializationException e) {
283 Logging.warn(Logging.getErrorMessage(Utils.getRootCause(e)));
284 }
285 }),
286 new InitializationTask(tr("Initializing internal traffic data"), RightAndLefthandTraffic::initialize),
287 new InitializationTask(tr("Initializing validator"), OsmValidator::initialize),
288 new InitializationTask(tr("Initializing presets"), TaggingPresets::initialize),
289 new InitializationTask(tr("Initializing map styles"), MapPaintPreference::initialize),
290 new InitializationTask(tr("Loading imagery preferences"), ImageryPreference::initialize)
291 );
292 }
293
294 @Override
295 protected List<Callable<?>> asynchronousCallableTasks() {
296 return Arrays.asList(
297 OverpassTurboQueryWizard::getInstance
298 );
299 }
300
301 @Override
302 protected List<Runnable> asynchronousRunnableTasks() {
303 return Arrays.asList(
304 TMSLayer::getCache,
305 OsmValidator::initializeTests
306 );
307 }
308
309 @Override
310 protected List<InitializationTask> afterInitializationTasks() {
311 return Arrays.asList(
312 new InitializationTask(tr("Updating user interface"), () -> GuiHelper.runInEDTAndWait(() -> {
313 // hooks for the jmapviewer component
314 FeatureAdapter.registerBrowserAdapter(OpenBrowser::displayUrl);
315 FeatureAdapter.registerTranslationAdapter(I18n::tr);
316 FeatureAdapter.registerLoggingAdapter(name -> Logging.getLogger());
317 // UI update
318 toolbar.refreshToolbarControl();
319 toolbar.control.updateUI();
320 contentPanePrivate.updateUI();
321 }))
322 );
323 }
324
325 /**
326 * Called once at startup to initialize the main window content.
327 * Should set {@link #menu} and {@link #mainPanel}
328 */
329 @SuppressWarnings("deprecation")
330 protected void initializeMainWindow() {
331 if (mainFrame != null) {
332 mainPanel = mainFrame.getPanel();
333 panel = mainPanel;
334 mainFrame.initialize();
335 menu = mainFrame.getMenu();
336 super.menu = menu;
337 } else {
338 // required for running some tests.
339 mainPanel = new MainPanel(layerManager);
340 panel = mainPanel;
341 menu = new MainMenu();
342 super.menu = menu;
343 }
344 mainPanel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
345 mainPanel.reAddListeners();
346 }
347
348 @Override
349 protected void shutdown() {
350 if (!GraphicsEnvironment.isHeadless()) {
351 worker.shutdown();
352 }
353 if (mainFrame != null) {
354 mainFrame.storeState();
355 }
356 if (map != null) {
357 map.rememberToggleDialogWidth();
358 }
359 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
360 layerManager.resetState();
361 super.shutdown();
362 if (!GraphicsEnvironment.isHeadless()) {
363 worker.shutdownNow();
364 }
365 }
366
367 @Override
368 protected Bounds getRealBounds() {
369 return isDisplayingMapView() ? map.mapView.getRealBounds() : null;
370 }
371
372 @Override
373 protected void restoreOldBounds(Bounds oldBounds) {
374 if (isDisplayingMapView()) {
375 map.mapView.zoomTo(oldBounds);
376 }
377 }
378
379 /**
380 * Replies the current selected primitives, from a end-user point of view.
381 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
382 * Indeed, if the user is currently in drawing mode, only the way currently being drawn is returned,
383 * see {@link DrawAction#getInProgressSelection()}.
384 *
385 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
386 * @since 6546
387 */
388 @Override
389 public Collection<OsmPrimitive> getInProgressSelection() {
390 if (map != null && map.mapMode instanceof DrawAction) {
391 return ((DrawAction) map.mapMode).getInProgressSelection();
392 } else {
393 DataSet ds = layerManager.getEditDataSet();
394 if (ds == null) return null;
395 return ds.getSelected();
396 }
397 }
398
399 @Override
400 public DataSet getEditDataSet() {
401 return getLayerManager().getEditDataSet();
402 }
403
404 /**
405 * Returns the command-line arguments used to run the application.
406 * @return the command-line arguments used to run the application
407 * @since 11650
408 */
409 public static List<String> getCommandLineArgs() {
410 return Collections.unmodifiableList(COMMAND_LINE_ARGS);
411 }
412
413 /**
414 * Returns the main layer manager that is used by the map view.
415 * @return The layer manager. The value returned will never change.
416 * @since 12636 (as a replacement to {@code Main.getLayerManager()})
417 */
418 @SuppressWarnings("deprecation")
419 public static MainLayerManager getLayerManager() {
420 return layerManager;
421 }
422
423 /**
424 * Returns the MapFrame.
425 * <p>
426 * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
427 * @return the MapFrame
428 * @see MainPanel
429 * @since 12630 (as a replacement to {@code Main.map})
430 */
431 public static MapFrame getMap() {
432 return map;
433 }
434
435 /**
436 * Returns the main panel.
437 * @return the main panel
438 * @since 12642 (as a replacement to {@code Main.main.panel})
439 */
440 public static MainPanel getMainPanel() {
441 return mainPanel;
442 }
443
444 /**
445 * Returns the main menu, at top of screen.
446 * @return the main menu
447 * @since 12643 (as a replacement to {@code MainApplication.getMenu()})
448 */
449 public static MainMenu getMenu() {
450 return menu;
451 }
452
453 /**
454 * Returns the toolbar preference control to register new actions.
455 * @return the toolbar preference control
456 * @since 12637 (as a replacement to {@code Main.toolbar})
457 */
458 public static ToolbarPreferences getToolbar() {
459 return toolbar;
460 }
461
462 /**
463 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
464 * it only shows the MOTD panel.
465 * <p>
466 * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
467 *
468 * @return <code>true</code> if JOSM currently displays a map view
469 * @since 12630 (as a replacement to {@code Main.isDisplayingMapView()})
470 */
471 @SuppressWarnings("deprecation")
472 public static boolean isDisplayingMapView() {
473 return map != null && map.mapView != null;
474 }
475
476 /**
477 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
478 * If there are some unsaved data layers, asks first for user confirmation.
479 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
480 * @param exitCode The return code
481 * @param reason the reason for exiting
482 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
483 * @since 12636 (specialized version of {@link Main#exitJosm})
484 */
485 public static boolean exitJosm(boolean exit, int exitCode, SaveLayersDialog.Reason reason) {
486 final boolean proceed = Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
487 SaveLayersDialog.saveUnsavedModifications(layerManager.getLayers(),
488 reason != null ? reason : SaveLayersDialog.Reason.EXIT)));
489 if (proceed) {
490 return Main.exitJosm(exit, exitCode);
491 }
492 return false;
493 }
494
495 public static void redirectToMainContentPane(JComponent source) {
496 RedirectInputMap.redirect(source, contentPanePrivate);
497 }
498
499 /**
500 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes.
501 * <p>
502 * It will fire an initial mapFrameInitialized event when the MapFrame is present.
503 * Otherwise will only fire when the MapFrame is created or destroyed.
504 * @param listener The MapFrameListener
505 * @return {@code true} if the listeners collection changed as a result of the call
506 * @see #addMapFrameListener
507 * @since 12639 (as a replacement to {@code Main.addAndFireMapFrameListener})
508 */
509 @SuppressWarnings("deprecation")
510 public static boolean addAndFireMapFrameListener(MapFrameListener listener) {
511 return mainPanel != null && mainPanel.addAndFireMapFrameListener(listener);
512 }
513
514 /**
515 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
516 * @param listener The MapFrameListener
517 * @return {@code true} if the listeners collection changed as a result of the call
518 * @see #addAndFireMapFrameListener
519 * @since 12639 (as a replacement to {@code Main.addMapFrameListener})
520 */
521 @SuppressWarnings("deprecation")
522 public static boolean addMapFrameListener(MapFrameListener listener) {
523 return mainPanel != null && mainPanel.addMapFrameListener(listener);
524 }
525
526 /**
527 * Unregisters the given {@code MapFrameListener} from MapFrame changes
528 * @param listener The MapFrameListener
529 * @return {@code true} if the listeners collection changed as a result of the call
530 * @since 12639 (as a replacement to {@code Main.removeMapFrameListener})
531 */
532 @SuppressWarnings("deprecation")
533 public static boolean removeMapFrameListener(MapFrameListener listener) {
534 return mainPanel != null && mainPanel.removeMapFrameListener(listener);
535 }
536
537 /**
538 * Registers a {@code JosmAction} and its shortcut.
539 * @param action action defining its own shortcut
540 * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
541 */
542 @SuppressWarnings("deprecation")
543 public static void registerActionShortcut(JosmAction action) {
544 registerActionShortcut(action, action.getShortcut());
545 }
546
547 /**
548 * Registers an action and its shortcut.
549 * @param action action to register
550 * @param shortcut shortcut to associate to {@code action}
551 * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
552 */
553 @SuppressWarnings("deprecation")
554 public static void registerActionShortcut(Action action, Shortcut shortcut) {
555 KeyStroke keyStroke = shortcut.getKeyStroke();
556 if (keyStroke == null)
557 return;
558
559 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
560 Object existing = inputMap.get(keyStroke);
561 if (existing != null && !existing.equals(action)) {
562 Logging.info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
563 }
564 inputMap.put(keyStroke, action);
565
566 contentPanePrivate.getActionMap().put(action, action);
567 }
568
569 /**
570 * Unregisters a shortcut.
571 * @param shortcut shortcut to unregister
572 * @since 12639 (as a replacement to {@code Main.unregisterShortcut})
573 */
574 @SuppressWarnings("deprecation")
575 public static void unregisterShortcut(Shortcut shortcut) {
576 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
577 }
578
579 /**
580 * Unregisters a {@code JosmAction} and its shortcut.
581 * @param action action to unregister
582 * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
583 */
584 @SuppressWarnings("deprecation")
585 public static void unregisterActionShortcut(JosmAction action) {
586 unregisterActionShortcut(action, action.getShortcut());
587 }
588
589 /**
590 * Unregisters an action and its shortcut.
591 * @param action action to unregister
592 * @param shortcut shortcut to unregister
593 * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
594 */
595 @SuppressWarnings("deprecation")
596 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
597 unregisterShortcut(shortcut);
598 contentPanePrivate.getActionMap().remove(action);
599 }
600
601 /**
602 * Replies the registered action for the given shortcut
603 * @param shortcut The shortcut to look for
604 * @return the registered action for the given shortcut
605 * @since 12639 (as a replacement to {@code Main.getRegisteredActionShortcut})
606 */
607 @SuppressWarnings("deprecation")
608 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
609 KeyStroke keyStroke = shortcut.getKeyStroke();
610 if (keyStroke == null)
611 return null;
612 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
613 if (action instanceof Action)
614 return (Action) action;
615 return null;
616 }
617
618 /**
619 * Displays help on the console
620 * @since 2748
621 */
622 public static void showHelp() {
623 // TODO: put in a platformHook for system that have no console by default
624 System.out.println(getHelp());
625 }
626
627 static String getHelp() {
628 return tr("Java OpenStreetMap Editor")+" ["
629 +Version.getInstance().getAgentString()+"]\n\n"+
630 tr("usage")+":\n"+
631 "\tjava -jar josm.jar <options>...\n\n"+
632 tr("options")+":\n"+
633 "\t--help|-h "+tr("Show this help")+'\n'+
634 "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+'\n'+
635 "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+'\n'+
636 "\t[--download=]<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z)")+'\n'+
637 "\t[--download=]<filename> "+tr("Open a file (any file type that can be opened with File/Open)")+'\n'+
638 "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw GPS")+'\n'+
639 "\t--downloadgps=<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z) as raw GPS")+'\n'+
640 "\t--selection=<searchstring> "+tr("Select with the given search")+'\n'+
641 "\t--[no-]maximize "+tr("Launch in maximized mode")+'\n'+
642 "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+
643 "\t--load-preferences=<url-to-xml> "+tr("Changes preferences according to the XML file")+"\n\n"+
644 "\t--set=<key>=<value> "+tr("Set preference key to value")+"\n\n"+
645 "\t--language=<language> "+tr("Set the language")+"\n\n"+
646 "\t--version "+tr("Displays the JOSM version and exits")+"\n\n"+
647 "\t--debug "+tr("Print debugging messages to console")+"\n\n"+
648 "\t--skip-plugins "+tr("Skip loading plugins")+"\n\n"+
649 "\t--offline=<osm_api|josm_website|all> "+tr("Disable access to the given resource(s), separated by comma")+"\n\n"+
650 tr("options provided as Java system properties")+":\n"+
651 align("\t-Djosm.dir.name=JOSM") + tr("Change the JOSM directory name") + "\n\n" +
652 align("\t-Djosm.pref=" + tr("/PATH/TO/JOSM/PREF ")) + tr("Set the preferences directory") + "\n" +
653 align("\t") + tr("Default: {0}", platform.getDefaultPrefDirectory()) + "\n\n" +
654 align("\t-Djosm.userdata=" + tr("/PATH/TO/JOSM/USERDATA")) + tr("Set the user data directory") + "\n" +
655 align("\t") + tr("Default: {0}", platform.getDefaultUserDataDirectory()) + "\n\n" +
656 align("\t-Djosm.cache=" + tr("/PATH/TO/JOSM/CACHE ")) + tr("Set the cache directory") + "\n" +
657 align("\t") + tr("Default: {0}", platform.getDefaultCacheDirectory()) + "\n\n" +
658 align("\t-Djosm.home=" + tr("/PATH/TO/JOSM/HOMEDIR ")) +
659 tr("Set the preferences+data+cache directory (cache directory will be josm.home/cache)")+"\n\n"+
660 tr("-Djosm.home has lower precedence, i.e. the specific setting overrides the general one")+"\n\n"+
661 tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
662 " Java option to specify the maximum size of allocated memory in megabytes")+":\n"+
663 "\t-Xmx...m\n\n"+
664 tr("examples")+":\n"+
665 "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
666 "\tjava -jar josm.jar "+OsmUrlToBounds.getURL(43.2, 11.1, 13)+'\n'+
667 "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
668 "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
669 "\tjava -Djosm.pref=$XDG_CONFIG_HOME -Djosm.userdata=$XDG_DATA_HOME -Djosm.cache=$XDG_CACHE_HOME -jar josm.jar\n"+
670 "\tjava -Djosm.dir.name=josm_dev -jar josm.jar\n"+
671 "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
672 "\tjava -Xmx1024m -jar josm.jar\n\n"+
673 tr("Parameters --download, --downloadgps, and --selection are processed in this order.")+'\n'+
674 tr("Make sure you load some data if you use --selection.")+'\n';
675 }
676
677 private static String align(String str) {
678 return str + Stream.generate(() -> " ").limit(Math.max(0, 43 - str.length())).collect(Collectors.joining(""));
679 }
680
681 /**
682 * Main application Startup
683 * @param argArray Command-line arguments
684 */
685 @SuppressWarnings("deprecation")
686 public static void main(final String[] argArray) {
687 I18n.init();
688
689 ProgramArguments args = null;
690 // construct argument table
691 try {
692 args = new ProgramArguments(argArray);
693 } catch (IllegalArgumentException e) {
694 System.err.println(e.getMessage());
695 System.exit(1);
696 return;
697 }
698
699 Level logLevel = args.getLogLevel();
700 Logging.setLogLevel(logLevel);
701 if (!args.showVersion() && !args.showHelp()) {
702 Logging.info(tr("Log level is at {0} ({1}, {2})", logLevel.getLocalizedName(), logLevel.getName(), logLevel.intValue()));
703 }
704
705 Optional<String> language = args.getSingle(Option.LANGUAGE);
706 I18n.set(language.orElse(null));
707
708 Policy.setPolicy(new Policy() {
709 // Permissions for plug-ins loaded when josm is started via webstart
710 private PermissionCollection pc;
711
712 {
713 pc = new Permissions();
714 pc.add(new AllPermission());
715 }
716
717 @Override
718 public PermissionCollection getPermissions(CodeSource codesource) {
719 return pc;
720 }
721 });
722
723 Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
724
725 // initialize the platform hook, and
726 Main.determinePlatformHook();
727 // call the really early hook before we do anything else
728 Main.platform.preStartupHook();
729
730 if (args.showVersion()) {
731 System.out.println(Version.getInstance().getAgentString());
732 return;
733 } else if (args.showHelp()) {
734 showHelp();
735 return;
736 }
737
738 COMMAND_LINE_ARGS.addAll(Arrays.asList(argArray));
739
740 boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
741 if (skipLoadingPlugins) {
742 Logging.info(tr("Plugin loading skipped"));
743 }
744
745 if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
746 // Enable debug in OAuth signpost via system preference, but only at trace level
747 Utils.updateSystemProperty("debug", "true");
748 Logging.info(tr("Enabled detailed debug level (trace)"));
749 }
750
751 Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
752
753 args.getPreferencesToSet().forEach(Main.pref::put);
754
755 if (!language.isPresent()) {
756 I18n.set(Main.pref.get("language", null));
757 }
758 Main.pref.updateSystemProperties();
759
760 checkIPv6();
761
762 processOffline(args);
763
764 Main.platform.afterPrefStartupHook();
765
766 FontsManager.initialize();
767
768 GuiHelper.setupLanguageFonts();
769
770 Handler.install();
771
772 WindowGeometry geometry = WindowGeometry.mainWindow("gui.geometry",
773 args.getSingle(Option.GEOMETRY).orElse(null),
774 !args.hasOption(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
775 final MainFrame mainFrame = new MainFrame(geometry);
776 if (mainFrame.getContentPane() instanceof JComponent) {
777 contentPanePrivate = (JComponent) mainFrame.getContentPane();
778 }
779 mainPanel = mainFrame.getPanel();
780 Main.parent = mainFrame;
781
782 if (args.hasOption(Option.LOAD_PREFERENCES)) {
783 XMLCommandProcessor config = new XMLCommandProcessor(Main.pref);
784 for (String i : args.get(Option.LOAD_PREFERENCES)) {
785 Logging.info("Reading preferences from " + i);
786 try (InputStream is = openStream(new URL(i))) {
787 config.openAndReadXML(is);
788 } catch (IOException ex) {
789 throw BugReport.intercept(ex).put("file", i);
790 }
791 }
792 }
793
794 try {
795 CertificateAmendment.addMissingCertificates();
796 } catch (IOException | GeneralSecurityException ex) {
797 Logging.warn(ex);
798 Logging.warn(Logging.getErrorMessage(Utils.getRootCause(ex)));
799 }
800 Authenticator.setDefault(DefaultAuthenticator.getInstance());
801 DefaultProxySelector proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
802 ProxySelector.setDefault(proxySelector);
803 OAuthAccessTokenHolder.getInstance().init(Main.pref, CredentialsManager.getInstance());
804
805 final SplashScreen splash = GuiHelper.runInEDTAndWaitAndReturn(SplashScreen::new);
806 final SplashScreen.SplashProgressMonitor monitor = splash.getProgressMonitor();
807 monitor.beginTask(tr("Initializing"));
808 GuiHelper.runInEDT(() -> splash.setVisible(Main.pref.getBoolean("draw.splashscreen", true)));
809 Main.setInitStatusListener(new InitStatusListener() {
810
811 @Override
812 public Object updateStatus(String event) {
813 monitor.beginTask(event);
814 return event;
815 }
816
817 @Override
818 public void finish(Object status) {
819 if (status instanceof String) {
820 monitor.finishTask((String) status);
821 }
822 }
823 });
824
825 Collection<PluginInformation> pluginsToLoad = null;
826
827 if (!skipLoadingPlugins) {
828 pluginsToLoad = updateAndLoadEarlyPlugins(splash, monitor);
829 }
830
831 monitor.indeterminateSubTask(tr("Setting defaults"));
832 setupUIManager();
833 toolbar = new ToolbarPreferences();
834 Main.toolbar = toolbar;
835 ProjectionPreference.setProjection();
836 GuiHelper.translateJavaInternalMessages();
837 preConstructorInit();
838
839 monitor.indeterminateSubTask(tr("Creating main GUI"));
840 final Main main = new MainApplication(mainFrame);
841 main.initialize();
842
843 if (!skipLoadingPlugins) {
844 loadLatePlugins(splash, monitor, pluginsToLoad);
845 }
846
847 // Wait for splash disappearance (fix #9714)
848 GuiHelper.runInEDTAndWait(() -> {
849 splash.setVisible(false);
850 splash.dispose();
851 mainFrame.setVisible(true);
852 });
853
854 boolean maximized = Main.pref.getBoolean("gui.maximized", false);
855 if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
856 mainFrame.setMaximized(true);
857 }
858 if (main.menu.fullscreenToggleAction != null) {
859 main.menu.fullscreenToggleAction.initial();
860 }
861
862 SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
863
864 if (Main.isPlatformWindows()) {
865 try {
866 // Check for insecure certificates to remove.
867 // This is Windows-dependant code but it can't go to preStartupHook (need i18n)
868 // neither startupHook (need to be called before remote control)
869 PlatformHookWindows.removeInsecureCertificates();
870 } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
871 Logging.error(e);
872 }
873 }
874
875 if (RemoteControl.PROP_REMOTECONTROL_ENABLED.get()) {
876 RemoteControl.start();
877 }
878
879 if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
880 MessageNotifier.start();
881 }
882
883 if (Main.pref.getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
884 // Repaint manager is registered so late for a reason - there is lots of violation during startup process
885 // but they don't seem to break anything and are difficult to fix
886 Logging.info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
887 RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
888 }
889 }
890
891 static void setupUIManager() {
892 String defaultlaf = platform.getDefaultStyle();
893 String laf = LafPreference.LAF.get();
894 try {
895 UIManager.setLookAndFeel(laf);
896 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
897 // Try to find look and feel in plugin classloaders
898 Logging.trace(e);
899 Class<?> klass = null;
900 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
901 try {
902 klass = cl.loadClass(laf);
903 break;
904 } catch (ClassNotFoundException ex) {
905 Logging.trace(ex);
906 }
907 }
908 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
909 try {
910 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
911 } catch (ReflectiveOperationException ex) {
912 Logging.log(Logging.LEVEL_WARN, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage(), ex);
913 } catch (UnsupportedLookAndFeelException ex) {
914 Logging.info("Look and Feel not supported: " + laf);
915 LafPreference.LAF.put(defaultlaf);
916 Logging.trace(ex);
917 }
918 } else {
919 Logging.info("Look and Feel not found: " + laf);
920 LafPreference.LAF.put(defaultlaf);
921 }
922 } catch (UnsupportedLookAndFeelException e) {
923 Logging.info("Look and Feel not supported: " + laf);
924 LafPreference.LAF.put(defaultlaf);
925 Logging.trace(e);
926 } catch (InstantiationException | IllegalAccessException e) {
927 Logging.error(e);
928 }
929
930 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
931 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
932 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
933 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
934 // Ensures caret color is the same than text foreground color, see #12257
935 // See http://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
936 for (String p : Arrays.asList(
937 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
938 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
939 }
940 }
941
942 private static InputStream openStream(URL url) throws IOException {
943 if ("file".equals(url.getProtocol())) {
944 return url.openStream();
945 } else {
946 return HttpClient.create(url).connect().getContent();
947 }
948 }
949
950 static Collection<PluginInformation> updateAndLoadEarlyPlugins(SplashScreen splash, SplashProgressMonitor monitor) {
951 Collection<PluginInformation> pluginsToLoad;
952 pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
953 if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
954 monitor.subTask(tr("Updating plugins"));
955 pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
956 }
957
958 monitor.indeterminateSubTask(tr("Installing updated plugins"));
959 PluginHandler.installDownloadedPlugins(true);
960
961 monitor.indeterminateSubTask(tr("Loading early plugins"));
962 PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
963 return pluginsToLoad;
964 }
965
966 static void loadLatePlugins(SplashScreen splash, SplashProgressMonitor monitor, Collection<PluginInformation> pluginsToLoad) {
967 monitor.indeterminateSubTask(tr("Loading plugins"));
968 PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
969 GuiHelper.runInEDTAndWait(() -> toolbar.refreshToolbarControl());
970 }
971
972 private static void processOffline(ProgramArguments args) {
973 for (String offlineNames : args.get(Option.OFFLINE)) {
974 for (String s : offlineNames.split(",")) {
975 try {
976 Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
977 } catch (IllegalArgumentException e) {
978 Logging.log(Logging.LEVEL_ERROR,
979 tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
980 s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())), e);
981 System.exit(1);
982 return;
983 }
984 }
985 }
986 Set<OnlineResource> offline = Main.getOfflineResources();
987 if (!offline.isEmpty()) {
988 Logging.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
989 "JOSM is running in offline mode. These resources will not be available: {0}",
990 offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
991 }
992 }
993
994 /**
995 * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
996 * disabling or enabling IPV6 may only be done with next start.
997 */
998 private static void checkIPv6() {
999 if ("auto".equals(Main.pref.get("prefer.ipv6", "auto"))) {
1000 new Thread((Runnable) () -> { /* this may take some time (DNS, Connect) */
1001 boolean hasv6 = false;
1002 boolean wasv6 = Main.pref.getBoolean("validated.ipv6", false);
1003 try {
1004 /* Use the check result from last run of the software, as after the test, value
1005 changes have no effect anymore */
1006 if (wasv6) {
1007 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1008 }
1009 for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
1010 if (a instanceof Inet6Address) {
1011 if (a.isReachable(1000)) {
1012 /* be sure it REALLY works */
1013 SSLSocketFactory.getDefault().createSocket(a, 443).close();
1014 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1015 if (!wasv6) {
1016 Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4 after next restart."));
1017 } else {
1018 Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4."));
1019 }
1020 hasv6 = true;
1021 }
1022 break; /* we're done */
1023 }
1024 }
1025 } catch (IOException | SecurityException e) {
1026 Logging.debug("Exception while checking IPv6 connectivity: {0}", e);
1027 Logging.trace(e);
1028 }
1029 if (wasv6 && !hasv6) {
1030 Logging.info(tr("Detected no useable IPv6 network, prefering IPv4 over IPv6 after next restart."));
1031 Main.pref.put("validated.ipv6", hasv6); // be sure it is stored before the restart!
1032 try {
1033 RestartAction.restartJOSM();
1034 } catch (IOException e) {
1035 Logging.error(e);
1036 }
1037 }
1038 Main.pref.put("validated.ipv6", hasv6);
1039 }, "IPv6-checker").start();
1040 }
1041 }
1042
1043 /**
1044 * Download area specified as Bounds value.
1045 * @param rawGps Flag to download raw GPS tracks
1046 * @param b The bounds value
1047 * @return the complete download task (including post-download handler)
1048 */
1049 static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
1050 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1051 // asynchronously launch the download task ...
1052 Future<?> future = task.download(true, b, null);
1053 // ... and the continuation when the download is finished (this will wait for the download to finish)
1054 return Collections.singletonList(MainApplication.worker.submit(new PostDownloadHandler(task, future)));
1055 }
1056
1057 /**
1058 * Handle command line instructions after GUI has been initialized.
1059 * @param args program arguments
1060 * @return the list of submitted tasks
1061 */
1062 static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
1063 List<Future<?>> tasks = new ArrayList<>();
1064 List<File> fileList = new ArrayList<>();
1065 for (String s : args.get(Option.DOWNLOAD)) {
1066 tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
1067 }
1068 if (!fileList.isEmpty()) {
1069 tasks.add(OpenFileAction.openFiles(fileList, true));
1070 }
1071 for (String s : args.get(Option.DOWNLOADGPS)) {
1072 tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
1073 }
1074 final Collection<String> selectionArguments = args.get(Option.SELECTION);
1075 if (!selectionArguments.isEmpty()) {
1076 tasks.add(MainApplication.worker.submit(() -> {
1077 for (String s : selectionArguments) {
1078 SearchAction.search(s, SearchMode.add);
1079 }
1080 }));
1081 }
1082 return tasks;
1083 }
1084
1085 private static class GuiFinalizationWorker implements Runnable {
1086
1087 private final ProgramArguments args;
1088 private final DefaultProxySelector proxySelector;
1089
1090 GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
1091 this.args = args;
1092 this.proxySelector = proxySelector;
1093 }
1094
1095 @Override
1096 public void run() {
1097
1098 // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
1099 if (!handleProxyErrors()) {
1100 handleNetworkErrors();
1101 }
1102
1103 // Restore autosave layers after crash and start autosave thread
1104 handleAutosave();
1105
1106 // Handle command line instructions
1107 postConstructorProcessCmdLine(args);
1108
1109 // Show download dialog if autostart is enabled
1110 DownloadDialog.autostartIfNeeded();
1111 }
1112
1113 private static void handleAutosave() {
1114 if (AutosaveTask.PROP_AUTOSAVE_ENABLED.get()) {
1115 AutosaveTask autosaveTask = new AutosaveTask();
1116 List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
1117 if (!unsavedLayerFiles.isEmpty()) {
1118 ExtendedDialog dialog = new ExtendedDialog(
1119 Main.parent,
1120 tr("Unsaved osm data"),
1121 tr("Restore"), tr("Cancel"), tr("Discard")
1122 );
1123 dialog.setContent(
1124 trn("JOSM found {0} unsaved osm data layer. ",
1125 "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
1126 tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
1127 dialog.setButtonIcons("ok", "cancel", "dialogs/delete");
1128 int selection = dialog.showDialog().getValue();
1129 if (selection == 1) {
1130 autosaveTask.recoverUnsavedLayers();
1131 } else if (selection == 3) {
1132 autosaveTask.discardUnsavedLayers();
1133 }
1134 }
1135 autosaveTask.schedule();
1136 }
1137 }
1138
1139 private static boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
1140 if (hasErrors) {
1141 ExtendedDialog ed = new ExtendedDialog(
1142 Main.parent, title,
1143 tr("Change proxy settings"), tr("Cancel"));
1144 ed.setButtonIcons("dialogs/settings", "cancel").setCancelButton(2);
1145 ed.setMinimumSize(new Dimension(460, 260));
1146 ed.setIcon(JOptionPane.WARNING_MESSAGE);
1147 ed.setContent(message);
1148
1149 if (ed.showDialog().getValue() == 1) {
1150 PreferencesAction.forPreferenceSubTab(null, null, ProxyPreference.class).run();
1151 }
1152 }
1153 return hasErrors;
1154 }
1155
1156 private boolean handleProxyErrors() {
1157 return handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
1158 tr("JOSM tried to access the following resources:<br>" +
1159 "{0}" +
1160 "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
1161 "{1}" +
1162 "Would you like to change your proxy settings now?",
1163 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
1164 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
1165 ));
1166 }
1167
1168 private static boolean handleNetworkErrors() {
1169 Map<String, Throwable> networkErrors = Main.getNetworkErrors();
1170 boolean condition = !networkErrors.isEmpty();
1171 if (condition) {
1172 Set<String> errors = new TreeSet<>();
1173 for (Throwable t : networkErrors.values()) {
1174 errors.add(t.toString());
1175 }
1176 return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
1177 tr("JOSM tried to access the following resources:<br>" +
1178 "{0}" +
1179 "but <b>failed</b> to do so, because of the following network errors:<br>" +
1180 "{1}" +
1181 "It may be due to a missing proxy configuration.<br>" +
1182 "Would you like to change your proxy settings now?",
1183 Utils.joinAsHtmlUnorderedList(networkErrors.keySet()),
1184 Utils.joinAsHtmlUnorderedList(errors)
1185 ));
1186 }
1187 return false;
1188 }
1189 }
1190}
Note: See TracBrowser for help on using the repository browser.