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

Last change on this file since 12770 was 12770, checked in by bastiK, 7 years ago

see #15229 - remove GUI references from BugReport and BugReportQueue

signature of BugReport#getReportText changed without deprecation
(probably not used by any external plugin)

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