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

Last change on this file since 12952 was 12928, checked in by bastiK, 7 years ago

see #15229 - do not copy the entire preferences list, just to set a custom server API in OAuth wizard

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