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

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

see #15229 - see #15182 - make FileWatcher generic so it has no more dependence on MapCSS

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