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

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

closes #15273, see #15229, see #15182 - add command line interface module for projections

  • run josm project --help to see the options
  • extracts parser from LatLon and CustomProjection into LatLonParser
  • Property svn:eol-style set to native
File size: 60.2 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 NTV2GridShiftFileWrapper.registerNTV2GridShiftFileSource(
981 NTV2GridShiftFileWrapper.NTV2_SOURCE_PRIORITY_LOCAL,
982 NTV2Proj4DirGridShiftFileSource.getInstance());
983 NTV2GridShiftFileWrapper.registerNTV2GridShiftFileSource(
984 NTV2GridShiftFileWrapper.NTV2_SOURCE_PRIORITY_DOWNLOAD,
985 JOSM_WEBSITE_NTV2_SOURCE);
986 GuiHelper.translateJavaInternalMessages();
987 preConstructorInit();
988
989 monitor.indeterminateSubTask(tr("Creating main GUI"));
990 final Main main = new MainApplication(mainFrame);
991 main.initialize();
992
993 if (!skipLoadingPlugins) {
994 loadLatePlugins(splash, monitor, pluginsToLoad);
995 }
996
997 // Wait for splash disappearance (fix #9714)
998 GuiHelper.runInEDTAndWait(() -> {
999 splash.setVisible(false);
1000 splash.dispose();
1001 mainFrame.setVisible(true);
1002 });
1003
1004 boolean maximized = Main.pref.getBoolean("gui.maximized", false);
1005 if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
1006 mainFrame.setMaximized(true);
1007 }
1008 if (main.menu.fullscreenToggleAction != null) {
1009 main.menu.fullscreenToggleAction.initial();
1010 }
1011
1012 SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
1013
1014 if (Main.isPlatformWindows()) {
1015 try {
1016 // Check for insecure certificates to remove.
1017 // This is Windows-dependant code but it can't go to preStartupHook (need i18n)
1018 // neither startupHook (need to be called before remote control)
1019 PlatformHookWindows.removeInsecureCertificates();
1020 } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
1021 Logging.error(e);
1022 }
1023 }
1024
1025 if (RemoteControl.PROP_REMOTECONTROL_ENABLED.get()) {
1026 RemoteControl.start();
1027 }
1028
1029 if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
1030 MessageNotifier.start();
1031 }
1032
1033 if (Main.pref.getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
1034 // Repaint manager is registered so late for a reason - there is lots of violation during startup process
1035 // but they don't seem to break anything and are difficult to fix
1036 Logging.info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
1037 RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
1038 }
1039 }
1040
1041 static void applyWorkarounds() {
1042 // Workaround for JDK-8180379: crash on Windows 10 1703 with Windows L&F and java < 8u141 / 9+172
1043 // To remove during Java 9 migration
1044 if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows 10") &&
1045 platform.getDefaultStyle().equals(LafPreference.LAF.get())) {
1046 try {
1047 final int currentBuild = Integer.parseInt(PlatformHookWindows.getCurrentBuild());
1048 final int javaVersion = Utils.getJavaVersion();
1049 final int javaUpdate = Utils.getJavaUpdate();
1050 final int javaBuild = Utils.getJavaBuild();
1051 // See https://technet.microsoft.com/en-us/windows/release-info.aspx
1052 if (currentBuild >= 15_063 && ((javaVersion == 8 && javaUpdate < 141)
1053 || (javaVersion == 9 && javaUpdate == 0 && javaBuild < 173))) {
1054 // Workaround from https://bugs.openjdk.java.net/browse/JDK-8179014
1055 UIManager.put("FileChooser.useSystemExtensionHiding", Boolean.FALSE);
1056 }
1057 } catch (NumberFormatException | ReflectiveOperationException e) {
1058 Logging.error(e);
1059 }
1060 }
1061 }
1062
1063 static void setupCallbacks() {
1064 MessageNotifier.setNotifierCallback(MainApplication::notifyNewMessages);
1065 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
1066 }
1067
1068 static void setupUIManager() {
1069 String defaultlaf = platform.getDefaultStyle();
1070 String laf = LafPreference.LAF.get();
1071 try {
1072 UIManager.setLookAndFeel(laf);
1073 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
1074 // Try to find look and feel in plugin classloaders
1075 Logging.trace(e);
1076 Class<?> klass = null;
1077 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
1078 try {
1079 klass = cl.loadClass(laf);
1080 break;
1081 } catch (ClassNotFoundException ex) {
1082 Logging.trace(ex);
1083 }
1084 }
1085 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
1086 try {
1087 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
1088 } catch (ReflectiveOperationException ex) {
1089 Logging.log(Logging.LEVEL_WARN, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage(), ex);
1090 } catch (UnsupportedLookAndFeelException ex) {
1091 Logging.info("Look and Feel not supported: " + laf);
1092 LafPreference.LAF.put(defaultlaf);
1093 Logging.trace(ex);
1094 }
1095 } else {
1096 Logging.info("Look and Feel not found: " + laf);
1097 LafPreference.LAF.put(defaultlaf);
1098 }
1099 } catch (UnsupportedLookAndFeelException e) {
1100 Logging.info("Look and Feel not supported: " + laf);
1101 LafPreference.LAF.put(defaultlaf);
1102 Logging.trace(e);
1103 } catch (InstantiationException | IllegalAccessException e) {
1104 Logging.error(e);
1105 }
1106
1107 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
1108 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
1109 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
1110 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
1111 // Ensures caret color is the same than text foreground color, see #12257
1112 // See http://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
1113 for (String p : Arrays.asList(
1114 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
1115 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
1116 }
1117 }
1118
1119 private static InputStream openStream(URL url) throws IOException {
1120 if ("file".equals(url.getProtocol())) {
1121 return url.openStream();
1122 } else {
1123 return HttpClient.create(url).connect().getContent();
1124 }
1125 }
1126
1127 static Collection<PluginInformation> updateAndLoadEarlyPlugins(SplashScreen splash, SplashProgressMonitor monitor) {
1128 Collection<PluginInformation> pluginsToLoad;
1129 pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
1130 if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
1131 monitor.subTask(tr("Updating plugins"));
1132 pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
1133 }
1134
1135 monitor.indeterminateSubTask(tr("Installing updated plugins"));
1136 PluginHandler.installDownloadedPlugins(true);
1137
1138 monitor.indeterminateSubTask(tr("Loading early plugins"));
1139 PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
1140 return pluginsToLoad;
1141 }
1142
1143 static void loadLatePlugins(SplashScreen splash, SplashProgressMonitor monitor, Collection<PluginInformation> pluginsToLoad) {
1144 monitor.indeterminateSubTask(tr("Loading plugins"));
1145 PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
1146 GuiHelper.runInEDTAndWait(() -> toolbar.refreshToolbarControl());
1147 }
1148
1149 private static void processOffline(ProgramArguments args) {
1150 for (String offlineNames : args.get(Option.OFFLINE)) {
1151 for (String s : offlineNames.split(",")) {
1152 try {
1153 Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
1154 } catch (IllegalArgumentException e) {
1155 Logging.log(Logging.LEVEL_ERROR,
1156 tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
1157 s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())), e);
1158 System.exit(1);
1159 return;
1160 }
1161 }
1162 }
1163 Set<OnlineResource> offline = Main.getOfflineResources();
1164 if (!offline.isEmpty()) {
1165 Logging.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
1166 "JOSM is running in offline mode. These resources will not be available: {0}",
1167 offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
1168 }
1169 }
1170
1171 /**
1172 * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
1173 * disabling or enabling IPV6 may only be done with next start.
1174 */
1175 private static void checkIPv6() {
1176 if ("auto".equals(Main.pref.get("prefer.ipv6", "auto"))) {
1177 new Thread((Runnable) () -> { /* this may take some time (DNS, Connect) */
1178 boolean hasv6 = false;
1179 boolean wasv6 = Main.pref.getBoolean("validated.ipv6", false);
1180 try {
1181 /* Use the check result from last run of the software, as after the test, value
1182 changes have no effect anymore */
1183 if (wasv6) {
1184 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1185 }
1186 for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
1187 if (a instanceof Inet6Address) {
1188 if (a.isReachable(1000)) {
1189 /* be sure it REALLY works */
1190 SSLSocketFactory.getDefault().createSocket(a, 443).close();
1191 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1192 if (!wasv6) {
1193 Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4 after next restart."));
1194 } else {
1195 Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4."));
1196 }
1197 hasv6 = true;
1198 }
1199 break; /* we're done */
1200 }
1201 }
1202 } catch (IOException | SecurityException e) {
1203 Logging.debug("Exception while checking IPv6 connectivity: {0}", e);
1204 Logging.trace(e);
1205 }
1206 if (wasv6 && !hasv6) {
1207 Logging.info(tr("Detected no useable IPv6 network, prefering IPv4 over IPv6 after next restart."));
1208 Main.pref.put("validated.ipv6", hasv6); // be sure it is stored before the restart!
1209 try {
1210 RestartAction.restartJOSM();
1211 } catch (IOException e) {
1212 Logging.error(e);
1213 }
1214 }
1215 Main.pref.put("validated.ipv6", hasv6);
1216 }, "IPv6-checker").start();
1217 }
1218 }
1219
1220 /**
1221 * Download area specified as Bounds value.
1222 * @param rawGps Flag to download raw GPS tracks
1223 * @param b The bounds value
1224 * @return the complete download task (including post-download handler)
1225 */
1226 static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
1227 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1228 // asynchronously launch the download task ...
1229 Future<?> future = task.download(true, b, null);
1230 // ... and the continuation when the download is finished (this will wait for the download to finish)
1231 return Collections.singletonList(MainApplication.worker.submit(new PostDownloadHandler(task, future)));
1232 }
1233
1234 /**
1235 * Handle command line instructions after GUI has been initialized.
1236 * @param args program arguments
1237 * @return the list of submitted tasks
1238 */
1239 static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
1240 List<Future<?>> tasks = new ArrayList<>();
1241 List<File> fileList = new ArrayList<>();
1242 for (String s : args.get(Option.DOWNLOAD)) {
1243 tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
1244 }
1245 if (!fileList.isEmpty()) {
1246 tasks.add(OpenFileAction.openFiles(fileList, true));
1247 }
1248 for (String s : args.get(Option.DOWNLOADGPS)) {
1249 tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
1250 }
1251 final Collection<String> selectionArguments = args.get(Option.SELECTION);
1252 if (!selectionArguments.isEmpty()) {
1253 tasks.add(MainApplication.worker.submit(() -> {
1254 for (String s : selectionArguments) {
1255 SearchAction.search(s, SearchMode.add);
1256 }
1257 }));
1258 }
1259 return tasks;
1260 }
1261
1262 private static class GuiFinalizationWorker implements Runnable {
1263
1264 private final ProgramArguments args;
1265 private final DefaultProxySelector proxySelector;
1266
1267 GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
1268 this.args = args;
1269 this.proxySelector = proxySelector;
1270 }
1271
1272 @Override
1273 public void run() {
1274
1275 // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
1276 if (!handleProxyErrors()) {
1277 handleNetworkErrors();
1278 }
1279
1280 // Restore autosave layers after crash and start autosave thread
1281 handleAutosave();
1282
1283 // Handle command line instructions
1284 postConstructorProcessCmdLine(args);
1285
1286 // Show download dialog if autostart is enabled
1287 DownloadDialog.autostartIfNeeded();
1288 }
1289
1290 private static void handleAutosave() {
1291 if (AutosaveTask.PROP_AUTOSAVE_ENABLED.get()) {
1292 AutosaveTask autosaveTask = new AutosaveTask();
1293 List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
1294 if (!unsavedLayerFiles.isEmpty()) {
1295 ExtendedDialog dialog = new ExtendedDialog(
1296 Main.parent,
1297 tr("Unsaved osm data"),
1298 tr("Restore"), tr("Cancel"), tr("Discard")
1299 );
1300 dialog.setContent(
1301 trn("JOSM found {0} unsaved osm data layer. ",
1302 "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
1303 tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
1304 dialog.setButtonIcons("ok", "cancel", "dialogs/delete");
1305 int selection = dialog.showDialog().getValue();
1306 if (selection == 1) {
1307 autosaveTask.recoverUnsavedLayers();
1308 } else if (selection == 3) {
1309 autosaveTask.discardUnsavedLayers();
1310 }
1311 }
1312 autosaveTask.schedule();
1313 }
1314 }
1315
1316 private static boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
1317 if (hasErrors) {
1318 ExtendedDialog ed = new ExtendedDialog(
1319 Main.parent, title,
1320 tr("Change proxy settings"), tr("Cancel"));
1321 ed.setButtonIcons("dialogs/settings", "cancel").setCancelButton(2);
1322 ed.setMinimumSize(new Dimension(460, 260));
1323 ed.setIcon(JOptionPane.WARNING_MESSAGE);
1324 ed.setContent(message);
1325
1326 if (ed.showDialog().getValue() == 1) {
1327 PreferencesAction.forPreferenceSubTab(null, null, ProxyPreference.class).run();
1328 }
1329 }
1330 return hasErrors;
1331 }
1332
1333 private boolean handleProxyErrors() {
1334 return handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
1335 tr("JOSM tried to access the following resources:<br>" +
1336 "{0}" +
1337 "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
1338 "{1}" +
1339 "Would you like to change your proxy settings now?",
1340 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
1341 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
1342 ));
1343 }
1344
1345 private static boolean handleNetworkErrors() {
1346 Map<String, Throwable> networkErrors = Main.getNetworkErrors();
1347 boolean condition = !networkErrors.isEmpty();
1348 if (condition) {
1349 Set<String> errors = new TreeSet<>();
1350 for (Throwable t : networkErrors.values()) {
1351 errors.add(t.toString());
1352 }
1353 return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
1354 tr("JOSM tried to access the following resources:<br>" +
1355 "{0}" +
1356 "but <b>failed</b> to do so, because of the following network errors:<br>" +
1357 "{1}" +
1358 "It may be due to a missing proxy configuration.<br>" +
1359 "Would you like to change your proxy settings now?",
1360 Utils.joinAsHtmlUnorderedList(networkErrors.keySet()),
1361 Utils.joinAsHtmlUnorderedList(errors)
1362 ));
1363 }
1364 return false;
1365 }
1366 }
1367
1368 private static class DefaultNativeOsCallback implements NativeOsCallback {
1369 @Override
1370 public void openFiles(List<File> files) {
1371 Executors.newSingleThreadExecutor(Utils.newThreadFactory("openFiles-%d", Thread.NORM_PRIORITY)).submit(
1372 new OpenFileTask(files, null) {
1373 @Override
1374 protected void realRun() throws SAXException, IOException, OsmTransferException {
1375 // Wait for JOSM startup is advanced enough to load a file
1376 while (Main.parent == null || !Main.parent.isVisible()) {
1377 try {
1378 Thread.sleep(25);
1379 } catch (InterruptedException e) {
1380 Logging.warn(e);
1381 Thread.currentThread().interrupt();
1382 }
1383 }
1384 super.realRun();
1385 }
1386 });
1387 }
1388
1389 @Override
1390 public boolean handleQuitRequest() {
1391 return MainApplication.exitJosm(false, 0, null);
1392 }
1393
1394 @Override
1395 public void handleAbout() {
1396 MainApplication.getMenu().about.actionPerformed(null);
1397 }
1398
1399 @Override
1400 public void handlePreferences() {
1401 MainApplication.getMenu().preferences.actionPerformed(null);
1402 }
1403 }
1404
1405 static void notifyNewMessages(UserInfo userInfo) {
1406 GuiHelper.runInEDT(() -> {
1407 JPanel panel = new JPanel(new GridBagLayout());
1408 panel.add(new JLabel(trn("You have {0} unread message.", "You have {0} unread messages.",
1409 userInfo.getUnreadMessages(), userInfo.getUnreadMessages())),
1410 GBC.eol());
1411 panel.add(new UrlLabel(Main.getBaseUserUrl() + '/' + userInfo.getDisplayName() + "/inbox",
1412 tr("Click here to see your inbox.")), GBC.eol());
1413 panel.setOpaque(false);
1414 new Notification().setContent(panel)
1415 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1416 .setDuration(Notification.TIME_LONG)
1417 .show();
1418 });
1419 }
1420}
Note: See TracBrowser for help on using the repository browser.