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

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

see #15310 - remove Main.worker

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