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

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

see #15229 - deprecate Main.fileWatcher

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