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

Last change on this file since 12846 was 12845, checked in by bastiK, 7 years ago

new class Config to hold a global IPreferences singleton, replacing calls to Main.pref as far as the interface supports it

makes it possible to easily replace org.openstreetmap.josm.data.Preferences by
another preferences handler (implementation of IPreferences)

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