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

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

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

run josm render --help to see the options

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