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

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

fix #15662 - allow JOSM to open JAR URLs containing exclamation marks (workaround to https://bugs.openjdk.java.net/browse/JDK-4523159)

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