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

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

see #15229 - see #15182 - make Main to not depend on JCS

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