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

Last change on this file since 13489 was 13445, checked in by Don-vip, 6 years ago

fix #15901 - allow file:/ URLs

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