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

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

see #15229 - see #15182 - remove GUI references from OsmApi

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