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

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

see #15310 - remove most of deprecated APIs

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