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

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

see #15273, see #15229 - fix unit tests, PMD, etc.

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