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

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

see #15310 - fix unit tests, warnings

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