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

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

see #15229 - deprecate all Main methods related to network features. New NetworkManager class

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