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

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

see #15229 - see #15182 - SonarQube - squid:S2444 - make static fields volatile

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