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

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

see #15182 - deprecate Main.main.panel. Replacement: gui.MainApplication.getMainPanel()

  • Property svn:eol-style set to native
File size: 48.2 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.Dimension;
9import java.awt.GraphicsEnvironment;
10import java.awt.event.KeyEvent;
11import java.io.File;
12import java.io.IOException;
13import java.io.InputStream;
14import java.net.Authenticator;
15import java.net.Inet6Address;
16import java.net.InetAddress;
17import java.net.ProxySelector;
18import java.net.URL;
19import java.security.AllPermission;
20import java.security.CodeSource;
21import java.security.GeneralSecurityException;
22import java.security.KeyStoreException;
23import java.security.NoSuchAlgorithmException;
24import java.security.PermissionCollection;
25import java.security.Permissions;
26import java.security.Policy;
27import java.security.cert.CertificateException;
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.Collection;
31import java.util.Collections;
32import java.util.List;
33import java.util.Locale;
34import java.util.Map;
35import java.util.Optional;
36import java.util.Set;
37import java.util.TreeSet;
38import java.util.concurrent.Callable;
39import java.util.concurrent.ExecutorService;
40import java.util.concurrent.Future;
41import java.util.logging.Level;
42import java.util.stream.Collectors;
43import java.util.stream.Stream;
44
45import javax.net.ssl.SSLSocketFactory;
46import javax.swing.Action;
47import javax.swing.InputMap;
48import javax.swing.JComponent;
49import javax.swing.JOptionPane;
50import javax.swing.KeyStroke;
51import javax.swing.LookAndFeel;
52import javax.swing.RepaintManager;
53import javax.swing.SwingUtilities;
54import javax.swing.UIManager;
55import javax.swing.UnsupportedLookAndFeelException;
56
57import org.jdesktop.swinghelper.debug.CheckThreadViolationRepaintManager;
58import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
59import org.openstreetmap.josm.Main;
60import org.openstreetmap.josm.actions.JosmAction;
61import org.openstreetmap.josm.actions.OpenFileAction;
62import org.openstreetmap.josm.actions.PreferencesAction;
63import org.openstreetmap.josm.actions.RestartAction;
64import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
65import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
66import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
67import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
68import org.openstreetmap.josm.actions.mapmode.DrawAction;
69import org.openstreetmap.josm.actions.search.SearchAction;
70import org.openstreetmap.josm.data.Bounds;
71import org.openstreetmap.josm.data.UndoRedoHandler;
72import org.openstreetmap.josm.data.Version;
73import org.openstreetmap.josm.data.osm.DataSet;
74import org.openstreetmap.josm.data.osm.OsmPrimitive;
75import org.openstreetmap.josm.data.validation.OsmValidator;
76import org.openstreetmap.josm.gui.ProgramArguments.Option;
77import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
78import org.openstreetmap.josm.gui.download.DownloadDialog;
79import org.openstreetmap.josm.gui.io.CustomConfigurator.XMLCommandProcessor;
80import org.openstreetmap.josm.gui.io.SaveLayersDialog;
81import org.openstreetmap.josm.gui.layer.AutosaveTask;
82import org.openstreetmap.josm.gui.layer.MainLayerManager;
83import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
84import org.openstreetmap.josm.gui.layer.TMSLayer;
85import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
86import org.openstreetmap.josm.gui.preferences.display.LafPreference;
87import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
88import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
89import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
90import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
91import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
92import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
93import org.openstreetmap.josm.gui.util.GuiHelper;
94import org.openstreetmap.josm.gui.util.RedirectInputMap;
95import org.openstreetmap.josm.io.CertificateAmendment;
96import org.openstreetmap.josm.io.DefaultProxySelector;
97import org.openstreetmap.josm.io.MessageNotifier;
98import org.openstreetmap.josm.io.OnlineResource;
99import org.openstreetmap.josm.io.OsmApi;
100import org.openstreetmap.josm.io.OsmApiInitializationException;
101import org.openstreetmap.josm.io.OsmTransferCanceledException;
102import org.openstreetmap.josm.io.auth.CredentialsManager;
103import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
104import org.openstreetmap.josm.io.protocols.data.Handler;
105import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
106import org.openstreetmap.josm.plugins.PluginHandler;
107import org.openstreetmap.josm.plugins.PluginInformation;
108import org.openstreetmap.josm.tools.FontsManager;
109import org.openstreetmap.josm.tools.HttpClient;
110import org.openstreetmap.josm.tools.I18n;
111import org.openstreetmap.josm.tools.ImageProvider;
112import org.openstreetmap.josm.tools.Logging;
113import org.openstreetmap.josm.tools.OpenBrowser;
114import org.openstreetmap.josm.tools.OsmUrlToBounds;
115import org.openstreetmap.josm.tools.OverpassTurboQueryWizard;
116import org.openstreetmap.josm.tools.PlatformHookWindows;
117import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
118import org.openstreetmap.josm.tools.Shortcut;
119import org.openstreetmap.josm.tools.Territories;
120import org.openstreetmap.josm.tools.Utils;
121import org.openstreetmap.josm.tools.WindowGeometry;
122import org.openstreetmap.josm.tools.bugreport.BugReport;
123import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
124
125/**
126 * Main window class application.
127 *
128 * @author imi
129 */
130public class MainApplication extends Main {
131
132 /**
133 * Command-line arguments used to run the application.
134 */
135 private static final List<String> COMMAND_LINE_ARGS = new ArrayList<>();
136
137 /**
138 * The main panel, required to be static for {@link MapFrameListener} handling.
139 */
140 static MainPanel mainPanel;
141
142 /**
143 * The private content pane of {@link MainFrame}, required to be static for shortcut handling.
144 */
145 static JComponent contentPanePrivate;
146
147 /**
148 * The MapFrame.
149 */
150 static MapFrame map;
151
152 /**
153 * The toolbar preference control to register new actions.
154 */
155 static volatile ToolbarPreferences toolbar;
156
157 private final MainFrame mainFrame;
158
159 /**
160 * The worker thread slave. This is for executing all long and intensive
161 * calculations. The executed runnables are guaranteed to be executed separately and sequential.
162 * @since 12634 (as a replacement to {@code Main.worker})
163 */
164 public static final ExecutorService worker = new ProgressMonitorExecutor("main-worker-%d", Thread.NORM_PRIORITY);
165
166 /**
167 * Provides access to the layers displayed in the main view.
168 */
169 private static final MainLayerManager layerManager = new MainLayerManager();
170
171 /**
172 * The commands undo/redo handler.
173 * @since 12641 (as a replacement to {@code Main.main.undoRedo})
174 */
175 public static final UndoRedoHandler undoRedo = new UndoRedoHandler(); // Must be declared after layerManager
176
177 /**
178 * Listener that sets the enabled state of undo/redo menu entries.
179 */
180 private final CommandQueueListener redoUndoListener = (queueSize, redoSize) -> {
181 menu.undo.setEnabled(queueSize > 0);
182 menu.redo.setEnabled(redoSize > 0);
183 };
184
185 /**
186 * Constructs a new {@code MainApplication} without a window.
187 */
188 public MainApplication() {
189 this(null);
190 }
191
192 /**
193 * Constructs a main frame, ready sized and operating. Does not display the frame.
194 * @param mainFrame The main JFrame of the application
195 * @since 10340
196 */
197 public MainApplication(MainFrame mainFrame) {
198 this.mainFrame = mainFrame;
199 }
200
201 @Override
202 protected List<InitializationTask> beforeInitializationTasks() {
203 return Arrays.asList(
204 new InitializationTask(tr("Starting file watcher"), fileWatcher::start),
205 new InitializationTask(tr("Executing platform startup hook"), platform::startupHook),
206 new InitializationTask(tr("Building main menu"), this::initializeMainWindow),
207 new InitializationTask(tr("Updating user interface"), () -> {
208 undoRedo.addCommandQueueListener(redoUndoListener);
209 // creating toolbar
210 GuiHelper.runInEDTAndWait(() -> contentPanePrivate.add(toolbar.control, BorderLayout.NORTH));
211 // help shortcut
212 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
213 KeyEvent.VK_F1, Shortcut.DIRECT));
214 }),
215 // This needs to be done before RightAndLefthandTraffic::initialize is called
216 new InitializationTask(tr("Initializing internal boundaries data"), Territories::initialize)
217 );
218 }
219
220 @Override
221 protected Collection<InitializationTask> parallelInitializationTasks() {
222 return Arrays.asList(
223 new InitializationTask(tr("Initializing OSM API"), () -> {
224 // We try to establish an API connection early, so that any API
225 // capabilities are already known to the editor instance. However
226 // if it goes wrong that's not critical at this stage.
227 try {
228 OsmApi.getOsmApi().initialize(null, true);
229 } catch (OsmTransferCanceledException | OsmApiInitializationException e) {
230 Logging.warn(Logging.getErrorMessage(Utils.getRootCause(e)));
231 }
232 }),
233 new InitializationTask(tr("Initializing internal traffic data"), RightAndLefthandTraffic::initialize),
234 new InitializationTask(tr("Initializing validator"), OsmValidator::initialize),
235 new InitializationTask(tr("Initializing presets"), TaggingPresets::initialize),
236 new InitializationTask(tr("Initializing map styles"), MapPaintPreference::initialize),
237 new InitializationTask(tr("Loading imagery preferences"), ImageryPreference::initialize)
238 );
239 }
240
241 @Override
242 protected List<Callable<?>> asynchronousCallableTasks() {
243 return Arrays.asList(
244 OverpassTurboQueryWizard::getInstance
245 );
246 }
247
248 @Override
249 protected List<Runnable> asynchronousRunnableTasks() {
250 return Arrays.asList(
251 TMSLayer::getCache,
252 OsmValidator::initializeTests
253 );
254 }
255
256 @Override
257 protected List<InitializationTask> afterInitializationTasks() {
258 return Arrays.asList(
259 new InitializationTask(tr("Updating user interface"), () -> GuiHelper.runInEDTAndWait(() -> {
260 // hooks for the jmapviewer component
261 FeatureAdapter.registerBrowserAdapter(OpenBrowser::displayUrl);
262 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
263 FeatureAdapter.registerLoggingAdapter(name -> Logging.getLogger());
264 // UI update
265 toolbar.refreshToolbarControl();
266 toolbar.control.updateUI();
267 contentPanePrivate.updateUI();
268 }))
269 );
270 }
271
272 @Override
273 @SuppressWarnings("deprecation")
274 protected void initializeMainWindow() {
275 if (mainFrame != null) {
276 mainPanel = mainFrame.getPanel();
277 panel = mainPanel;
278 mainFrame.initialize();
279 menu = mainFrame.getMenu();
280 } else {
281 // required for running some tests.
282 mainPanel = new MainPanel(layerManager);
283 panel = mainPanel;
284 menu = new MainMenu();
285 }
286 mainPanel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
287 mainPanel.reAddListeners();
288 }
289
290 @Override
291 protected void shutdown() {
292 if (!GraphicsEnvironment.isHeadless()) {
293 worker.shutdown();
294 }
295 if (mainFrame != null) {
296 mainFrame.storeState();
297 }
298 if (map != null) {
299 map.rememberToggleDialogWidth();
300 }
301 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
302 layerManager.resetState();
303 super.shutdown();
304 if (!GraphicsEnvironment.isHeadless()) {
305 worker.shutdownNow();
306 }
307 }
308
309 @Override
310 protected Bounds getRealBounds() {
311 return isDisplayingMapView() ? map.mapView.getRealBounds() : null;
312 }
313
314 @Override
315 protected void restoreOldBounds(Bounds oldBounds) {
316 if (isDisplayingMapView()) {
317 map.mapView.zoomTo(oldBounds);
318 }
319 }
320
321 /**
322 * Replies the current selected primitives, from a end-user point of view.
323 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
324 * Indeed, if the user is currently in drawing mode, only the way currently being drawn is returned,
325 * see {@link DrawAction#getInProgressSelection()}.
326 *
327 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
328 * @since 6546
329 */
330 @Override
331 public Collection<OsmPrimitive> getInProgressSelection() {
332 if (map != null && map.mapMode instanceof DrawAction) {
333 return ((DrawAction) map.mapMode).getInProgressSelection();
334 } else {
335 DataSet ds = layerManager.getEditDataSet();
336 if (ds == null) return null;
337 return ds.getSelected();
338 }
339 }
340
341 /**
342 * Returns the command-line arguments used to run the application.
343 * @return the command-line arguments used to run the application
344 * @since 11650
345 */
346 public static List<String> getCommandLineArgs() {
347 return Collections.unmodifiableList(COMMAND_LINE_ARGS);
348 }
349
350 /**
351 * Returns the main layer manager that is used by the map view.
352 * @return The layer manager. The value returned will never change.
353 * @since 12636 (as a replacement to {@code Main.getLayerManager()})
354 */
355 @SuppressWarnings("deprecation")
356 public static MainLayerManager getLayerManager() {
357 return layerManager;
358 }
359
360 /**
361 * Returns the MapFrame.
362 * <p>
363 * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
364 * @return the MapFrame
365 * @see MainPanel
366 * @since 12630 (as a replacement to {@code Main.map})
367 */
368 public static MapFrame getMap() {
369 return map;
370 }
371
372 /**
373 * Returns the main panel.
374 * @return the main panel
375 * @since 12642 (as a replacement to {@code Main.main.panel})
376 */
377 public static MainPanel getMainPanel() {
378 return mainPanel;
379 }
380
381 /**
382 * Returns the toolbar preference control to register new actions.
383 * @return the toolbar preference control
384 * @since 12637 (as a replacement to {@code Main.toolbar})
385 */
386 public static ToolbarPreferences getToolbar() {
387 return toolbar;
388 }
389
390 /**
391 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
392 * it only shows the MOTD panel.
393 * <p>
394 * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
395 *
396 * @return <code>true</code> if JOSM currently displays a map view
397 * @since 12630 (as a replacement to {@code Main.isDisplayingMapView()})
398 */
399 @SuppressWarnings("deprecation")
400 public static boolean isDisplayingMapView() {
401 return map != null && map.mapView != null;
402 }
403
404 /**
405 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
406 * If there are some unsaved data layers, asks first for user confirmation.
407 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
408 * @param exitCode The return code
409 * @param reason the reason for exiting
410 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
411 * @since 12636 (specialized version of {@link Main#exitJosm})
412 */
413 public static boolean exitJosm(boolean exit, int exitCode, SaveLayersDialog.Reason reason) {
414 final boolean proceed = Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
415 SaveLayersDialog.saveUnsavedModifications(layerManager.getLayers(),
416 reason != null ? reason : SaveLayersDialog.Reason.EXIT)));
417 if (proceed) {
418 return Main.exitJosm(exit, exitCode);
419 }
420 return false;
421 }
422
423 public static void redirectToMainContentPane(JComponent source) {
424 RedirectInputMap.redirect(source, contentPanePrivate);
425 }
426
427 /**
428 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes.
429 * <p>
430 * It will fire an initial mapFrameInitialized event when the MapFrame is present.
431 * Otherwise will only fire when the MapFrame is created or destroyed.
432 * @param listener The MapFrameListener
433 * @return {@code true} if the listeners collection changed as a result of the call
434 * @see #addMapFrameListener
435 * @since 12639 (as a replacement to {@code Main.addAndFireMapFrameListener})
436 */
437 @SuppressWarnings("deprecation")
438 public static boolean addAndFireMapFrameListener(MapFrameListener listener) {
439 return mainPanel != null && mainPanel.addAndFireMapFrameListener(listener);
440 }
441
442 /**
443 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
444 * @param listener The MapFrameListener
445 * @return {@code true} if the listeners collection changed as a result of the call
446 * @see #addAndFireMapFrameListener
447 * @since 12639 (as a replacement to {@code Main.addMapFrameListener})
448 */
449 @SuppressWarnings("deprecation")
450 public static boolean addMapFrameListener(MapFrameListener listener) {
451 return mainPanel != null && mainPanel.addMapFrameListener(listener);
452 }
453
454 /**
455 * Unregisters the given {@code MapFrameListener} from MapFrame changes
456 * @param listener The MapFrameListener
457 * @return {@code true} if the listeners collection changed as a result of the call
458 * @since 12639 (as a replacement to {@code Main.removeMapFrameListener})
459 */
460 @SuppressWarnings("deprecation")
461 public static boolean removeMapFrameListener(MapFrameListener listener) {
462 return mainPanel != null && mainPanel.removeMapFrameListener(listener);
463 }
464
465 /**
466 * Registers a {@code JosmAction} and its shortcut.
467 * @param action action defining its own shortcut
468 * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
469 */
470 @SuppressWarnings("deprecation")
471 public static void registerActionShortcut(JosmAction action) {
472 registerActionShortcut(action, action.getShortcut());
473 }
474
475 /**
476 * Registers an action and its shortcut.
477 * @param action action to register
478 * @param shortcut shortcut to associate to {@code action}
479 * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
480 */
481 @SuppressWarnings("deprecation")
482 public static void registerActionShortcut(Action action, Shortcut shortcut) {
483 KeyStroke keyStroke = shortcut.getKeyStroke();
484 if (keyStroke == null)
485 return;
486
487 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
488 Object existing = inputMap.get(keyStroke);
489 if (existing != null && !existing.equals(action)) {
490 Logging.info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
491 }
492 inputMap.put(keyStroke, action);
493
494 contentPanePrivate.getActionMap().put(action, action);
495 }
496
497 /**
498 * Unregisters a shortcut.
499 * @param shortcut shortcut to unregister
500 * @since 12639 (as a replacement to {@code Main.unregisterShortcut})
501 */
502 @SuppressWarnings("deprecation")
503 public static void unregisterShortcut(Shortcut shortcut) {
504 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
505 }
506
507 /**
508 * Unregisters a {@code JosmAction} and its shortcut.
509 * @param action action to unregister
510 * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
511 */
512 @SuppressWarnings("deprecation")
513 public static void unregisterActionShortcut(JosmAction action) {
514 unregisterActionShortcut(action, action.getShortcut());
515 }
516
517 /**
518 * Unregisters an action and its shortcut.
519 * @param action action to unregister
520 * @param shortcut shortcut to unregister
521 * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
522 */
523 @SuppressWarnings("deprecation")
524 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
525 unregisterShortcut(shortcut);
526 contentPanePrivate.getActionMap().remove(action);
527 }
528
529 /**
530 * Replies the registered action for the given shortcut
531 * @param shortcut The shortcut to look for
532 * @return the registered action for the given shortcut
533 * @since 12639 (as a replacement to {@code Main.getRegisteredActionShortcut})
534 */
535 @SuppressWarnings("deprecation")
536 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
537 KeyStroke keyStroke = shortcut.getKeyStroke();
538 if (keyStroke == null)
539 return null;
540 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
541 if (action instanceof Action)
542 return (Action) action;
543 return null;
544 }
545
546 /**
547 * Displays help on the console
548 * @since 2748
549 */
550 public static void showHelp() {
551 // TODO: put in a platformHook for system that have no console by default
552 System.out.println(getHelp());
553 }
554
555 static String getHelp() {
556 return tr("Java OpenStreetMap Editor")+" ["
557 +Version.getInstance().getAgentString()+"]\n\n"+
558 tr("usage")+":\n"+
559 "\tjava -jar josm.jar <options>...\n\n"+
560 tr("options")+":\n"+
561 "\t--help|-h "+tr("Show this help")+'\n'+
562 "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+'\n'+
563 "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+'\n'+
564 "\t[--download=]<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z)")+'\n'+
565 "\t[--download=]<filename> "+tr("Open a file (any file type that can be opened with File/Open)")+'\n'+
566 "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw GPS")+'\n'+
567 "\t--downloadgps=<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z) as raw GPS")+'\n'+
568 "\t--selection=<searchstring> "+tr("Select with the given search")+'\n'+
569 "\t--[no-]maximize "+tr("Launch in maximized mode")+'\n'+
570 "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+
571 "\t--load-preferences=<url-to-xml> "+tr("Changes preferences according to the XML file")+"\n\n"+
572 "\t--set=<key>=<value> "+tr("Set preference key to value")+"\n\n"+
573 "\t--language=<language> "+tr("Set the language")+"\n\n"+
574 "\t--version "+tr("Displays the JOSM version and exits")+"\n\n"+
575 "\t--debug "+tr("Print debugging messages to console")+"\n\n"+
576 "\t--skip-plugins "+tr("Skip loading plugins")+"\n\n"+
577 "\t--offline=<osm_api|josm_website|all> "+tr("Disable access to the given resource(s), separated by comma")+"\n\n"+
578 tr("options provided as Java system properties")+":\n"+
579 align("\t-Djosm.dir.name=JOSM") + tr("Change the JOSM directory name") + "\n\n" +
580 align("\t-Djosm.pref=" + tr("/PATH/TO/JOSM/PREF ")) + tr("Set the preferences directory") + "\n" +
581 align("\t") + tr("Default: {0}", platform.getDefaultPrefDirectory()) + "\n\n" +
582 align("\t-Djosm.userdata=" + tr("/PATH/TO/JOSM/USERDATA")) + tr("Set the user data directory") + "\n" +
583 align("\t") + tr("Default: {0}", platform.getDefaultUserDataDirectory()) + "\n\n" +
584 align("\t-Djosm.cache=" + tr("/PATH/TO/JOSM/CACHE ")) + tr("Set the cache directory") + "\n" +
585 align("\t") + tr("Default: {0}", platform.getDefaultCacheDirectory()) + "\n\n" +
586 align("\t-Djosm.home=" + tr("/PATH/TO/JOSM/HOMEDIR ")) +
587 tr("Set the preferences+data+cache directory (cache directory will be josm.home/cache)")+"\n\n"+
588 tr("-Djosm.home has lower precedence, i.e. the specific setting overrides the general one")+"\n\n"+
589 tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
590 " Java option to specify the maximum size of allocated memory in megabytes")+":\n"+
591 "\t-Xmx...m\n\n"+
592 tr("examples")+":\n"+
593 "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
594 "\tjava -jar josm.jar "+OsmUrlToBounds.getURL(43.2, 11.1, 13)+'\n'+
595 "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
596 "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
597 "\tjava -Djosm.pref=$XDG_CONFIG_HOME -Djosm.userdata=$XDG_DATA_HOME -Djosm.cache=$XDG_CACHE_HOME -jar josm.jar\n"+
598 "\tjava -Djosm.dir.name=josm_dev -jar josm.jar\n"+
599 "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
600 "\tjava -Xmx1024m -jar josm.jar\n\n"+
601 tr("Parameters --download, --downloadgps, and --selection are processed in this order.")+'\n'+
602 tr("Make sure you load some data if you use --selection.")+'\n';
603 }
604
605 private static String align(String str) {
606 return str + Stream.generate(() -> " ").limit(Math.max(0, 43 - str.length())).collect(Collectors.joining(""));
607 }
608
609 /**
610 * Main application Startup
611 * @param argArray Command-line arguments
612 */
613 @SuppressWarnings("deprecation")
614 public static void main(final String[] argArray) {
615 I18n.init();
616
617 ProgramArguments args = null;
618 // construct argument table
619 try {
620 args = new ProgramArguments(argArray);
621 } catch (IllegalArgumentException e) {
622 System.err.println(e.getMessage());
623 System.exit(1);
624 return;
625 }
626
627 Level logLevel = args.getLogLevel();
628 Logging.setLogLevel(logLevel);
629 if (!args.showVersion() && !args.showHelp()) {
630 Logging.info(tr("Log level is at {0} ({1}, {2})", logLevel.getLocalizedName(), logLevel.getName(), logLevel.intValue()));
631 }
632
633 Optional<String> language = args.getSingle(Option.LANGUAGE);
634 I18n.set(language.orElse(null));
635
636 Policy.setPolicy(new Policy() {
637 // Permissions for plug-ins loaded when josm is started via webstart
638 private PermissionCollection pc;
639
640 {
641 pc = new Permissions();
642 pc.add(new AllPermission());
643 }
644
645 @Override
646 public PermissionCollection getPermissions(CodeSource codesource) {
647 return pc;
648 }
649 });
650
651 Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
652
653 // initialize the platform hook, and
654 Main.determinePlatformHook();
655 // call the really early hook before we do anything else
656 Main.platform.preStartupHook();
657
658 if (args.showVersion()) {
659 System.out.println(Version.getInstance().getAgentString());
660 return;
661 } else if (args.showHelp()) {
662 showHelp();
663 return;
664 }
665
666 COMMAND_LINE_ARGS.addAll(Arrays.asList(argArray));
667
668 boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
669 if (skipLoadingPlugins) {
670 Logging.info(tr("Plugin loading skipped"));
671 }
672
673 if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
674 // Enable debug in OAuth signpost via system preference, but only at trace level
675 Utils.updateSystemProperty("debug", "true");
676 Logging.info(tr("Enabled detailed debug level (trace)"));
677 }
678
679 Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
680
681 args.getPreferencesToSet().forEach(Main.pref::put);
682
683 if (!language.isPresent()) {
684 I18n.set(Main.pref.get("language", null));
685 }
686 Main.pref.updateSystemProperties();
687
688 checkIPv6();
689
690 processOffline(args);
691
692 Main.platform.afterPrefStartupHook();
693
694 FontsManager.initialize();
695
696 I18n.setupLanguageFonts();
697
698 Handler.install();
699
700 WindowGeometry geometry = WindowGeometry.mainWindow("gui.geometry",
701 args.getSingle(Option.GEOMETRY).orElse(null),
702 !args.hasOption(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
703 final MainFrame mainFrame = new MainFrame(geometry);
704 if (mainFrame.getContentPane() instanceof JComponent) {
705 contentPanePrivate = (JComponent) mainFrame.getContentPane();
706 }
707 mainPanel = mainFrame.getPanel();
708 Main.parent = mainFrame;
709
710 if (args.hasOption(Option.LOAD_PREFERENCES)) {
711 XMLCommandProcessor config = new XMLCommandProcessor(Main.pref);
712 for (String i : args.get(Option.LOAD_PREFERENCES)) {
713 Logging.info("Reading preferences from " + i);
714 try (InputStream is = openStream(new URL(i))) {
715 config.openAndReadXML(is);
716 } catch (IOException ex) {
717 throw BugReport.intercept(ex).put("file", i);
718 }
719 }
720 }
721
722 try {
723 CertificateAmendment.addMissingCertificates();
724 } catch (IOException | GeneralSecurityException ex) {
725 Logging.warn(ex);
726 Logging.warn(Logging.getErrorMessage(Utils.getRootCause(ex)));
727 }
728 Authenticator.setDefault(DefaultAuthenticator.getInstance());
729 DefaultProxySelector proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
730 ProxySelector.setDefault(proxySelector);
731 OAuthAccessTokenHolder.getInstance().init(Main.pref, CredentialsManager.getInstance());
732
733 final SplashScreen splash = GuiHelper.runInEDTAndWaitAndReturn(SplashScreen::new);
734 final SplashScreen.SplashProgressMonitor monitor = splash.getProgressMonitor();
735 monitor.beginTask(tr("Initializing"));
736 GuiHelper.runInEDT(() -> splash.setVisible(Main.pref.getBoolean("draw.splashscreen", true)));
737 Main.setInitStatusListener(new InitStatusListener() {
738
739 @Override
740 public Object updateStatus(String event) {
741 monitor.beginTask(event);
742 return event;
743 }
744
745 @Override
746 public void finish(Object status) {
747 if (status instanceof String) {
748 monitor.finishTask((String) status);
749 }
750 }
751 });
752
753 Collection<PluginInformation> pluginsToLoad = null;
754
755 if (!skipLoadingPlugins) {
756 pluginsToLoad = updateAndLoadEarlyPlugins(splash, monitor);
757 }
758
759 monitor.indeterminateSubTask(tr("Setting defaults"));
760 setupUIManager();
761 toolbar = new ToolbarPreferences();
762 Main.toolbar = toolbar;
763 preConstructorInit();
764
765 monitor.indeterminateSubTask(tr("Creating main GUI"));
766 final Main main = new MainApplication(mainFrame);
767 main.initialize();
768
769 if (!skipLoadingPlugins) {
770 loadLatePlugins(splash, monitor, pluginsToLoad);
771 }
772
773 // Wait for splash disappearance (fix #9714)
774 GuiHelper.runInEDTAndWait(() -> {
775 splash.setVisible(false);
776 splash.dispose();
777 mainFrame.setVisible(true);
778 });
779
780 boolean maximized = Main.pref.getBoolean("gui.maximized", false);
781 if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
782 mainFrame.setMaximized(true);
783 }
784 if (main.menu.fullscreenToggleAction != null) {
785 main.menu.fullscreenToggleAction.initial();
786 }
787
788 SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
789
790 if (Main.isPlatformWindows()) {
791 try {
792 // Check for insecure certificates to remove.
793 // This is Windows-dependant code but it can't go to preStartupHook (need i18n)
794 // neither startupHook (need to be called before remote control)
795 PlatformHookWindows.removeInsecureCertificates();
796 } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
797 Logging.error(e);
798 }
799 }
800
801 if (RemoteControl.PROP_REMOTECONTROL_ENABLED.get()) {
802 RemoteControl.start();
803 }
804
805 if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
806 MessageNotifier.start();
807 }
808
809 if (Main.pref.getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
810 // Repaint manager is registered so late for a reason - there is lots of violation during startup process
811 // but they don't seem to break anything and are difficult to fix
812 Logging.info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
813 RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
814 }
815 }
816
817 static void setupUIManager() {
818 String defaultlaf = platform.getDefaultStyle();
819 String laf = LafPreference.LAF.get();
820 try {
821 UIManager.setLookAndFeel(laf);
822 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
823 // Try to find look and feel in plugin classloaders
824 Logging.trace(e);
825 Class<?> klass = null;
826 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
827 try {
828 klass = cl.loadClass(laf);
829 break;
830 } catch (ClassNotFoundException ex) {
831 Logging.trace(ex);
832 }
833 }
834 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
835 try {
836 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
837 } catch (ReflectiveOperationException ex) {
838 Logging.log(Logging.LEVEL_WARN, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage(), ex);
839 } catch (UnsupportedLookAndFeelException ex) {
840 Logging.info("Look and Feel not supported: " + laf);
841 LafPreference.LAF.put(defaultlaf);
842 Logging.trace(ex);
843 }
844 } else {
845 Logging.info("Look and Feel not found: " + laf);
846 LafPreference.LAF.put(defaultlaf);
847 }
848 } catch (UnsupportedLookAndFeelException e) {
849 Logging.info("Look and Feel not supported: " + laf);
850 LafPreference.LAF.put(defaultlaf);
851 Logging.trace(e);
852 } catch (InstantiationException | IllegalAccessException e) {
853 Logging.error(e);
854 }
855
856 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
857 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
858 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
859 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
860 // Ensures caret color is the same than text foreground color, see #12257
861 // See http://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
862 for (String p : Arrays.asList(
863 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
864 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
865 }
866 }
867
868 private static InputStream openStream(URL url) throws IOException {
869 if ("file".equals(url.getProtocol())) {
870 return url.openStream();
871 } else {
872 return HttpClient.create(url).connect().getContent();
873 }
874 }
875
876 static Collection<PluginInformation> updateAndLoadEarlyPlugins(SplashScreen splash, SplashProgressMonitor monitor) {
877 Collection<PluginInformation> pluginsToLoad;
878 pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
879 if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
880 monitor.subTask(tr("Updating plugins"));
881 pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
882 }
883
884 monitor.indeterminateSubTask(tr("Installing updated plugins"));
885 PluginHandler.installDownloadedPlugins(true);
886
887 monitor.indeterminateSubTask(tr("Loading early plugins"));
888 PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
889 return pluginsToLoad;
890 }
891
892 static void loadLatePlugins(SplashScreen splash, SplashProgressMonitor monitor, Collection<PluginInformation> pluginsToLoad) {
893 monitor.indeterminateSubTask(tr("Loading plugins"));
894 PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
895 GuiHelper.runInEDTAndWait(() -> toolbar.refreshToolbarControl());
896 }
897
898 private static void processOffline(ProgramArguments args) {
899 for (String offlineNames : args.get(Option.OFFLINE)) {
900 for (String s : offlineNames.split(",")) {
901 try {
902 Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
903 } catch (IllegalArgumentException e) {
904 Logging.log(Logging.LEVEL_ERROR,
905 tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
906 s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())), e);
907 System.exit(1);
908 return;
909 }
910 }
911 }
912 Set<OnlineResource> offline = Main.getOfflineResources();
913 if (!offline.isEmpty()) {
914 Logging.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
915 "JOSM is running in offline mode. These resources will not be available: {0}",
916 offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
917 }
918 }
919
920 /**
921 * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
922 * disabling or enabling IPV6 may only be done with next start.
923 */
924 private static void checkIPv6() {
925 if ("auto".equals(Main.pref.get("prefer.ipv6", "auto"))) {
926 new Thread((Runnable) () -> { /* this may take some time (DNS, Connect) */
927 boolean hasv6 = false;
928 boolean wasv6 = Main.pref.getBoolean("validated.ipv6", false);
929 try {
930 /* Use the check result from last run of the software, as after the test, value
931 changes have no effect anymore */
932 if (wasv6) {
933 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
934 }
935 for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
936 if (a instanceof Inet6Address) {
937 if (a.isReachable(1000)) {
938 /* be sure it REALLY works */
939 SSLSocketFactory.getDefault().createSocket(a, 443).close();
940 Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
941 if (!wasv6) {
942 Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4 after next restart."));
943 } else {
944 Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4."));
945 }
946 hasv6 = true;
947 }
948 break; /* we're done */
949 }
950 }
951 } catch (IOException | SecurityException e) {
952 Logging.debug("Exception while checking IPv6 connectivity: {0}", e);
953 Logging.trace(e);
954 }
955 if (wasv6 && !hasv6) {
956 Logging.info(tr("Detected no useable IPv6 network, prefering IPv4 over IPv6 after next restart."));
957 Main.pref.put("validated.ipv6", hasv6); // be sure it is stored before the restart!
958 try {
959 RestartAction.restartJOSM();
960 } catch (IOException e) {
961 Logging.error(e);
962 }
963 }
964 Main.pref.put("validated.ipv6", hasv6);
965 }, "IPv6-checker").start();
966 }
967 }
968
969 /**
970 * Download area specified as Bounds value.
971 * @param rawGps Flag to download raw GPS tracks
972 * @param b The bounds value
973 * @return the complete download task (including post-download handler)
974 */
975 static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
976 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
977 // asynchronously launch the download task ...
978 Future<?> future = task.download(true, b, null);
979 // ... and the continuation when the download is finished (this will wait for the download to finish)
980 return Collections.singletonList(MainApplication.worker.submit(new PostDownloadHandler(task, future)));
981 }
982
983 /**
984 * Handle command line instructions after GUI has been initialized.
985 * @param args program arguments
986 * @return the list of submitted tasks
987 */
988 static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
989 List<Future<?>> tasks = new ArrayList<>();
990 List<File> fileList = new ArrayList<>();
991 for (String s : args.get(Option.DOWNLOAD)) {
992 tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
993 }
994 if (!fileList.isEmpty()) {
995 tasks.add(OpenFileAction.openFiles(fileList, true));
996 }
997 for (String s : args.get(Option.DOWNLOADGPS)) {
998 tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
999 }
1000 final Collection<String> selectionArguments = args.get(Option.SELECTION);
1001 if (!selectionArguments.isEmpty()) {
1002 tasks.add(MainApplication.worker.submit(() -> {
1003 for (String s : selectionArguments) {
1004 SearchAction.search(s, SearchAction.SearchMode.add);
1005 }
1006 }));
1007 }
1008 return tasks;
1009 }
1010
1011 private static class GuiFinalizationWorker implements Runnable {
1012
1013 private final ProgramArguments args;
1014 private final DefaultProxySelector proxySelector;
1015
1016 GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
1017 this.args = args;
1018 this.proxySelector = proxySelector;
1019 }
1020
1021 @Override
1022 public void run() {
1023
1024 // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
1025 if (!handleProxyErrors()) {
1026 handleNetworkErrors();
1027 }
1028
1029 // Restore autosave layers after crash and start autosave thread
1030 handleAutosave();
1031
1032 // Handle command line instructions
1033 postConstructorProcessCmdLine(args);
1034
1035 // Show download dialog if autostart is enabled
1036 DownloadDialog.autostartIfNeeded();
1037 }
1038
1039 private static void handleAutosave() {
1040 if (AutosaveTask.PROP_AUTOSAVE_ENABLED.get()) {
1041 AutosaveTask autosaveTask = new AutosaveTask();
1042 List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
1043 if (!unsavedLayerFiles.isEmpty()) {
1044 ExtendedDialog dialog = new ExtendedDialog(
1045 Main.parent,
1046 tr("Unsaved osm data"),
1047 tr("Restore"), tr("Cancel"), tr("Discard")
1048 );
1049 dialog.setContent(
1050 trn("JOSM found {0} unsaved osm data layer. ",
1051 "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
1052 tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
1053 dialog.setButtonIcons("ok", "cancel", "dialogs/delete");
1054 int selection = dialog.showDialog().getValue();
1055 if (selection == 1) {
1056 autosaveTask.recoverUnsavedLayers();
1057 } else if (selection == 3) {
1058 autosaveTask.discardUnsavedLayers();
1059 }
1060 }
1061 autosaveTask.schedule();
1062 }
1063 }
1064
1065 private static boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
1066 if (hasErrors) {
1067 ExtendedDialog ed = new ExtendedDialog(
1068 Main.parent, title,
1069 tr("Change proxy settings"), tr("Cancel"));
1070 ed.setButtonIcons("dialogs/settings", "cancel").setCancelButton(2);
1071 ed.setMinimumSize(new Dimension(460, 260));
1072 ed.setIcon(JOptionPane.WARNING_MESSAGE);
1073 ed.setContent(message);
1074
1075 if (ed.showDialog().getValue() == 1) {
1076 PreferencesAction.forPreferenceSubTab(null, null, ProxyPreference.class).run();
1077 }
1078 }
1079 return hasErrors;
1080 }
1081
1082 private boolean handleProxyErrors() {
1083 return handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
1084 tr("JOSM tried to access the following resources:<br>" +
1085 "{0}" +
1086 "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
1087 "{1}" +
1088 "Would you like to change your proxy settings now?",
1089 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
1090 Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
1091 ));
1092 }
1093
1094 private static boolean handleNetworkErrors() {
1095 Map<String, Throwable> networkErrors = Main.getNetworkErrors();
1096 boolean condition = !networkErrors.isEmpty();
1097 if (condition) {
1098 Set<String> errors = new TreeSet<>();
1099 for (Throwable t : networkErrors.values()) {
1100 errors.add(t.toString());
1101 }
1102 return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
1103 tr("JOSM tried to access the following resources:<br>" +
1104 "{0}" +
1105 "but <b>failed</b> to do so, because of the following network errors:<br>" +
1106 "{1}" +
1107 "It may be due to a missing proxy configuration.<br>" +
1108 "Would you like to change your proxy settings now?",
1109 Utils.joinAsHtmlUnorderedList(networkErrors.keySet()),
1110 Utils.joinAsHtmlUnorderedList(errors)
1111 ));
1112 }
1113 return false;
1114 }
1115 }
1116}
Note: See TracBrowser for help on using the repository browser.