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

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

see #15229 - see #15182 - remove GUI references from BugReportSender

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