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

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

see #9995 - add advanced option to scale the menu font (gui.scale.menu.font)

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