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

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

see #13036 - see #15229 - see #15182 - make Commands depends only on a DataSet, not a Layer. This removes a lot of GUI dependencies

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