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

Last change on this file since 12907 was 12906, checked in by bastiK, 7 years ago

see #15273, see #15229 - add command line module for rendering

run josm render --help to see the options

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