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

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

see #15229 - add registry for NTV2 grid file sources

removes dependency of NTV2GridShiftFileWrapper on Main

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