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

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

see #15182 - refactor PlatformHookOsx so that all GUI actions are performed in MainApplication and only macOS-specific stuff remains in platform hook

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