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

Last change on this file since 13506 was 13445, checked in by Don-vip, 6 years ago

fix #15901 - allow file:/ URLs

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