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