1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.gui;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 | import static org.openstreetmap.josm.tools.I18n.trn;
|
---|
6 |
|
---|
7 | import java.awt.BorderLayout;
|
---|
8 | import java.awt.Dimension;
|
---|
9 | import java.awt.GraphicsEnvironment;
|
---|
10 | import java.awt.event.KeyEvent;
|
---|
11 | import java.io.File;
|
---|
12 | import java.io.IOException;
|
---|
13 | import java.io.InputStream;
|
---|
14 | import java.net.Authenticator;
|
---|
15 | import java.net.Inet6Address;
|
---|
16 | import java.net.InetAddress;
|
---|
17 | import java.net.ProxySelector;
|
---|
18 | import java.net.URL;
|
---|
19 | import java.security.AllPermission;
|
---|
20 | import java.security.CodeSource;
|
---|
21 | import java.security.GeneralSecurityException;
|
---|
22 | import java.security.KeyStoreException;
|
---|
23 | import java.security.NoSuchAlgorithmException;
|
---|
24 | import java.security.PermissionCollection;
|
---|
25 | import java.security.Permissions;
|
---|
26 | import java.security.Policy;
|
---|
27 | import java.security.cert.CertificateException;
|
---|
28 | import java.util.ArrayList;
|
---|
29 | import java.util.Arrays;
|
---|
30 | import java.util.Collection;
|
---|
31 | import java.util.Collections;
|
---|
32 | import java.util.List;
|
---|
33 | import java.util.Locale;
|
---|
34 | import java.util.Map;
|
---|
35 | import java.util.Optional;
|
---|
36 | import java.util.Set;
|
---|
37 | import java.util.TreeSet;
|
---|
38 | import java.util.concurrent.Callable;
|
---|
39 | import java.util.concurrent.ExecutorService;
|
---|
40 | import java.util.concurrent.Future;
|
---|
41 | import java.util.logging.Level;
|
---|
42 | import java.util.stream.Collectors;
|
---|
43 | import java.util.stream.Stream;
|
---|
44 |
|
---|
45 | import javax.net.ssl.SSLSocketFactory;
|
---|
46 | import javax.swing.JComponent;
|
---|
47 | import javax.swing.JOptionPane;
|
---|
48 | import javax.swing.RepaintManager;
|
---|
49 | import javax.swing.SwingUtilities;
|
---|
50 |
|
---|
51 | import org.jdesktop.swinghelper.debug.CheckThreadViolationRepaintManager;
|
---|
52 | import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
|
---|
53 | import org.openstreetmap.josm.Main;
|
---|
54 | import org.openstreetmap.josm.actions.OpenFileAction;
|
---|
55 | import org.openstreetmap.josm.actions.PreferencesAction;
|
---|
56 | import org.openstreetmap.josm.actions.RestartAction;
|
---|
57 | import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
|
---|
58 | import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
|
---|
59 | import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
|
---|
60 | import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
|
---|
61 | import org.openstreetmap.josm.actions.mapmode.DrawAction;
|
---|
62 | import org.openstreetmap.josm.actions.search.SearchAction;
|
---|
63 | import org.openstreetmap.josm.data.Bounds;
|
---|
64 | import org.openstreetmap.josm.data.Version;
|
---|
65 | import org.openstreetmap.josm.data.osm.OsmPrimitive;
|
---|
66 | import org.openstreetmap.josm.data.validation.OsmValidator;
|
---|
67 | import org.openstreetmap.josm.gui.ProgramArguments.Option;
|
---|
68 | import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
|
---|
69 | import org.openstreetmap.josm.gui.download.DownloadDialog;
|
---|
70 | import org.openstreetmap.josm.gui.io.CustomConfigurator.XMLCommandProcessor;
|
---|
71 | import org.openstreetmap.josm.gui.layer.AutosaveTask;
|
---|
72 | import org.openstreetmap.josm.gui.layer.TMSLayer;
|
---|
73 | import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
|
---|
74 | import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
|
---|
75 | import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
|
---|
76 | import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
|
---|
77 | import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
|
---|
78 | import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
|
---|
79 | import org.openstreetmap.josm.gui.util.GuiHelper;
|
---|
80 | import org.openstreetmap.josm.io.CertificateAmendment;
|
---|
81 | import org.openstreetmap.josm.io.DefaultProxySelector;
|
---|
82 | import org.openstreetmap.josm.io.MessageNotifier;
|
---|
83 | import org.openstreetmap.josm.io.OnlineResource;
|
---|
84 | import org.openstreetmap.josm.io.OsmApi;
|
---|
85 | import org.openstreetmap.josm.io.OsmApiInitializationException;
|
---|
86 | import org.openstreetmap.josm.io.OsmTransferCanceledException;
|
---|
87 | import org.openstreetmap.josm.io.auth.CredentialsManager;
|
---|
88 | import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
|
---|
89 | import org.openstreetmap.josm.io.protocols.data.Handler;
|
---|
90 | import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
|
---|
91 | import org.openstreetmap.josm.plugins.PluginHandler;
|
---|
92 | import org.openstreetmap.josm.plugins.PluginInformation;
|
---|
93 | import org.openstreetmap.josm.tools.FontsManager;
|
---|
94 | import org.openstreetmap.josm.tools.HttpClient;
|
---|
95 | import org.openstreetmap.josm.tools.I18n;
|
---|
96 | import org.openstreetmap.josm.tools.Logging;
|
---|
97 | import org.openstreetmap.josm.tools.OpenBrowser;
|
---|
98 | import org.openstreetmap.josm.tools.OsmUrlToBounds;
|
---|
99 | import org.openstreetmap.josm.tools.OverpassTurboQueryWizard;
|
---|
100 | import org.openstreetmap.josm.tools.PlatformHookWindows;
|
---|
101 | import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
|
---|
102 | import org.openstreetmap.josm.tools.Shortcut;
|
---|
103 | import org.openstreetmap.josm.tools.Territories;
|
---|
104 | import org.openstreetmap.josm.tools.Utils;
|
---|
105 | import org.openstreetmap.josm.tools.WindowGeometry;
|
---|
106 | import org.openstreetmap.josm.tools.bugreport.BugReport;
|
---|
107 | import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
|
---|
108 |
|
---|
109 | /**
|
---|
110 | * Main window class application.
|
---|
111 | *
|
---|
112 | * @author imi
|
---|
113 | */
|
---|
114 | public class MainApplication extends Main {
|
---|
115 |
|
---|
116 | /**
|
---|
117 | * Command-line arguments used to run the application.
|
---|
118 | */
|
---|
119 | private static final List<String> COMMAND_LINE_ARGS = new ArrayList<>();
|
---|
120 |
|
---|
121 | /**
|
---|
122 | * The MapFrame.
|
---|
123 | */
|
---|
124 | static MapFrame map;
|
---|
125 |
|
---|
126 | private final MainFrame mainFrame;
|
---|
127 |
|
---|
128 | /**
|
---|
129 | * The worker thread slave. This is for executing all long and intensive
|
---|
130 | * calculations. The executed runnables are guaranteed to be executed separately and sequential.
|
---|
131 | * @since 12634 (as a replacement to {@code Main.worker})
|
---|
132 | */
|
---|
133 | public static final ExecutorService worker = new ProgressMonitorExecutor("main-worker-%d", Thread.NORM_PRIORITY);
|
---|
134 |
|
---|
135 | /**
|
---|
136 | * Constructs a new {@code MainApplication} without a window.
|
---|
137 | */
|
---|
138 | public MainApplication() {
|
---|
139 | this(null);
|
---|
140 | }
|
---|
141 |
|
---|
142 | /**
|
---|
143 | * Constructs a main frame, ready sized and operating. Does not display the frame.
|
---|
144 | * @param mainFrame The main JFrame of the application
|
---|
145 | * @since 10340
|
---|
146 | */
|
---|
147 | public MainApplication(MainFrame mainFrame) {
|
---|
148 | this.mainFrame = mainFrame;
|
---|
149 | }
|
---|
150 |
|
---|
151 | @Override
|
---|
152 | protected List<InitializationTask> beforeInitializationTasks() {
|
---|
153 | return Arrays.asList(
|
---|
154 | new InitializationTask(tr("Starting file watcher"), fileWatcher::start),
|
---|
155 | new InitializationTask(tr("Executing platform startup hook"), platform::startupHook),
|
---|
156 | new InitializationTask(tr("Building main menu"), this::initializeMainWindow),
|
---|
157 | new InitializationTask(tr("Updating user interface"), () -> {
|
---|
158 | undoRedo.addCommandQueueListener(redoUndoListener);
|
---|
159 | // creating toolbar
|
---|
160 | GuiHelper.runInEDTAndWait(() -> contentPanePrivate.add(toolbar.control, BorderLayout.NORTH));
|
---|
161 | // help shortcut
|
---|
162 | registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
|
---|
163 | KeyEvent.VK_F1, Shortcut.DIRECT));
|
---|
164 | }),
|
---|
165 | // This needs to be done before RightAndLefthandTraffic::initialize is called
|
---|
166 | new InitializationTask(tr("Initializing internal boundaries data"), Territories::initialize)
|
---|
167 | );
|
---|
168 | }
|
---|
169 |
|
---|
170 | @Override
|
---|
171 | protected Collection<InitializationTask> parallelInitializationTasks() {
|
---|
172 | return Arrays.asList(
|
---|
173 | new InitializationTask(tr("Initializing OSM API"), () -> {
|
---|
174 | // We try to establish an API connection early, so that any API
|
---|
175 | // capabilities are already known to the editor instance. However
|
---|
176 | // if it goes wrong that's not critical at this stage.
|
---|
177 | try {
|
---|
178 | OsmApi.getOsmApi().initialize(null, true);
|
---|
179 | } catch (OsmTransferCanceledException | OsmApiInitializationException e) {
|
---|
180 | Logging.warn(Logging.getErrorMessage(Utils.getRootCause(e)));
|
---|
181 | }
|
---|
182 | }),
|
---|
183 | new InitializationTask(tr("Initializing internal traffic data"), RightAndLefthandTraffic::initialize),
|
---|
184 | new InitializationTask(tr("Initializing validator"), OsmValidator::initialize),
|
---|
185 | new InitializationTask(tr("Initializing presets"), TaggingPresets::initialize),
|
---|
186 | new InitializationTask(tr("Initializing map styles"), MapPaintPreference::initialize),
|
---|
187 | new InitializationTask(tr("Loading imagery preferences"), ImageryPreference::initialize)
|
---|
188 | );
|
---|
189 | }
|
---|
190 |
|
---|
191 | @Override
|
---|
192 | protected List<Callable<?>> asynchronousCallableTasks() {
|
---|
193 | return Arrays.asList(
|
---|
194 | OverpassTurboQueryWizard::getInstance
|
---|
195 | );
|
---|
196 | }
|
---|
197 |
|
---|
198 | @Override
|
---|
199 | protected List<Runnable> asynchronousRunnableTasks() {
|
---|
200 | return Arrays.asList(
|
---|
201 | TMSLayer::getCache,
|
---|
202 | OsmValidator::initializeTests
|
---|
203 | );
|
---|
204 | }
|
---|
205 |
|
---|
206 | @Override
|
---|
207 | protected List<InitializationTask> afterInitializationTasks() {
|
---|
208 | return Arrays.asList(
|
---|
209 | new InitializationTask(tr("Updating user interface"), () -> GuiHelper.runInEDTAndWait(() -> {
|
---|
210 | // hooks for the jmapviewer component
|
---|
211 | FeatureAdapter.registerBrowserAdapter(OpenBrowser::displayUrl);
|
---|
212 | FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
|
---|
213 | FeatureAdapter.registerLoggingAdapter(name -> Logging.getLogger());
|
---|
214 | // UI update
|
---|
215 | toolbar.refreshToolbarControl();
|
---|
216 | toolbar.control.updateUI();
|
---|
217 | contentPanePrivate.updateUI();
|
---|
218 | }))
|
---|
219 | );
|
---|
220 | }
|
---|
221 |
|
---|
222 | @Override
|
---|
223 | protected void initializeMainWindow() {
|
---|
224 | if (mainFrame != null) {
|
---|
225 | panel = mainFrame.getPanel();
|
---|
226 | mainFrame.initialize();
|
---|
227 | menu = mainFrame.getMenu();
|
---|
228 | } else {
|
---|
229 | // required for running some tests.
|
---|
230 | panel = new MainPanel(Main.getLayerManager());
|
---|
231 | menu = new MainMenu();
|
---|
232 | }
|
---|
233 | panel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
|
---|
234 | panel.reAddListeners();
|
---|
235 | }
|
---|
236 |
|
---|
237 | @Override
|
---|
238 | protected void shutdown() {
|
---|
239 | if (!GraphicsEnvironment.isHeadless()) {
|
---|
240 | worker.shutdown();
|
---|
241 | }
|
---|
242 | if (mainFrame != null) {
|
---|
243 | mainFrame.storeState();
|
---|
244 | }
|
---|
245 | if (map != null) {
|
---|
246 | map.rememberToggleDialogWidth();
|
---|
247 | }
|
---|
248 | super.shutdown();
|
---|
249 | if (!GraphicsEnvironment.isHeadless()) {
|
---|
250 | worker.shutdownNow();
|
---|
251 | }
|
---|
252 | }
|
---|
253 |
|
---|
254 | @Override
|
---|
255 | protected Bounds getRealBounds() {
|
---|
256 | return isDisplayingMapView() ? map.mapView.getRealBounds() : null;
|
---|
257 | }
|
---|
258 |
|
---|
259 | @Override
|
---|
260 | protected void restoreOldBounds(Bounds oldBounds) {
|
---|
261 | if (isDisplayingMapView()) {
|
---|
262 | map.mapView.zoomTo(oldBounds);
|
---|
263 | }
|
---|
264 | }
|
---|
265 |
|
---|
266 | @Override
|
---|
267 | public Collection<OsmPrimitive> getInProgressSelection() {
|
---|
268 | if (map != null && map.mapMode instanceof DrawAction) {
|
---|
269 | return ((DrawAction) map.mapMode).getInProgressSelection();
|
---|
270 | } else {
|
---|
271 | return super.getInProgressSelection();
|
---|
272 | }
|
---|
273 | }
|
---|
274 |
|
---|
275 | /**
|
---|
276 | * Returns the command-line arguments used to run the application.
|
---|
277 | * @return the command-line arguments used to run the application
|
---|
278 | * @since 11650
|
---|
279 | */
|
---|
280 | public static List<String> getCommandLineArgs() {
|
---|
281 | return Collections.unmodifiableList(COMMAND_LINE_ARGS);
|
---|
282 | }
|
---|
283 |
|
---|
284 | /**
|
---|
285 | * Returns the MapFrame.
|
---|
286 | * <p>
|
---|
287 | * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
|
---|
288 | * @return the MapFrame
|
---|
289 | * @see MainPanel
|
---|
290 | * @since 12630 (as a replacement to {@code Main.map})
|
---|
291 | */
|
---|
292 | public static MapFrame getMap() {
|
---|
293 | return map;
|
---|
294 | }
|
---|
295 |
|
---|
296 | /**
|
---|
297 | * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
|
---|
298 | * it only shows the MOTD panel.
|
---|
299 | * <p>
|
---|
300 | * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
|
---|
301 | *
|
---|
302 | * @return <code>true</code> if JOSM currently displays a map view
|
---|
303 | * @since 12630 (as a replacement to {@code Main.isDisplayingMapView()})
|
---|
304 | */
|
---|
305 | @SuppressWarnings("deprecation")
|
---|
306 | public static boolean isDisplayingMapView() {
|
---|
307 | return map != null && map.mapView != null;
|
---|
308 | }
|
---|
309 |
|
---|
310 | /**
|
---|
311 | * Displays help on the console
|
---|
312 | * @since 2748
|
---|
313 | */
|
---|
314 | public static void showHelp() {
|
---|
315 | // TODO: put in a platformHook for system that have no console by default
|
---|
316 | System.out.println(getHelp());
|
---|
317 | }
|
---|
318 |
|
---|
319 | static String getHelp() {
|
---|
320 | return tr("Java OpenStreetMap Editor")+" ["
|
---|
321 | +Version.getInstance().getAgentString()+"]\n\n"+
|
---|
322 | tr("usage")+":\n"+
|
---|
323 | "\tjava -jar josm.jar <options>...\n\n"+
|
---|
324 | tr("options")+":\n"+
|
---|
325 | "\t--help|-h "+tr("Show this help")+'\n'+
|
---|
326 | "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+'\n'+
|
---|
327 | "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+'\n'+
|
---|
328 | "\t[--download=]<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z)")+'\n'+
|
---|
329 | "\t[--download=]<filename> "+tr("Open a file (any file type that can be opened with File/Open)")+'\n'+
|
---|
330 | "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw GPS")+'\n'+
|
---|
331 | "\t--downloadgps=<URL> "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z) as raw GPS")+'\n'+
|
---|
332 | "\t--selection=<searchstring> "+tr("Select with the given search")+'\n'+
|
---|
333 | "\t--[no-]maximize "+tr("Launch in maximized mode")+'\n'+
|
---|
334 | "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+
|
---|
335 | "\t--load-preferences=<url-to-xml> "+tr("Changes preferences according to the XML file")+"\n\n"+
|
---|
336 | "\t--set=<key>=<value> "+tr("Set preference key to value")+"\n\n"+
|
---|
337 | "\t--language=<language> "+tr("Set the language")+"\n\n"+
|
---|
338 | "\t--version "+tr("Displays the JOSM version and exits")+"\n\n"+
|
---|
339 | "\t--debug "+tr("Print debugging messages to console")+"\n\n"+
|
---|
340 | "\t--skip-plugins "+tr("Skip loading plugins")+"\n\n"+
|
---|
341 | "\t--offline=<osm_api|josm_website|all> "+tr("Disable access to the given resource(s), separated by comma")+"\n\n"+
|
---|
342 | tr("options provided as Java system properties")+":\n"+
|
---|
343 | align("\t-Djosm.dir.name=JOSM") + tr("Change the JOSM directory name") + "\n\n" +
|
---|
344 | align("\t-Djosm.pref=" + tr("/PATH/TO/JOSM/PREF ")) + tr("Set the preferences directory") + "\n" +
|
---|
345 | align("\t") + tr("Default: {0}", platform.getDefaultPrefDirectory()) + "\n\n" +
|
---|
346 | align("\t-Djosm.userdata=" + tr("/PATH/TO/JOSM/USERDATA")) + tr("Set the user data directory") + "\n" +
|
---|
347 | align("\t") + tr("Default: {0}", platform.getDefaultUserDataDirectory()) + "\n\n" +
|
---|
348 | align("\t-Djosm.cache=" + tr("/PATH/TO/JOSM/CACHE ")) + tr("Set the cache directory") + "\n" +
|
---|
349 | align("\t") + tr("Default: {0}", platform.getDefaultCacheDirectory()) + "\n\n" +
|
---|
350 | align("\t-Djosm.home=" + tr("/PATH/TO/JOSM/HOMEDIR ")) +
|
---|
351 | tr("Set the preferences+data+cache directory (cache directory will be josm.home/cache)")+"\n\n"+
|
---|
352 | tr("-Djosm.home has lower precedence, i.e. the specific setting overrides the general one")+"\n\n"+
|
---|
353 | tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
|
---|
354 | " Java option to specify the maximum size of allocated memory in megabytes")+":\n"+
|
---|
355 | "\t-Xmx...m\n\n"+
|
---|
356 | tr("examples")+":\n"+
|
---|
357 | "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
|
---|
358 | "\tjava -jar josm.jar "+OsmUrlToBounds.getURL(43.2, 11.1, 13)+'\n'+
|
---|
359 | "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
|
---|
360 | "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
|
---|
361 | "\tjava -Djosm.pref=$XDG_CONFIG_HOME -Djosm.userdata=$XDG_DATA_HOME -Djosm.cache=$XDG_CACHE_HOME -jar josm.jar\n"+
|
---|
362 | "\tjava -Djosm.dir.name=josm_dev -jar josm.jar\n"+
|
---|
363 | "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
|
---|
364 | "\tjava -Xmx1024m -jar josm.jar\n\n"+
|
---|
365 | tr("Parameters --download, --downloadgps, and --selection are processed in this order.")+'\n'+
|
---|
366 | tr("Make sure you load some data if you use --selection.")+'\n';
|
---|
367 | }
|
---|
368 |
|
---|
369 | private static String align(String str) {
|
---|
370 | return str + Stream.generate(() -> " ").limit(Math.max(0, 43 - str.length())).collect(Collectors.joining(""));
|
---|
371 | }
|
---|
372 |
|
---|
373 | /**
|
---|
374 | * Main application Startup
|
---|
375 | * @param argArray Command-line arguments
|
---|
376 | */
|
---|
377 | public static void main(final String[] argArray) {
|
---|
378 | I18n.init();
|
---|
379 |
|
---|
380 | ProgramArguments args = null;
|
---|
381 | // construct argument table
|
---|
382 | try {
|
---|
383 | args = new ProgramArguments(argArray);
|
---|
384 | } catch (IllegalArgumentException e) {
|
---|
385 | System.err.println(e.getMessage());
|
---|
386 | System.exit(1);
|
---|
387 | return;
|
---|
388 | }
|
---|
389 |
|
---|
390 | Level logLevel = args.getLogLevel();
|
---|
391 | Logging.setLogLevel(logLevel);
|
---|
392 | if (!args.showVersion() && !args.showHelp()) {
|
---|
393 | Logging.info(tr("Log level is at {0} ({1}, {2})", logLevel.getLocalizedName(), logLevel.getName(), logLevel.intValue()));
|
---|
394 | }
|
---|
395 |
|
---|
396 | Optional<String> language = args.getSingle(Option.LANGUAGE);
|
---|
397 | I18n.set(language.orElse(null));
|
---|
398 |
|
---|
399 | Policy.setPolicy(new Policy() {
|
---|
400 | // Permissions for plug-ins loaded when josm is started via webstart
|
---|
401 | private PermissionCollection pc;
|
---|
402 |
|
---|
403 | {
|
---|
404 | pc = new Permissions();
|
---|
405 | pc.add(new AllPermission());
|
---|
406 | }
|
---|
407 |
|
---|
408 | @Override
|
---|
409 | public PermissionCollection getPermissions(CodeSource codesource) {
|
---|
410 | return pc;
|
---|
411 | }
|
---|
412 | });
|
---|
413 |
|
---|
414 | Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
|
---|
415 |
|
---|
416 | // initialize the platform hook, and
|
---|
417 | Main.determinePlatformHook();
|
---|
418 | // call the really early hook before we do anything else
|
---|
419 | Main.platform.preStartupHook();
|
---|
420 |
|
---|
421 | if (args.showVersion()) {
|
---|
422 | System.out.println(Version.getInstance().getAgentString());
|
---|
423 | return;
|
---|
424 | } else if (args.showHelp()) {
|
---|
425 | showHelp();
|
---|
426 | return;
|
---|
427 | }
|
---|
428 |
|
---|
429 | COMMAND_LINE_ARGS.addAll(Arrays.asList(argArray));
|
---|
430 |
|
---|
431 | boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
|
---|
432 | if (skipLoadingPlugins) {
|
---|
433 | Logging.info(tr("Plugin loading skipped"));
|
---|
434 | }
|
---|
435 |
|
---|
436 | if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
|
---|
437 | // Enable debug in OAuth signpost via system preference, but only at trace level
|
---|
438 | Utils.updateSystemProperty("debug", "true");
|
---|
439 | Logging.info(tr("Enabled detailed debug level (trace)"));
|
---|
440 | }
|
---|
441 |
|
---|
442 | Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
|
---|
443 |
|
---|
444 | args.getPreferencesToSet().forEach(Main.pref::put);
|
---|
445 |
|
---|
446 | if (!language.isPresent()) {
|
---|
447 | I18n.set(Main.pref.get("language", null));
|
---|
448 | }
|
---|
449 | Main.pref.updateSystemProperties();
|
---|
450 |
|
---|
451 | checkIPv6();
|
---|
452 |
|
---|
453 | processOffline(args);
|
---|
454 |
|
---|
455 | Main.platform.afterPrefStartupHook();
|
---|
456 |
|
---|
457 | FontsManager.initialize();
|
---|
458 |
|
---|
459 | I18n.setupLanguageFonts();
|
---|
460 |
|
---|
461 | Handler.install();
|
---|
462 |
|
---|
463 | WindowGeometry geometry = WindowGeometry.mainWindow("gui.geometry",
|
---|
464 | args.getSingle(Option.GEOMETRY).orElse(null),
|
---|
465 | !args.hasOption(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
|
---|
466 | final MainFrame mainFrame = new MainFrame(geometry);
|
---|
467 | if (mainFrame.getContentPane() instanceof JComponent) {
|
---|
468 | Main.contentPanePrivate = (JComponent) mainFrame.getContentPane();
|
---|
469 | }
|
---|
470 | Main.mainPanel = mainFrame.getPanel();
|
---|
471 | Main.parent = mainFrame;
|
---|
472 |
|
---|
473 | if (args.hasOption(Option.LOAD_PREFERENCES)) {
|
---|
474 | XMLCommandProcessor config = new XMLCommandProcessor(Main.pref);
|
---|
475 | for (String i : args.get(Option.LOAD_PREFERENCES)) {
|
---|
476 | Logging.info("Reading preferences from " + i);
|
---|
477 | try (InputStream is = openStream(new URL(i))) {
|
---|
478 | config.openAndReadXML(is);
|
---|
479 | } catch (IOException ex) {
|
---|
480 | throw BugReport.intercept(ex).put("file", i);
|
---|
481 | }
|
---|
482 | }
|
---|
483 | }
|
---|
484 |
|
---|
485 | try {
|
---|
486 | CertificateAmendment.addMissingCertificates();
|
---|
487 | } catch (IOException | GeneralSecurityException ex) {
|
---|
488 | Logging.warn(ex);
|
---|
489 | Logging.warn(Logging.getErrorMessage(Utils.getRootCause(ex)));
|
---|
490 | }
|
---|
491 | Authenticator.setDefault(DefaultAuthenticator.getInstance());
|
---|
492 | DefaultProxySelector proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
|
---|
493 | ProxySelector.setDefault(proxySelector);
|
---|
494 | OAuthAccessTokenHolder.getInstance().init(Main.pref, CredentialsManager.getInstance());
|
---|
495 |
|
---|
496 | final SplashScreen splash = GuiHelper.runInEDTAndWaitAndReturn(SplashScreen::new);
|
---|
497 | final SplashScreen.SplashProgressMonitor monitor = splash.getProgressMonitor();
|
---|
498 | monitor.beginTask(tr("Initializing"));
|
---|
499 | GuiHelper.runInEDT(() -> splash.setVisible(Main.pref.getBoolean("draw.splashscreen", true)));
|
---|
500 | Main.setInitStatusListener(new InitStatusListener() {
|
---|
501 |
|
---|
502 | @Override
|
---|
503 | public Object updateStatus(String event) {
|
---|
504 | monitor.beginTask(event);
|
---|
505 | return event;
|
---|
506 | }
|
---|
507 |
|
---|
508 | @Override
|
---|
509 | public void finish(Object status) {
|
---|
510 | if (status instanceof String) {
|
---|
511 | monitor.finishTask((String) status);
|
---|
512 | }
|
---|
513 | }
|
---|
514 | });
|
---|
515 |
|
---|
516 | Collection<PluginInformation> pluginsToLoad = null;
|
---|
517 |
|
---|
518 | if (!skipLoadingPlugins) {
|
---|
519 | pluginsToLoad = updateAndLoadEarlyPlugins(splash, monitor);
|
---|
520 | }
|
---|
521 |
|
---|
522 | monitor.indeterminateSubTask(tr("Setting defaults"));
|
---|
523 | preConstructorInit();
|
---|
524 |
|
---|
525 | monitor.indeterminateSubTask(tr("Creating main GUI"));
|
---|
526 | final Main main = new MainApplication(mainFrame);
|
---|
527 | main.initialize();
|
---|
528 |
|
---|
529 | if (!skipLoadingPlugins) {
|
---|
530 | loadLatePlugins(splash, monitor, pluginsToLoad);
|
---|
531 | }
|
---|
532 |
|
---|
533 | // Wait for splash disappearance (fix #9714)
|
---|
534 | GuiHelper.runInEDTAndWait(() -> {
|
---|
535 | splash.setVisible(false);
|
---|
536 | splash.dispose();
|
---|
537 | mainFrame.setVisible(true);
|
---|
538 | });
|
---|
539 |
|
---|
540 | boolean maximized = Main.pref.getBoolean("gui.maximized", false);
|
---|
541 | if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
|
---|
542 | mainFrame.setMaximized(true);
|
---|
543 | }
|
---|
544 | if (main.menu.fullscreenToggleAction != null) {
|
---|
545 | main.menu.fullscreenToggleAction.initial();
|
---|
546 | }
|
---|
547 |
|
---|
548 | SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
|
---|
549 |
|
---|
550 | if (Main.isPlatformWindows()) {
|
---|
551 | try {
|
---|
552 | // Check for insecure certificates to remove.
|
---|
553 | // This is Windows-dependant code but it can't go to preStartupHook (need i18n)
|
---|
554 | // neither startupHook (need to be called before remote control)
|
---|
555 | PlatformHookWindows.removeInsecureCertificates();
|
---|
556 | } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
|
---|
557 | Logging.error(e);
|
---|
558 | }
|
---|
559 | }
|
---|
560 |
|
---|
561 | if (RemoteControl.PROP_REMOTECONTROL_ENABLED.get()) {
|
---|
562 | RemoteControl.start();
|
---|
563 | }
|
---|
564 |
|
---|
565 | if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
|
---|
566 | MessageNotifier.start();
|
---|
567 | }
|
---|
568 |
|
---|
569 | if (Main.pref.getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
|
---|
570 | // Repaint manager is registered so late for a reason - there is lots of violation during startup process
|
---|
571 | // but they don't seem to break anything and are difficult to fix
|
---|
572 | Logging.info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
|
---|
573 | RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
|
---|
574 | }
|
---|
575 | }
|
---|
576 |
|
---|
577 | private static InputStream openStream(URL url) throws IOException {
|
---|
578 | if ("file".equals(url.getProtocol())) {
|
---|
579 | return url.openStream();
|
---|
580 | } else {
|
---|
581 | return HttpClient.create(url).connect().getContent();
|
---|
582 | }
|
---|
583 | }
|
---|
584 |
|
---|
585 | static Collection<PluginInformation> updateAndLoadEarlyPlugins(SplashScreen splash, SplashProgressMonitor monitor) {
|
---|
586 | Collection<PluginInformation> pluginsToLoad;
|
---|
587 | pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
|
---|
588 | if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
|
---|
589 | monitor.subTask(tr("Updating plugins"));
|
---|
590 | pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
|
---|
591 | }
|
---|
592 |
|
---|
593 | monitor.indeterminateSubTask(tr("Installing updated plugins"));
|
---|
594 | PluginHandler.installDownloadedPlugins(true);
|
---|
595 |
|
---|
596 | monitor.indeterminateSubTask(tr("Loading early plugins"));
|
---|
597 | PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
|
---|
598 | return pluginsToLoad;
|
---|
599 | }
|
---|
600 |
|
---|
601 | static void loadLatePlugins(SplashScreen splash, SplashProgressMonitor monitor, Collection<PluginInformation> pluginsToLoad) {
|
---|
602 | monitor.indeterminateSubTask(tr("Loading plugins"));
|
---|
603 | PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
|
---|
604 | GuiHelper.runInEDTAndWait(() -> toolbar.refreshToolbarControl());
|
---|
605 | }
|
---|
606 |
|
---|
607 | private static void processOffline(ProgramArguments args) {
|
---|
608 | for (String offlineNames : args.get(Option.OFFLINE)) {
|
---|
609 | for (String s : offlineNames.split(",")) {
|
---|
610 | try {
|
---|
611 | Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
|
---|
612 | } catch (IllegalArgumentException e) {
|
---|
613 | Logging.log(Logging.LEVEL_ERROR,
|
---|
614 | tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
|
---|
615 | s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())), e);
|
---|
616 | System.exit(1);
|
---|
617 | return;
|
---|
618 | }
|
---|
619 | }
|
---|
620 | }
|
---|
621 | Set<OnlineResource> offline = Main.getOfflineResources();
|
---|
622 | if (!offline.isEmpty()) {
|
---|
623 | Logging.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
|
---|
624 | "JOSM is running in offline mode. These resources will not be available: {0}",
|
---|
625 | offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
|
---|
626 | }
|
---|
627 | }
|
---|
628 |
|
---|
629 | /**
|
---|
630 | * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
|
---|
631 | * disabling or enabling IPV6 may only be done with next start.
|
---|
632 | */
|
---|
633 | private static void checkIPv6() {
|
---|
634 | if ("auto".equals(Main.pref.get("prefer.ipv6", "auto"))) {
|
---|
635 | new Thread((Runnable) () -> { /* this may take some time (DNS, Connect) */
|
---|
636 | boolean hasv6 = false;
|
---|
637 | boolean wasv6 = Main.pref.getBoolean("validated.ipv6", false);
|
---|
638 | try {
|
---|
639 | /* Use the check result from last run of the software, as after the test, value
|
---|
640 | changes have no effect anymore */
|
---|
641 | if (wasv6) {
|
---|
642 | Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
|
---|
643 | }
|
---|
644 | for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
|
---|
645 | if (a instanceof Inet6Address) {
|
---|
646 | if (a.isReachable(1000)) {
|
---|
647 | /* be sure it REALLY works */
|
---|
648 | SSLSocketFactory.getDefault().createSocket(a, 443).close();
|
---|
649 | Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
|
---|
650 | if (!wasv6) {
|
---|
651 | Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4 after next restart."));
|
---|
652 | } else {
|
---|
653 | Logging.info(tr("Detected useable IPv6 network, prefering IPv6 over IPv4."));
|
---|
654 | }
|
---|
655 | hasv6 = true;
|
---|
656 | }
|
---|
657 | break; /* we're done */
|
---|
658 | }
|
---|
659 | }
|
---|
660 | } catch (IOException | SecurityException e) {
|
---|
661 | Logging.debug("Exception while checking IPv6 connectivity: {0}", e);
|
---|
662 | Logging.trace(e);
|
---|
663 | }
|
---|
664 | if (wasv6 && !hasv6) {
|
---|
665 | Logging.info(tr("Detected no useable IPv6 network, prefering IPv4 over IPv6 after next restart."));
|
---|
666 | Main.pref.put("validated.ipv6", hasv6); // be sure it is stored before the restart!
|
---|
667 | try {
|
---|
668 | RestartAction.restartJOSM();
|
---|
669 | } catch (IOException e) {
|
---|
670 | Logging.error(e);
|
---|
671 | }
|
---|
672 | }
|
---|
673 | Main.pref.put("validated.ipv6", hasv6);
|
---|
674 | }, "IPv6-checker").start();
|
---|
675 | }
|
---|
676 | }
|
---|
677 |
|
---|
678 | /**
|
---|
679 | * Download area specified as Bounds value.
|
---|
680 | * @param rawGps Flag to download raw GPS tracks
|
---|
681 | * @param b The bounds value
|
---|
682 | * @return the complete download task (including post-download handler)
|
---|
683 | */
|
---|
684 | static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
|
---|
685 | DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
|
---|
686 | // asynchronously launch the download task ...
|
---|
687 | Future<?> future = task.download(true, b, null);
|
---|
688 | // ... and the continuation when the download is finished (this will wait for the download to finish)
|
---|
689 | return Collections.singletonList(MainApplication.worker.submit(new PostDownloadHandler(task, future)));
|
---|
690 | }
|
---|
691 |
|
---|
692 | /**
|
---|
693 | * Handle command line instructions after GUI has been initialized.
|
---|
694 | * @param args program arguments
|
---|
695 | * @return the list of submitted tasks
|
---|
696 | */
|
---|
697 | static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
|
---|
698 | List<Future<?>> tasks = new ArrayList<>();
|
---|
699 | List<File> fileList = new ArrayList<>();
|
---|
700 | for (String s : args.get(Option.DOWNLOAD)) {
|
---|
701 | tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
|
---|
702 | }
|
---|
703 | if (!fileList.isEmpty()) {
|
---|
704 | tasks.add(OpenFileAction.openFiles(fileList, true));
|
---|
705 | }
|
---|
706 | for (String s : args.get(Option.DOWNLOADGPS)) {
|
---|
707 | tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
|
---|
708 | }
|
---|
709 | final Collection<String> selectionArguments = args.get(Option.SELECTION);
|
---|
710 | if (!selectionArguments.isEmpty()) {
|
---|
711 | tasks.add(MainApplication.worker.submit(() -> {
|
---|
712 | for (String s : selectionArguments) {
|
---|
713 | SearchAction.search(s, SearchAction.SearchMode.add);
|
---|
714 | }
|
---|
715 | }));
|
---|
716 | }
|
---|
717 | return tasks;
|
---|
718 | }
|
---|
719 |
|
---|
720 | private static class GuiFinalizationWorker implements Runnable {
|
---|
721 |
|
---|
722 | private final ProgramArguments args;
|
---|
723 | private final DefaultProxySelector proxySelector;
|
---|
724 |
|
---|
725 | GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
|
---|
726 | this.args = args;
|
---|
727 | this.proxySelector = proxySelector;
|
---|
728 | }
|
---|
729 |
|
---|
730 | @Override
|
---|
731 | public void run() {
|
---|
732 |
|
---|
733 | // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
|
---|
734 | if (!handleProxyErrors()) {
|
---|
735 | handleNetworkErrors();
|
---|
736 | }
|
---|
737 |
|
---|
738 | // Restore autosave layers after crash and start autosave thread
|
---|
739 | handleAutosave();
|
---|
740 |
|
---|
741 | // Handle command line instructions
|
---|
742 | postConstructorProcessCmdLine(args);
|
---|
743 |
|
---|
744 | // Show download dialog if autostart is enabled
|
---|
745 | DownloadDialog.autostartIfNeeded();
|
---|
746 | }
|
---|
747 |
|
---|
748 | private static void handleAutosave() {
|
---|
749 | if (AutosaveTask.PROP_AUTOSAVE_ENABLED.get()) {
|
---|
750 | AutosaveTask autosaveTask = new AutosaveTask();
|
---|
751 | List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
|
---|
752 | if (!unsavedLayerFiles.isEmpty()) {
|
---|
753 | ExtendedDialog dialog = new ExtendedDialog(
|
---|
754 | Main.parent,
|
---|
755 | tr("Unsaved osm data"),
|
---|
756 | tr("Restore"), tr("Cancel"), tr("Discard")
|
---|
757 | );
|
---|
758 | dialog.setContent(
|
---|
759 | trn("JOSM found {0} unsaved osm data layer. ",
|
---|
760 | "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
|
---|
761 | tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
|
---|
762 | dialog.setButtonIcons("ok", "cancel", "dialogs/delete");
|
---|
763 | int selection = dialog.showDialog().getValue();
|
---|
764 | if (selection == 1) {
|
---|
765 | autosaveTask.recoverUnsavedLayers();
|
---|
766 | } else if (selection == 3) {
|
---|
767 | autosaveTask.discardUnsavedLayers();
|
---|
768 | }
|
---|
769 | }
|
---|
770 | autosaveTask.schedule();
|
---|
771 | }
|
---|
772 | }
|
---|
773 |
|
---|
774 | private static boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
|
---|
775 | if (hasErrors) {
|
---|
776 | ExtendedDialog ed = new ExtendedDialog(
|
---|
777 | Main.parent, title,
|
---|
778 | tr("Change proxy settings"), tr("Cancel"));
|
---|
779 | ed.setButtonIcons("dialogs/settings", "cancel").setCancelButton(2);
|
---|
780 | ed.setMinimumSize(new Dimension(460, 260));
|
---|
781 | ed.setIcon(JOptionPane.WARNING_MESSAGE);
|
---|
782 | ed.setContent(message);
|
---|
783 |
|
---|
784 | if (ed.showDialog().getValue() == 1) {
|
---|
785 | PreferencesAction.forPreferenceSubTab(null, null, ProxyPreference.class).run();
|
---|
786 | }
|
---|
787 | }
|
---|
788 | return hasErrors;
|
---|
789 | }
|
---|
790 |
|
---|
791 | private boolean handleProxyErrors() {
|
---|
792 | return handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
|
---|
793 | tr("JOSM tried to access the following resources:<br>" +
|
---|
794 | "{0}" +
|
---|
795 | "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
|
---|
796 | "{1}" +
|
---|
797 | "Would you like to change your proxy settings now?",
|
---|
798 | Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
|
---|
799 | Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
|
---|
800 | ));
|
---|
801 | }
|
---|
802 |
|
---|
803 | private static boolean handleNetworkErrors() {
|
---|
804 | Map<String, Throwable> networkErrors = Main.getNetworkErrors();
|
---|
805 | boolean condition = !networkErrors.isEmpty();
|
---|
806 | if (condition) {
|
---|
807 | Set<String> errors = new TreeSet<>();
|
---|
808 | for (Throwable t : networkErrors.values()) {
|
---|
809 | errors.add(t.toString());
|
---|
810 | }
|
---|
811 | return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
|
---|
812 | tr("JOSM tried to access the following resources:<br>" +
|
---|
813 | "{0}" +
|
---|
814 | "but <b>failed</b> to do so, because of the following network errors:<br>" +
|
---|
815 | "{1}" +
|
---|
816 | "It may be due to a missing proxy configuration.<br>" +
|
---|
817 | "Would you like to change your proxy settings now?",
|
---|
818 | Utils.joinAsHtmlUnorderedList(networkErrors.keySet()),
|
---|
819 | Utils.joinAsHtmlUnorderedList(errors)
|
---|
820 | ));
|
---|
821 | }
|
---|
822 | return false;
|
---|
823 | }
|
---|
824 | }
|
---|
825 | }
|
---|