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

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

see #15182 - remove dependence on GUI for tools.PlatformHook

  • Property svn:eol-style set to native
File size: 51.1 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.osm.DataSet;
74import org.openstreetmap.josm.data.osm.OsmPrimitive;
75import org.openstreetmap.josm.data.osm.search.SearchMode;
76import org.openstreetmap.josm.data.validation.OsmValidator;
77import org.openstreetmap.josm.gui.ProgramArguments.Option;
78import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
79import org.openstreetmap.josm.gui.download.DownloadDialog;
80import org.openstreetmap.josm.gui.io.CustomConfigurator.XMLCommandProcessor;
81import org.openstreetmap.josm.gui.io.SaveLayersDialog;
82import org.openstreetmap.josm.gui.layer.AutosaveTask;
83import org.openstreetmap.josm.gui.layer.MainLayerManager;
84import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
85import org.openstreetmap.josm.gui.layer.TMSLayer;
86import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
87import org.openstreetmap.josm.gui.preferences.display.LafPreference;
88import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
89import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
90import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
91import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
92import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
93import org.openstreetmap.josm.gui.progress.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.io.CertificateAmendment;
98import org.openstreetmap.josm.io.DefaultProxySelector;
99import org.openstreetmap.josm.io.MessageNotifier;
100import org.openstreetmap.josm.io.OnlineResource;
101import org.openstreetmap.josm.io.OsmApi;
102import org.openstreetmap.josm.io.OsmApiInitializationException;
103import org.openstreetmap.josm.io.OsmTransferCanceledException;
104import org.openstreetmap.josm.io.auth.CredentialsManager;
105import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
106import org.openstreetmap.josm.io.protocols.data.Handler;
107import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
108import org.openstreetmap.josm.plugins.PluginHandler;
109import org.openstreetmap.josm.plugins.PluginInformation;
110import org.openstreetmap.josm.tools.FontsManager;
111import org.openstreetmap.josm.tools.HttpClient;
112import org.openstreetmap.josm.tools.I18n;
113import org.openstreetmap.josm.tools.ImageProvider;
114import org.openstreetmap.josm.tools.Logging;
115import org.openstreetmap.josm.tools.OpenBrowser;
116import org.openstreetmap.josm.tools.OsmUrlToBounds;
117import org.openstreetmap.josm.tools.OverpassTurboQueryWizard;
118import org.openstreetmap.josm.tools.PlatformHookWindows;
119import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
120import org.openstreetmap.josm.tools.Shortcut;
121import org.openstreetmap.josm.tools.Territories;
122import org.openstreetmap.josm.tools.Utils;
123import org.openstreetmap.josm.tools.WindowGeometry;
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 /**
400 * Returns the command-line arguments used to run the application.
401 * @return the command-line arguments used to run the application
402 * @since 11650
403 */
404 public static List<String> getCommandLineArgs() {
405 return Collections.unmodifiableList(COMMAND_LINE_ARGS);
406 }
407
408 /**
409 * Returns the main layer manager that is used by the map view.
410 * @return The layer manager. The value returned will never change.
411 * @since 12636 (as a replacement to {@code Main.getLayerManager()})
412 */
413 @SuppressWarnings("deprecation")
414 public static MainLayerManager getLayerManager() {
415 return layerManager;
416 }
417
418 /**
419 * Returns the MapFrame.
420 * <p>
421 * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
422 * @return the MapFrame
423 * @see MainPanel
424 * @since 12630 (as a replacement to {@code Main.map})
425 */
426 public static MapFrame getMap() {
427 return map;
428 }
429
430 /**
431 * Returns the main panel.
432 * @return the main panel
433 * @since 12642 (as a replacement to {@code Main.main.panel})
434 */
435 public static MainPanel getMainPanel() {
436 return mainPanel;
437 }
438
439 /**
440 * Returns the main menu, at top of screen.
441 * @return the main menu
442 * @since 12643 (as a replacement to {@code MainApplication.getMenu()})
443 */
444 public static MainMenu getMenu() {
445 return menu;
446 }
447
448 /**
449 * Returns the toolbar preference control to register new actions.
450 * @return the toolbar preference control
451 * @since 12637 (as a replacement to {@code Main.toolbar})
452 */
453 public static ToolbarPreferences getToolbar() {
454 return toolbar;
455 }
456
457 /**
458 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
459 * it only shows the MOTD panel.
460 * <p>
461 * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
462 *
463 * @return <code>true</code> if JOSM currently displays a map view
464 * @since 12630 (as a replacement to {@code Main.isDisplayingMapView()})
465 */
466 @SuppressWarnings("deprecation")
467 public static boolean isDisplayingMapView() {
468 return map != null && map.mapView != null;
469 }
470
471 /**
472 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
473 * If there are some unsaved data layers, asks first for user confirmation.
474 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
475 * @param exitCode The return code
476 * @param reason the reason for exiting
477 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
478 * @since 12636 (specialized version of {@link Main#exitJosm})
479 */
480 public static boolean exitJosm(boolean exit, int exitCode, SaveLayersDialog.Reason reason) {
481 final boolean proceed = Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
482 SaveLayersDialog.saveUnsavedModifications(layerManager.getLayers(),
483 reason != null ? reason : SaveLayersDialog.Reason.EXIT)));
484 if (proceed) {
485 return Main.exitJosm(exit, exitCode);
486 }
487 return false;
488 }
489
490 public static void redirectToMainContentPane(JComponent source) {
491 RedirectInputMap.redirect(source, contentPanePrivate);
492 }
493
494 /**
495 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes.
496 * <p>
497 * It will fire an initial mapFrameInitialized event when the MapFrame is present.
498 * Otherwise will only fire when the MapFrame is created or destroyed.
499 * @param listener The MapFrameListener
500 * @return {@code true} if the listeners collection changed as a result of the call
501 * @see #addMapFrameListener
502 * @since 12639 (as a replacement to {@code Main.addAndFireMapFrameListener})
503 */
504 @SuppressWarnings("deprecation")
505 public static boolean addAndFireMapFrameListener(MapFrameListener listener) {
506 return mainPanel != null && mainPanel.addAndFireMapFrameListener(listener);
507 }
508
509 /**
510 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
511 * @param listener The MapFrameListener
512 * @return {@code true} if the listeners collection changed as a result of the call
513 * @see #addAndFireMapFrameListener
514 * @since 12639 (as a replacement to {@code Main.addMapFrameListener})
515 */
516 @SuppressWarnings("deprecation")
517 public static boolean addMapFrameListener(MapFrameListener listener) {
518 return mainPanel != null && mainPanel.addMapFrameListener(listener);
519 }
520
521 /**
522 * Unregisters the given {@code MapFrameListener} from MapFrame changes
523 * @param listener The MapFrameListener
524 * @return {@code true} if the listeners collection changed as a result of the call
525 * @since 12639 (as a replacement to {@code Main.removeMapFrameListener})
526 */
527 @SuppressWarnings("deprecation")
528 public static boolean removeMapFrameListener(MapFrameListener listener) {
529 return mainPanel != null && mainPanel.removeMapFrameListener(listener);
530 }
531
532 /**
533 * Registers a {@code JosmAction} and its shortcut.
534 * @param action action defining its own shortcut
535 * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
536 */
537 @SuppressWarnings("deprecation")
538 public static void registerActionShortcut(JosmAction action) {
539 registerActionShortcut(action, action.getShortcut());
540 }
541
542 /**
543 * Registers an action and its shortcut.
544 * @param action action to register
545 * @param shortcut shortcut to associate to {@code action}
546 * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
547 */
548 @SuppressWarnings("deprecation")
549 public static void registerActionShortcut(Action action, Shortcut shortcut) {
550 KeyStroke keyStroke = shortcut.getKeyStroke();
551 if (keyStroke == null)
552 return;
553
554 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
555 Object existing = inputMap.get(keyStroke);
556 if (existing != null && !existing.equals(action)) {
557 Logging.info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
558 }
559 inputMap.put(keyStroke, action);
560
561 contentPanePrivate.getActionMap().put(action, action);
562 }
563
564 /**
565 * Unregisters a shortcut.
566 * @param shortcut shortcut to unregister
567 * @since 12639 (as a replacement to {@code Main.unregisterShortcut})
568 */
569 @SuppressWarnings("deprecation")
570 public static void unregisterShortcut(Shortcut shortcut) {
571 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
572 }
573
574 /**
575 * Unregisters a {@code JosmAction} and its shortcut.
576 * @param action action to unregister
577 * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
578 */
579 @SuppressWarnings("deprecation")
580 public static void unregisterActionShortcut(JosmAction action) {
581 unregisterActionShortcut(action, action.getShortcut());
582 }
583
584 /**
585 * Unregisters an action and its shortcut.
586 * @param action action to unregister
587 * @param shortcut shortcut to unregister
588 * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
589 */
590 @SuppressWarnings("deprecation")
591 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
592 unregisterShortcut(shortcut);
593 contentPanePrivate.getActionMap().remove(action);
594 }
595
596 /**
597 * Replies the registered action for the given shortcut
598 * @param shortcut The shortcut to look for
599 * @return the registered action for the given shortcut
600 * @since 12639 (as a replacement to {@code Main.getRegisteredActionShortcut})
601 */
602 @SuppressWarnings("deprecation")
603 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
604 KeyStroke keyStroke = shortcut.getKeyStroke();
605 if (keyStroke == null)
606 return null;
607 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
608 if (action instanceof Action)
609 return (Action) action;
610 return null;
611 }
612
613 /**
614 * Displays help on the console
615 * @since 2748
616 */
617 public static void showHelp() {
618 // TODO: put in a platformHook for system that have no console by default
619 System.out.println(getHelp());
620 }
621
622 static String getHelp() {
623 return tr("Java OpenStreetMap Editor")+" ["
624 +Version.getInstance().getAgentString()+"]\n\n"+
625 tr("usage")+":\n"+
626 "\tjava -jar josm.jar <options>...\n\n"+
627 tr("options")+":\n"+
628 "\t--help|-h "+tr("Show this help")+'\n'+
629 "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+'\n'+
630 "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+'\n'+
631 "\t[--download=]<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z)")+'\n'+
632 "\t[--download=]<filename> "+tr("Open a file (any file type that can be opened with File/Open)")+'\n'+
633 "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw GPS")+'\n'+
634 "\t--downloadgps=<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z) as raw GPS")+'\n'+
635 "\t--selection=<searchstring> "+tr("Select with the given search")+'\n'+
636 "\t--[no-]maximize "+tr("Launch in maximized mode")+'\n'+
637 "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+
638 "\t--load-preferences=<url-to-xml> "+tr("Changes preferences according to the XML file")+"\n\n"+
639 "\t--set=<key>=<value> "+tr("Set preference key to value")+"\n\n"+
640 "\t--language=<language> "+tr("Set the language")+"\n\n"+
641 "\t--version "+tr("Displays the JOSM version and exits")+"\n\n"+
642 "\t--debug "+tr("Print debugging messages to console")+"\n\n"+
643 "\t--skip-plugins "+tr("Skip loading plugins")+"\n\n"+
644 "\t--offline=<osm_api|josm_website|all> "+tr("Disable access to the given resource(s), separated by comma")+"\n\n"+
645 tr("options provided as Java system properties")+":\n"+
646 align("\t-Djosm.dir.name=JOSM") + tr("Change the JOSM directory name") + "\n\n" +
647 align("\t-Djosm.pref=" + tr("/PATH/TO/JOSM/PREF ")) + tr("Set the preferences directory") + "\n" +
648 align("\t") + tr("Default: {0}", platform.getDefaultPrefDirectory()) + "\n\n" +
649 align("\t-Djosm.userdata=" + tr("/PATH/TO/JOSM/USERDATA")) + tr("Set the user data directory") + "\n" +
650 align("\t") + tr("Default: {0}", platform.getDefaultUserDataDirectory()) + "\n\n" +
651 align("\t-Djosm.cache=" + tr("/PATH/TO/JOSM/CACHE ")) + tr("Set the cache directory") + "\n" +
652 align("\t") + tr("Default: {0}", platform.getDefaultCacheDirectory()) + "\n\n" +
653 align("\t-Djosm.home=" + tr("/PATH/TO/JOSM/HOMEDIR ")) +
654 tr("Set the preferences+data+cache directory (cache directory will be josm.home/cache)")+"\n\n"+
655 tr("-Djosm.home has lower precedence, i.e. the specific setting overrides the general one")+"\n\n"+
656 tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
657 " Java option to specify the maximum size of allocated memory in megabytes")+":\n"+
658 "\t-Xmx...m\n\n"+
659 tr("examples")+":\n"+
660 "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
661 "\tjava -jar josm.jar "+OsmUrlToBounds.getURL(43.2, 11.1, 13)+'\n'+
662 "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
663 "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
664 "\tjava -Djosm.pref=$XDG_CONFIG_HOME -Djosm.userdata=$XDG_DATA_HOME -Djosm.cache=$XDG_CACHE_HOME -jar josm.jar\n"+
665 "\tjava -Djosm.dir.name=josm_dev -jar josm.jar\n"+
666 "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
667 "\tjava -Xmx1024m -jar josm.jar\n\n"+
668 tr("Parameters --download, --downloadgps, and --selection are processed in this order.")+'\n'+
669 tr("Make sure you load some data if you use --selection.")+'\n';
670 }
671
672 private static String align(String str) {
673 return str + Stream.generate(() -> " ").limit(Math.max(0, 43 - str.length())).collect(Collectors.joining(""));
674 }
675
676 /**
677 * Main application Startup
678 * @param argArray Command-line arguments
679 */
680 @SuppressWarnings("deprecation")
681 public static void main(final String[] argArray) {
682 I18n.init();
683
684 ProgramArguments args = null;
685 // construct argument table
686 try {
687 args = new ProgramArguments(argArray);
688 } catch (IllegalArgumentException e) {
689 System.err.println(e.getMessage());
690 System.exit(1);
691 return;
692 }
693
694 Level logLevel = args.getLogLevel();
695 Logging.setLogLevel(logLevel);
696 if (!args.showVersion() && !args.showHelp()) {
697 Logging.info(tr("Log level is at {0} ({1}, {2})", logLevel.getLocalizedName(), logLevel.getName(), logLevel.intValue()));
698 }
699
700 Optional<String> language = args.getSingle(Option.LANGUAGE);
701 I18n.set(language.orElse(null));
702
703 Policy.setPolicy(new Policy() {
704 // Permissions for plug-ins loaded when josm is started via webstart
705 private PermissionCollection pc;
706
707 {
708 pc = new Permissions();
709 pc.add(new AllPermission());
710 }
711
712 @Override
713 public PermissionCollection getPermissions(CodeSource codesource) {
714 return pc;
715 }
716 });
717
718 Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
719
720 // initialize the platform hook, and
721 Main.determinePlatformHook();
722 // call the really early hook before we do anything else
723 Main.platform.preStartupHook();
724
725 if (args.showVersion()) {
726 System.out.println(Version.getInstance().getAgentString());
727 return;
728 } else if (args.showHelp()) {
729 showHelp();
730 return;
731 }
732
733 COMMAND_LINE_ARGS.addAll(Arrays.asList(argArray));
734
735 boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
736 if (skipLoadingPlugins) {
737 Logging.info(tr("Plugin loading skipped"));
738 }
739
740 if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
741 // Enable debug in OAuth signpost via system preference, but only at trace level
742 Utils.updateSystemProperty("debug", "true");
743 Logging.info(tr("Enabled detailed debug level (trace)"));
744 }
745
746 Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
747
748 args.getPreferencesToSet().forEach(Main.pref::put);
749
750 if (!language.isPresent()) {
751 I18n.set(Main.pref.get("language", null));
752 }
753 Main.pref.updateSystemProperties();
754
755 checkIPv6();
756
757 processOffline(args);
758
759 Main.platform.afterPrefStartupHook();
760
761 FontsManager.initialize();
762
763 GuiHelper.setupLanguageFonts();
764
765 Handler.install();
766
767 WindowGeometry geometry = WindowGeometry.mainWindow("gui.geometry",
768 args.getSingle(Option.GEOMETRY).orElse(null),
769 !args.hasOption(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
770 final MainFrame mainFrame = new MainFrame(geometry);
771 if (mainFrame.getContentPane() instanceof JComponent) {
772 contentPanePrivate = (JComponent) mainFrame.getContentPane();
773 }
774 mainPanel = mainFrame.getPanel();
775 Main.parent = mainFrame;
776
777 if (args.hasOption(Option.LOAD_PREFERENCES)) {
778 XMLCommandProcessor config = new XMLCommandProcessor(Main.pref);
779 for (String i : args.get(Option.LOAD_PREFERENCES)) {
780 Logging.info("Reading preferences from " + i);
781 try (InputStream is = openStream(new URL(i))) {
782 config.openAndReadXML(is);
783 } catch (IOException ex) {
784 throw BugReport.intercept(ex).put("file", i);
785 }
786 }
787 }
788
789 try {
790 CertificateAmendment.addMissingCertificates();
791 } catch (IOException | GeneralSecurityException ex) {
792 Logging.warn(ex);
793 Logging.warn(Logging.getErrorMessage(Utils.getRootCause(ex)));
794 }
795 Authenticator.setDefault(DefaultAuthenticator.getInstance());
796 DefaultProxySelector proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
797 ProxySelector.setDefault(proxySelector);
798 OAuthAccessTokenHolder.getInstance().init(Main.pref, CredentialsManager.getInstance());
799
800 final SplashScreen splash = GuiHelper.runInEDTAndWaitAndReturn(SplashScreen::new);
801 final SplashScreen.SplashProgressMonitor monitor = splash.getProgressMonitor();
802 monitor.beginTask(tr("Initializing"));
803 GuiHelper.runInEDT(() -> splash.setVisible(Main.pref.getBoolean("draw.splashscreen", true)));
804 Main.setInitStatusListener(new InitStatusListener() {
805
806 @Override
807 public Object updateStatus(String event) {
808 monitor.beginTask(event);
809 return event;
810 }
811
812 @Override
813 public void finish(Object status) {
814 if (status instanceof String) {
815 monitor.finishTask((String) status);
816 }
817 }
818 });
819
820 Collection<PluginInformation> pluginsToLoad = null;
821
822 if (!skipLoadingPlugins) {
823 pluginsToLoad = updateAndLoadEarlyPlugins(splash, monitor);
824 }
825
826 monitor.indeterminateSubTask(tr("Setting defaults"));
827 setupUIManager();
828 toolbar = new ToolbarPreferences();
829 Main.toolbar = toolbar;
830 ProjectionPreference.setProjection();
831 GuiHelper.translateJavaInternalMessages();
832 preConstructorInit();
833
834 monitor.indeterminateSubTask(tr("Creating main GUI"));
835 final Main main = new MainApplication(mainFrame);
836 main.initialize();
837
838 if (!skipLoadingPlugins) {
839 loadLatePlugins(splash, monitor, pluginsToLoad);
840 }
841
842 // Wait for splash disappearance (fix #9714)
843 GuiHelper.runInEDTAndWait(() -> {
844 splash.setVisible(false);
845 splash.dispose();
846 mainFrame.setVisible(true);
847 });
848
849 boolean maximized = Main.pref.getBoolean("gui.maximized", false);
850 if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
851 mainFrame.setMaximized(true);
852 }
853 if (main.menu.fullscreenToggleAction != null) {
854 main.menu.fullscreenToggleAction.initial();
855 }
856
857 SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
858
859 if (Main.isPlatformWindows()) {
860 try {
861 // Check for insecure certificates to remove.
862 // This is Windows-dependant code but it can't go to preStartupHook (need i18n)
863 // neither startupHook (need to be called before remote control)
864 PlatformHookWindows.removeInsecureCertificates();
865 } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
866 Logging.error(e);
867 }
868 }
869
870 if (RemoteControl.PROP_REMOTECONTROL_ENABLED.get()) {
871 RemoteControl.start();
872 }
873
874 if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
875 MessageNotifier.start();
876 }
877
878 if (Main.pref.getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
879 // Repaint manager is registered so late for a reason - there is lots of violation during startup process
880 // but they don't seem to break anything and are difficult to fix
881 Logging.info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
882 RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
883 }
884 }
885
886 static void setupUIManager() {
887 String defaultlaf = platform.getDefaultStyle();
888 String laf = LafPreference.LAF.get();
889 try {
890 UIManager.setLookAndFeel(laf);
891 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
892 // Try to find look and feel in plugin classloaders
893 Logging.trace(e);
894 Class<?> klass = null;
895 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
896 try {
897 klass = cl.loadClass(laf);
898 break;
899 } catch (ClassNotFoundException ex) {
900 Logging.trace(ex);
901 }
902 }
903 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
904 try {
905 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
906 } catch (ReflectiveOperationException ex) {
907 Logging.log(Logging.LEVEL_WARN, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage(), ex);
908 } catch (UnsupportedLookAndFeelException ex) {
909 Logging.info("Look and Feel not supported: " + laf);
910 LafPreference.LAF.put(defaultlaf);
911 Logging.trace(ex);
912 }
913 } else {
914 Logging.info("Look and Feel not found: " + laf);
915 LafPreference.LAF.put(defaultlaf);
916 }
917 } catch (UnsupportedLookAndFeelException e) {
918 Logging.info("Look and Feel not supported: " + laf);
919 LafPreference.LAF.put(defaultlaf);
920 Logging.trace(e);
921 } catch (InstantiationException | IllegalAccessException e) {
922 Logging.error(e);
923 }
924
925 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
926 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
927 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
928 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
929 // Ensures caret color is the same than text foreground color, see #12257
930 // See http://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
931 for (String p : Arrays.asList(
932 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
933 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
934 }
935 }
936
937 private static InputStream openStream(URL url) throws IOException {
938 if ("file".equals(url.getProtocol())) {
939 return url.openStream();
940 } else {
941 return HttpClient.create(url).connect().getContent();
942 }
943 }
944
945 static Collection<PluginInformation> updateAndLoadEarlyPlugins(SplashScreen splash, SplashProgressMonitor monitor) {
946 Collection<PluginInformation> pluginsToLoad;
947 pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
948 if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
949 monitor.subTask(tr("Updating plugins"));
950 pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
951 }
952
953 monitor.indeterminateSubTask(tr("Installing updated plugins"));
954 PluginHandler.installDownloadedPlugins(true);
955
956 monitor.indeterminateSubTask(tr("Loading early plugins"));
957 PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
958 return pluginsToLoad;
959 }
960
961 static void loadLatePlugins(SplashScreen splash, SplashProgressMonitor monitor, Collection<PluginInformation> pluginsToLoad) {
962 monitor.indeterminateSubTask(tr("Loading plugins"));
963 PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
964 GuiHelper.runInEDTAndWait(() -> toolbar.refreshToolbarControl());
965 }
966
967 private static void processOffline(ProgramArguments args) {
968 for (String offlineNames : args.get(Option.OFFLINE)) {
969 for (String s : offlineNames.split(",")) {
970 try {
971 Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
972 } catch (IllegalArgumentException e) {
973 Logging.log(Logging.LEVEL_ERROR,
974 tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
975 s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())), e);
976 System.exit(1);
977 return;
978 }
979 }
980 }
981 Set<OnlineResource> offline = Main.getOfflineResources();
982 if (!offline.isEmpty()) {
983 Logging.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
984 "JOSM is running in offline mode. These resources will not be available: {0}",
985 offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
986 }
987 }
988
989 /**
990 * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
991 * disabling or enabling IPV6 may only be done with next start.
992 */
993 private static void checkIPv6() {
994 if ("auto".equals(Main.pref.get("prefer.ipv6", "auto"))) {
995 new Thread((Runnable) () -> { /* this may take some time (DNS, Connect) */
996 boolean hasv6 = false;
997 boolean wasv6 = Main.pref.getBoolean("validated.ipv6", false);
998 try {
999 /* Use the check result from last run of the software, as after the test, value
1000 changes have no effect anymore */
1001 if (wasv6) {
1002 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1003 }
1004 for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
1005 if (a instanceof Inet6Address) {
1006 if (a.isReachable(1000)) {
1007 /* be sure it REALLY works */
1008 SSLSocketFactory.getDefault().createSocket(a, 443).close();
1009 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1010 if (!wasv6) {
1011 Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4 after next restart."));
1012 } else {
1013 Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4."));
1014 }
1015 hasv6 = true;
1016 }
1017 break; /* we're done */
1018 }
1019 }
1020 } catch (IOException | SecurityException e) {
1021 Logging.debug("Exception while checking IPv6 connectivity: {0}", e);
1022 Logging.trace(e);
1023 }
1024 if (wasv6 && !hasv6) {
1025 Logging.info(tr("Detected no useable IPv6 network, prefering IPv4 over IPv6 after next restart."));
1026 Main.pref.put("validated.ipv6", hasv6); // be sure it is stored before the restart!
1027 try {
1028 RestartAction.restartJOSM();
1029 } catch (IOException e) {
1030 Logging.error(e);
1031 }
1032 }
1033 Main.pref.put("validated.ipv6", hasv6);
1034 }, "IPv6-checker").start();
1035 }
1036 }
1037
1038 /**
1039 * Download area specified as Bounds value.
1040 * @param rawGps Flag to download raw GPS tracks
1041 * @param b The bounds value
1042 * @return the complete download task (including post-download handler)
1043 */
1044 static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
1045 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1046 // asynchronously launch the download task ...
1047 Future<?> future = task.download(true, b, null);
1048 // ... and the continuation when the download is finished (this will wait for the download to finish)
1049 return Collections.singletonList(MainApplication.worker.submit(new PostDownloadHandler(task, future)));
1050 }
1051
1052 /**
1053 * Handle command line instructions after GUI has been initialized.
1054 * @param args program arguments
1055 * @return the list of submitted tasks
1056 */
1057 static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
1058 List<Future<?>> tasks = new ArrayList<>();
1059 List<File> fileList = new ArrayList<>();
1060 for (String s : args.get(Option.DOWNLOAD)) {
1061 tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
1062 }
1063 if (!fileList.isEmpty()) {
1064 tasks.add(OpenFileAction.openFiles(fileList, true));
1065 }
1066 for (String s : args.get(Option.DOWNLOADGPS)) {
1067 tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
1068 }
1069 final Collection<String> selectionArguments = args.get(Option.SELECTION);
1070 if (!selectionArguments.isEmpty()) {
1071 tasks.add(MainApplication.worker.submit(() -> {
1072 for (String s : selectionArguments) {
1073 SearchAction.search(s, SearchMode.add);
1074 }
1075 }));
1076 }
1077 return tasks;
1078 }
1079
1080 private static class GuiFinalizationWorker implements Runnable {
1081
1082 private final ProgramArguments args;
1083 private final DefaultProxySelector proxySelector;
1084
1085 GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
1086 this.args = args;
1087 this.proxySelector = proxySelector;
1088 }
1089
1090 @Override
1091 public void run() {
1092
1093 // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
1094 if (!handleProxyErrors()) {
1095 handleNetworkErrors();
1096 }
1097
1098 // Restore autosave layers after crash and start autosave thread
1099 handleAutosave();
1100
1101 // Handle command line instructions
1102 postConstructorProcessCmdLine(args);
1103
1104 // Show download dialog if autostart is enabled
1105 DownloadDialog.autostartIfNeeded();
1106 }
1107
1108 private static void handleAutosave() {
1109 if (AutosaveTask.PROP_AUTOSAVE_ENABLED.get()) {
1110 AutosaveTask autosaveTask = new AutosaveTask();
1111 List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
1112 if (!unsavedLayerFiles.isEmpty()) {
1113 ExtendedDialog dialog = new ExtendedDialog(
1114 Main.parent,
1115 tr("Unsaved osm data"),
1116 tr("Restore"), tr("Cancel"), tr("Discard")
1117 );
1118 dialog.setContent(
1119 trn("JOSM found {0} unsaved osm data layer. ",
1120 "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
1121 tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
1122 dialog.setButtonIcons("ok", "cancel", "dialogs/delete");
1123 int selection = dialog.showDialog().getValue();
1124 if (selection == 1) {
1125 autosaveTask.recoverUnsavedLayers();
1126 } else if (selection == 3) {
1127 autosaveTask.discardUnsavedLayers();
1128 }
1129 }
1130 autosaveTask.schedule();
1131 }
1132 }
1133
1134 private static boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
1135 if (hasErrors) {
1136 ExtendedDialog ed = new ExtendedDialog(
1137 Main.parent, title,
1138 tr("Change proxy settings"), tr("Cancel"));
1139 ed.setButtonIcons("dialogs/settings", "cancel").setCancelButton(2);
1140 ed.setMinimumSize(new Dimension(460, 260));
1141 ed.setIcon(JOptionPane.WARNING_MESSAGE);
1142 ed.setContent(message);
1143
1144 if (ed.showDialog().getValue() == 1) {
1145 PreferencesAction.forPreferenceSubTab(null, null, ProxyPreference.class).run();
1146 }
1147 }
1148 return hasErrors;
1149 }
1150
1151 private boolean handleProxyErrors() {
1152 return handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
1153 tr("JOSM tried to access the following resources:<br>" +
1154 "{0}" +
1155 "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
1156 "{1}" +
1157 "Would you like to change your proxy settings now?",
1158 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
1159 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
1160 ));
1161 }
1162
1163 private static boolean handleNetworkErrors() {
1164 Map<String, Throwable> networkErrors = Main.getNetworkErrors();
1165 boolean condition = !networkErrors.isEmpty();
1166 if (condition) {
1167 Set<String> errors = new TreeSet<>();
1168 for (Throwable t : networkErrors.values()) {
1169 errors.add(t.toString());
1170 }
1171 return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
1172 tr("JOSM tried to access the following resources:<br>" +
1173 "{0}" +
1174 "but <b>failed</b> to do so, because of the following network errors:<br>" +
1175 "{1}" +
1176 "It may be due to a missing proxy configuration.<br>" +
1177 "Would you like to change your proxy settings now?",
1178 Utils.joinAsHtmlUnorderedList(networkErrors.keySet()),
1179 Utils.joinAsHtmlUnorderedList(errors)
1180 ));
1181 }
1182 return false;
1183 }
1184 }
1185}
Note: See TracBrowser for help on using the repository browser.