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

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

see #15343 - catch Java 9 exceptions

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