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

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

see #15273 - document new features in the main help page

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