source: josm/trunk/src/org/openstreetmap/josm/Main.java@ 10635

Last change on this file since 10635 was 10605, checked in by Don-vip, 8 years ago

see #12478 - Use ​Swing Copy/Paste instead of CopyAction/PasteAction with custom buffer (layer part: patch by michael2402, modified) - gsoc-core

  • Property svn:eol-style set to native
File size: 65.6 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[626]2package org.openstreetmap.josm;
[5670]3
[301]4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.BorderLayout;
7import java.awt.Component;
[3815]8import java.awt.GridBagConstraints;
9import java.awt.GridBagLayout;
[5538]10import java.awt.Window;
[301]11import java.awt.event.KeyEvent;
[2876]12import java.awt.event.WindowAdapter;
13import java.awt.event.WindowEvent;
[301]14import java.io.File;
[9821]15import java.io.IOException;
[4126]16import java.lang.ref.WeakReference;
[301]17import java.net.URI;
18import java.net.URISyntaxException;
[6471]19import java.net.URL;
[5481]20import java.text.MessageFormat;
[2025]21import java.util.ArrayList;
[5538]22import java.util.Arrays;
[301]23import java.util.Collection;
[7420]24import java.util.Collections;
[10044]25import java.util.EnumSet;
[6642]26import java.util.HashMap;
[4126]27import java.util.Iterator;
[2025]28import java.util.List;
[8404]29import java.util.Locale;
[301]30import java.util.Map;
[7083]31import java.util.Objects;
[7434]32import java.util.Set;
[301]33import java.util.StringTokenizer;
[5134]34import java.util.concurrent.Callable;
[10212]35import java.util.concurrent.ExecutionException;
[1465]36import java.util.concurrent.ExecutorService;
[5134]37import java.util.concurrent.Executors;
[2322]38import java.util.concurrent.Future;
[7802]39import java.util.logging.Handler;
40import java.util.logging.Level;
41import java.util.logging.LogRecord;
42import java.util.logging.Logger;
[301]43
[3252]44import javax.swing.Action;
45import javax.swing.InputMap;
[301]46import javax.swing.JComponent;
47import javax.swing.JOptionPane;
48import javax.swing.JPanel;
[3815]49import javax.swing.JTextArea;
[3252]50import javax.swing.KeyStroke;
[7634]51import javax.swing.LookAndFeel;
[301]52import javax.swing.UIManager;
[6248]53import javax.swing.UnsupportedLookAndFeelException;
[301]54
[4489]55import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
[3444]56import org.openstreetmap.josm.actions.JosmAction;
[2047]57import org.openstreetmap.josm.actions.OpenFileAction;
[8809]58import org.openstreetmap.josm.actions.OpenLocationAction;
[301]59import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
60import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
[2322]61import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
62import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
[6546]63import org.openstreetmap.josm.actions.mapmode.DrawAction;
[301]64import org.openstreetmap.josm.actions.search.SearchAction;
65import org.openstreetmap.josm.data.Bounds;
66import org.openstreetmap.josm.data.Preferences;
[7816]67import org.openstreetmap.josm.data.ProjectionBounds;
[301]68import org.openstreetmap.josm.data.UndoRedoHandler;
[6992]69import org.openstreetmap.josm.data.ViewportData;
[8168]70import org.openstreetmap.josm.data.cache.JCSCacheManager;
[1990]71import org.openstreetmap.josm.data.coor.CoordinateFormat;
[2327]72import org.openstreetmap.josm.data.coor.LatLon;
[301]73import org.openstreetmap.josm.data.osm.DataSet;
[6546]74import org.openstreetmap.josm.data.osm.OsmPrimitive;
[2305]75import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy;
[301]76import org.openstreetmap.josm.data.projection.Projection;
[4126]77import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
[3669]78import org.openstreetmap.josm.data.validation.OsmValidator;
[301]79import org.openstreetmap.josm.gui.GettingStarted;
[5279]80import org.openstreetmap.josm.gui.MainApplication.Option;
[10432]81import org.openstreetmap.josm.gui.MainFrame;
[301]82import org.openstreetmap.josm.gui.MainMenu;
[10432]83import org.openstreetmap.josm.gui.MainPanel;
[301]84import org.openstreetmap.josm.gui.MapFrame;
[5957]85import org.openstreetmap.josm.gui.MapFrameListener;
[10604]86import org.openstreetmap.josm.gui.datatransfer.OsmTransferHandler;
[10605]87import org.openstreetmap.josm.gui.datatransfer.data.OsmLayerTransferData;
[6143]88import org.openstreetmap.josm.gui.help.HelpUtil;
[2025]89import org.openstreetmap.josm.gui.io.SaveLayersDialog;
[7420]90import org.openstreetmap.josm.gui.layer.AbstractModifiableLayer;
[301]91import org.openstreetmap.josm.gui.layer.Layer;
[10279]92import org.openstreetmap.josm.gui.layer.MainLayerManager;
[301]93import org.openstreetmap.josm.gui.layer.OsmDataLayer;
94import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
95import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
[4968]96import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
97import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
[5226]98import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
[4718]99import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
100import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
[8863]101import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
[10400]102import org.openstreetmap.josm.gui.util.GuiHelper;
[4897]103import org.openstreetmap.josm.gui.util.RedirectInputMap;
[6901]104import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
[7185]105import org.openstreetmap.josm.io.FileWatcher;
[7434]106import org.openstreetmap.josm.io.OnlineResource;
[3934]107import org.openstreetmap.josm.io.OsmApi;
[10212]108import org.openstreetmap.josm.io.OsmApiInitializationException;
109import org.openstreetmap.josm.io.OsmTransferCanceledException;
[7634]110import org.openstreetmap.josm.plugins.PluginHandler;
[4126]111import org.openstreetmap.josm.tools.CheckParameterUtil;
[3340]112import org.openstreetmap.josm.tools.I18n;
[301]113import org.openstreetmap.josm.tools.ImageProvider;
[4489]114import org.openstreetmap.josm.tools.OpenBrowser;
[1307]115import org.openstreetmap.josm.tools.OsmUrlToBounds;
[1023]116import org.openstreetmap.josm.tools.PlatformHook;
[1465]117import org.openstreetmap.josm.tools.PlatformHookOsx;
[1023]118import org.openstreetmap.josm.tools.PlatformHookUnixoid;
119import org.openstreetmap.josm.tools.PlatformHookWindows;
[1084]120import org.openstreetmap.josm.tools.Shortcut;
[4288]121import org.openstreetmap.josm.tools.Utils;
[626]122
[5829]123/**
124 * Abstract class holding various static global variables and methods used in large parts of JOSM application.
125 * @since 98
126 */
[6883]127public abstract class Main {
[2485]128
[1104]129 /**
[6143]130 * The JOSM website URL.
[6897]131 * @since 6897 (was public from 6143 to 6896)
[6143]132 */
[6920]133 private static final String JOSM_WEBSITE = "https://josm.openstreetmap.de";
[6453]134
[6143]135 /**
[6453]136 * The OSM website URL.
[6897]137 * @since 6897 (was public from 6453 to 6896)
[6453]138 */
[6920]139 private static final String OSM_WEBSITE = "https://www.openstreetmap.org";
[6453]140
141 /**
[2343]142 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
143 * it only shows the MOTD panel.
[10288]144 * <p>
145 * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
[2512]146 *
[5357]147 * @return <code>true</code> if JOSM currently displays a map view
[2343]148 */
[6883]149 public static boolean isDisplayingMapView() {
[9276]150 return map != null && map.mapView != null;
[2343]151 }
[6070]152
[2343]153 /**
[1104]154 * Global parent component for all dialogs and message boxes
155 */
156 public static Component parent;
[6070]157
[1104]158 /**
159 * Global application.
160 */
[8126]161 public static volatile Main main;
[6070]162
[1104]163 /**
[5831]164 * Command-line arguments used to run the application.
165 */
[8356]166 protected static final List<String> COMMAND_LINE_ARGS = new ArrayList<>();
[6070]167
[5831]168 /**
[1104]169 * The worker thread slave. This is for executing all long and intensive
170 * calculations. The executed runnables are guaranteed to be executed separately
171 * and sequential.
172 */
[8734]173 public static final ExecutorService worker = new ProgressMonitorExecutor("main-worker-%d", Thread.NORM_PRIORITY);
[6070]174
[1104]175 /**
176 * Global application preferences
177 */
[3542]178 public static Preferences pref;
[1814]179
[1104]180 /**
181 * The global paste buffer.
[10604]182 * @deprecated Use swing CCP instead. See {@link OsmTransferHandler}
[1104]183 */
[10604]184 @Deprecated
[4869]185 public static final PrimitiveDeepCopy pasteBuffer = new PrimitiveDeepCopy();
[6070]186
[5829]187 /**
188 * The layer source from which {@link Main#pasteBuffer} data comes from.
[10604]189 * @deprecated During a copy operation, the layer should be added. See {@link OsmLayerTransferData}.
[5829]190 */
[10604]191 @Deprecated
[1592]192 public static Layer pasteSource;
[4126]193
[1104]194 /**
[5829]195 * The MapFrame. Use {@link Main#setMapFrame} to set or clear it.
[10271]196 * <p>
197 * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
[10432]198 *
199 * @see MainPanel
[1104]200 */
201 public static MapFrame map;
[6070]202
[1104]203 /**
[10271]204 * Provides access to the layers displayed in the main view.
205 * @since 10271
206 */
[10279]207 private static final MainLayerManager layerManager = new MainLayerManager();
[10271]208
209 /**
[1104]210 * The toolbar preference control to register new actions.
211 */
[8126]212 public static volatile ToolbarPreferences toolbar;
[626]213
[5829]214 /**
215 * The commands undo/redo handler.
216 */
[7083]217 public final UndoRedoHandler undoRedo = new UndoRedoHandler();
[626]218
[5831]219 /**
220 * The progress monitor being currently displayed.
221 */
[4718]222 public static PleaseWaitProgressMonitor currentProgressMonitor;
223
[1104]224 /**
225 * The main menu bar at top of screen.
226 */
[5134]227 public MainMenu menu;
[626]228
[5481]229 /**
230 * The data validation handler.
231 */
[5134]232 public OsmValidator validator;
[6642]233
[1104]234 /**
[7185]235 * The file watcher service.
236 */
237 public static final FileWatcher fileWatcher = new FileWatcher();
238
239 /**
[1356]240 * The MOTD Layer.
[10432]241 * @deprecated Do not access this. It will be removed soon. You should not need to access the GettingStarted panel.
[1356]242 */
[10432]243 @Deprecated
244 public final GettingStarted gettingStarted = mainPanel.getGettingStarted();
[1356]245
[7005]246 protected static final Map<String, Throwable> NETWORK_ERRORS = new HashMap<>();
[6642]247
[7442]248 // First lines of last 5 error and warning messages, used for bug reports
[7420]249 private static final List<String> ERRORS_AND_WARNINGS = Collections.<String>synchronizedList(new ArrayList<String>());
250
[10044]251 private static final Set<OnlineResource> OFFLINE_RESOURCES = EnumSet.noneOf(OnlineResource.class);
[7434]252
[1356]253 /**
[6730]254 * Logging level (5 = trace, 4 = debug, 3 = info, 2 = warn, 1 = error, 0 = none).
[6248]255 * @since 6248
[1104]256 */
[6248]257 public static int logLevel = 3;
[6474]258
[10432]259 /**
260 * The real main panel. This field may be removed any time and made private to {@link MainFrame}
261 * @see #panel
262 */
263 protected static final MainPanel mainPanel = new MainPanel(getLayerManager());
264
[7420]265 private static void rememberWarnErrorMsg(String msg) {
266 // Only remember first line of message
267 int idx = msg.indexOf('\n');
268 if (idx > 0) {
269 ERRORS_AND_WARNINGS.add(msg.substring(0, idx));
270 } else {
271 ERRORS_AND_WARNINGS.add(msg);
272 }
[10498]273 // Only keep 10 lines to avoid memory leak
274 while (ERRORS_AND_WARNINGS.size() > 10) {
[7420]275 ERRORS_AND_WARNINGS.remove(0);
276 }
277 }
278
[5481]279 /**
[8857]280 * Replies the first lines of last 5 error and warning messages, used for bug reports
281 * @return the first lines of last 5 error and warning messages
[7420]282 * @since 7420
283 */
284 public static final Collection<String> getLastErrorAndWarnings() {
285 return Collections.unmodifiableList(ERRORS_AND_WARNINGS);
286 }
287
288 /**
[8959]289 * Clears the list of last error and warning messages.
290 * @since 8959
291 */
292 public static void clearLastErrorAndWarnings() {
293 ERRORS_AND_WARNINGS.clear();
294 }
295
296 /**
[6248]297 * Prints an error message if logging is on.
[5481]298 * @param msg The message to print.
[6248]299 * @since 6248
[5481]300 */
[6248]301 public static void error(String msg) {
302 if (logLevel < 1)
[4190]303 return;
[6643]304 if (msg != null && !msg.isEmpty()) {
305 System.err.println(tr("ERROR: {0}", msg));
[7420]306 rememberWarnErrorMsg("E: "+msg);
[6643]307 }
[6248]308 }
[6474]309
[6248]310 /**
311 * Prints a warning message if logging is on.
312 * @param msg The message to print.
313 */
314 public static void warn(String msg) {
315 if (logLevel < 2)
316 return;
[6643]317 if (msg != null && !msg.isEmpty()) {
318 System.err.println(tr("WARNING: {0}", msg));
[7420]319 rememberWarnErrorMsg("W: "+msg);
[6643]320 }
[4190]321 }
[6474]322
[5481]323 /**
[6248]324 * Prints an informational message if logging is on.
[5481]325 * @param msg The message to print.
326 */
[6248]327 public static void info(String msg) {
328 if (logLevel < 3)
[4190]329 return;
[6643]330 if (msg != null && !msg.isEmpty()) {
331 System.out.println(tr("INFO: {0}", msg));
332 }
[4190]333 }
[6474]334
[5481]335 /**
[6248]336 * Prints a debug message if logging is on.
[5481]337 * @param msg The message to print.
338 */
[6248]339 public static void debug(String msg) {
340 if (logLevel < 4)
[1104]341 return;
[6643]342 if (msg != null && !msg.isEmpty()) {
343 System.out.println(tr("DEBUG: {0}", msg));
344 }
[1104]345 }
[6474]346
[5481]347 /**
[6730]348 * Prints a trace message if logging is on.
349 * @param msg The message to print.
350 */
351 public static void trace(String msg) {
352 if (logLevel < 5)
353 return;
354 if (msg != null && !msg.isEmpty()) {
355 System.out.print("TRACE: ");
356 System.out.println(msg);
357 }
358 }
359
360 /**
[6852]361 * Determines if debug log level is enabled.
362 * Useful to avoid costly construction of debug messages when not enabled.
363 * @return {@code true} if log level is at least debug, {@code false} otherwise
364 * @since 6852
365 */
366 public static boolean isDebugEnabled() {
367 return logLevel >= 4;
368 }
369
370 /**
371 * Determines if trace log level is enabled.
372 * Useful to avoid costly construction of trace messages when not enabled.
373 * @return {@code true} if log level is at least trace, {@code false} otherwise
374 * @since 6852
375 */
376 public static boolean isTraceEnabled() {
377 return logLevel >= 5;
378 }
379
380 /**
[6535]381 * Prints a formatted error message if logging is on. Calls {@link MessageFormat#format}
[5481]382 * function to format text.
[6535]383 * @param msg The formatted message to print.
[5481]384 * @param objects The objects to insert into format string.
[6248]385 * @since 6248
[5481]386 */
[6248]387 public static void error(String msg, Object... objects) {
388 error(MessageFormat.format(msg, objects));
389 }
[6474]390
[6248]391 /**
[6535]392 * Prints a formatted warning message if logging is on. Calls {@link MessageFormat#format}
[6248]393 * function to format text.
[6535]394 * @param msg The formatted message to print.
[6248]395 * @param objects The objects to insert into format string.
396 */
397 public static void warn(String msg, Object... objects) {
[5481]398 warn(MessageFormat.format(msg, objects));
399 }
[6474]400
[5481]401 /**
[6535]402 * Prints a formatted informational message if logging is on. Calls {@link MessageFormat#format}
[5481]403 * function to format text.
[6535]404 * @param msg The formatted message to print.
[5481]405 * @param objects The objects to insert into format string.
406 */
[6248]407 public static void info(String msg, Object... objects) {
[5481]408 info(MessageFormat.format(msg, objects));
409 }
[6474]410
[5481]411 /**
[6535]412 * Prints a formatted debug message if logging is on. Calls {@link MessageFormat#format}
[5481]413 * function to format text.
[6535]414 * @param msg The formatted message to print.
[5481]415 * @param objects The objects to insert into format string.
416 */
[6248]417 public static void debug(String msg, Object... objects) {
[5481]418 debug(MessageFormat.format(msg, objects));
419 }
[6474]420
[6248]421 /**
[8015]422 * Prints a formatted trace message if logging is on. Calls {@link MessageFormat#format}
423 * function to format text.
424 * @param msg The formatted message to print.
425 * @param objects The objects to insert into format string.
426 */
427 public static void trace(String msg, Object... objects) {
428 trace(MessageFormat.format(msg, objects));
429 }
430
431 /**
[6248]432 * Prints an error message for the given Throwable.
433 * @param t The throwable object causing the error
434 * @since 6248
435 */
436 public static void error(Throwable t) {
[6642]437 error(t, true);
[6248]438 }
[6474]439
[6248]440 /**
441 * Prints a warning message for the given Throwable.
442 * @param t The throwable object causing the error
443 * @since 6248
444 */
445 public static void warn(Throwable t) {
[6642]446 warn(t, true);
447 }
448
449 /**
[10420]450 * Prints a debug message for the given Throwable. Useful for exceptions usually ignored
451 * @param t The throwable object causing the error
[10421]452 * @since 10420
[10420]453 */
454 public static void debug(Throwable t) {
455 debug(getErrorMessage(t));
456 }
457
458 /**
459 * Prints a trace message for the given Throwable. Useful for exceptions usually ignored
460 * @param t The throwable object causing the error
[10421]461 * @since 10420
[10420]462 */
463 public static void trace(Throwable t) {
464 trace(getErrorMessage(t));
465 }
466
467 /**
[6642]468 * Prints an error message for the given Throwable.
469 * @param t The throwable object causing the error
470 * @param stackTrace {@code true}, if the stacktrace should be displayed
[6643]471 * @since 6642
[6642]472 */
473 public static void error(Throwable t, boolean stackTrace) {
474 error(getErrorMessage(t));
475 if (stackTrace) {
476 t.printStackTrace();
477 }
478 }
479
480 /**
[10420]481 * Prints an error message for the given Throwable.
482 * @param t The throwable object causing the error
483 * @param message additional error message
[10421]484 * @since 10420
[10420]485 */
486 public static void error(Throwable t, String message) {
487 warn(message + ' ' + getErrorMessage(t));
488 }
489
490 /**
[6642]491 * Prints a warning message for the given Throwable.
492 * @param t The throwable object causing the error
493 * @param stackTrace {@code true}, if the stacktrace should be displayed
[6643]494 * @since 6642
[6642]495 */
496 public static void warn(Throwable t, boolean stackTrace) {
[6311]497 warn(getErrorMessage(t));
[6642]498 if (stackTrace) {
499 t.printStackTrace();
500 }
[6248]501 }
[6474]502
[6642]503 /**
[10420]504 * Prints a warning message for the given Throwable.
505 * @param t The throwable object causing the error
506 * @param message additional error message
[10421]507 * @since 10420
[10420]508 */
509 public static void warn(Throwable t, String message) {
510 warn(message + ' ' + getErrorMessage(t));
511 }
512
513 /**
[6642]514 * Returns a human-readable message of error, also usable for developers.
515 * @param t The error
516 * @return The human-readable error message
517 * @since 6642
518 */
519 public static String getErrorMessage(Throwable t) {
[6783]520 if (t == null) {
521 return null;
522 }
[6311]523 StringBuilder sb = new StringBuilder(t.getClass().getName());
524 String msg = t.getMessage();
525 if (msg != null) {
526 sb.append(": ").append(msg.trim());
527 }
[6474]528 Throwable cause = t.getCause();
529 if (cause != null && !cause.equals(t)) {
530 sb.append(". ").append(tr("Cause: ")).append(getErrorMessage(cause));
531 }
[6311]532 return sb.toString();
533 }
[301]534
[1104]535 /**
536 * Platform specific code goes in here.
537 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
538 * So if you need to hook into those early ones, split your class and send the one with the early hooks
539 * to the JOSM team for inclusion.
540 */
[8126]541 public static volatile PlatformHook platform;
[1023]542
[1104]543 /**
[5262]544 * Whether or not the java vm is openjdk
[2987]545 * We use this to work around openjdk bugs
546 */
547 public static boolean isOpenjdk;
548
549 /**
[6471]550 * Initializes {@code Main.pref} in normal application context.
551 * @since 6471
552 */
553 public static void initApplicationPreferences() {
554 Main.pref = new Preferences();
555 }
556
557 /**
[1104]558 * Set or clear (if passed <code>null</code>) the map.
[10432]559 * <p>
560 * To be removed any time
[5829]561 * @param map The map to set {@link Main#map} to. Can be null.
[10432]562 * @deprecated This is done automatically by {@link MainPanel}
[1104]563 */
[10432]564 @Deprecated
[1104]565 public final void setMapFrame(final MapFrame map) {
[10432]566 Main.warn("setMapFrame call was ignored.");
[1104]567 }
[626]568
[1104]569 /**
[1169]570 * Remove the specified layer from the map. If it is the last layer,
[1096]571 * remove the map as well.
[10432]572 * <p>
573 * To be removed end of 2016
[5831]574 * @param layer The layer to remove
[10432]575 * @deprecated You can remove the layer using {@link #getLayerManager()}
[1104]576 */
[10432]577 @Deprecated
[5896]578 public final synchronized void removeLayer(final Layer layer) {
[1633]579 if (map != null) {
[10271]580 getLayerManager().removeLayer(layer);
[1633]581 }
[1104]582 }
[626]583
[8840]584 private static volatile InitStatusListener initListener;
[4681]585
[8512]586 public interface InitStatusListener {
[4681]587
[8497]588 Object updateStatus(String event);
[8510]589
[8497]590 void finish(Object status);
[4681]591 }
592
593 public static void setInitStatusListener(InitStatusListener listener) {
[8497]594 CheckParameterUtil.ensureParameterNotNull(listener);
[4681]595 initListener = listener;
596 }
597
[6523]598 /**
[10340]599 * Constructs new {@code Main} object.
600 * @see #initialize()
[6523]601 */
[1104]602 public Main() {
603 main = this;
[10601]604 mainPanel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
[10340]605 }
606
607 /**
608 * Initializes the main object. A lot of global variables are initialized here.
609 * @since 10340
610 */
611 public void initialize() {
[8404]612 isOpenjdk = System.getProperty("java.vm.name").toUpperCase(Locale.ENGLISH).indexOf("OPENJDK") != -1;
[9205]613 fileWatcher.start();
[4681]614
[8497]615 new InitializationTask(tr("Executing platform startup hook")) {
616 @Override
617 public void initialize() {
618 platform.startupHook();
619 }
620 }.call();
[3934]621
[8497]622 new InitializationTask(tr("Building main menu")) {
[5138]623
[8497]624 @Override
625 public void initialize() {
[10340]626 initializeMainWindow();
[8497]627 }
628 }.call();
629
[5138]630 undoRedo.addCommandQueueListener(redoUndoListener);
631
632 // creating toolbar
633 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
634
635 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
636 KeyEvent.VK_F1, Shortcut.DIRECT));
637
[5134]638 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
[7005]639 List<Callable<Void>> tasks = new ArrayList<>();
[3934]640
[7476]641 tasks.add(new InitializationTask(tr("Initializing OSM API")) {
[626]642
[7476]643 @Override
[8497]644 public void initialize() {
[7476]645 // We try to establish an API connection early, so that any API
646 // capabilities are already known to the editor instance. However
647 // if it goes wrong that's not critical at this stage.
648 try {
649 OsmApi.getOsmApi().initialize(null, true);
[10212]650 } catch (OsmTransferCanceledException | OsmApiInitializationException e) {
[7476]651 Main.warn(getErrorMessage(Utils.getRootCause(e)));
[5134]652 }
[7476]653 }
654 });
[1023]655
[6779]656 tasks.add(new InitializationTask(tr("Initializing validator")) {
[626]657
[5134]658 @Override
[8497]659 public void initialize() {
[5177]660 validator = new OsmValidator();
[5134]661 }
662 });
663
[6779]664 tasks.add(new InitializationTask(tr("Initializing presets")) {
[5134]665
666 @Override
[8497]667 public void initialize() {
[7100]668 TaggingPresets.initialize();
[6779]669 }
670 });
671
672 tasks.add(new InitializationTask(tr("Initializing map styles")) {
673
674 @Override
[8497]675 public void initialize() {
[5134]676 MapPaintPreference.initialize();
677 }
678 });
679
[6779]680 tasks.add(new InitializationTask(tr("Loading imagery preferences")) {
[5134]681
682 @Override
[8497]683 public void initialize() {
[5134]684 ImageryPreference.initialize();
685 }
686 });
687
688 try {
[8734]689 final ExecutorService service = Executors.newFixedThreadPool(
690 Runtime.getRuntime().availableProcessors(), Utils.newThreadFactory("main-init-%d", Thread.NORM_PRIORITY));
691 for (Future<Void> i : service.invokeAll(tasks)) {
[5195]692 i.get();
693 }
[8738]694 service.shutdown();
[10212]695 } catch (InterruptedException | ExecutionException ex) {
[5134]696 throw new RuntimeException(ex);
[4718]697 }
[3669]698
[4489]699 // hooks for the jmapviewer component
[10601]700 FeatureAdapter.registerBrowserAdapter(OpenBrowser::displayUrl);
[4489]701 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
[10601]702 FeatureAdapter.registerLoggingAdapter(name -> {
[7802]703 Logger logger = Logger.getAnonymousLogger();
704 logger.setUseParentHandlers(false);
705 logger.setLevel(Level.ALL);
706 if (logger.getHandlers().length == 0) {
707 logger.addHandler(new Handler() {
708 @Override
709 public void publish(LogRecord record) {
710 String msg = MessageFormat.format(record.getMessage(), record.getParameters());
711 if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
712 Main.error(msg);
713 } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
714 Main.warn(msg);
715 } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
716 Main.info(msg);
717 } else if (record.getLevel().intValue() >= Level.FINE.intValue()) {
718 Main.debug(msg);
719 } else {
720 Main.trace(msg);
721 }
722 }
[4489]723
[7802]724 @Override
725 public void flush() {
[9989]726 // Do nothing
[7802]727 }
728
729 @Override
[8291]730 public void close() {
[9989]731 // Do nothing
[7802]732 }
733 });
734 }
735 return logger;
[10601]736 });
[7802]737
[8497]738 new InitializationTask(tr("Updating user interface")) {
[4681]739
[8497]740 @Override
741 public void initialize() {
742 toolbar.refreshToolbarControl();
743 toolbar.control.updateUI();
744 contentPanePrivate.updateUI();
745 }
746 }.call();
[1104]747 }
[626]748
[10340]749 /**
750 * Called once at startup to initialize the main window content.
751 * Should set {@link #menu}
752 */
753 protected void initializeMainWindow() {
754 // can be implementd by subclasses
755 }
756
[9087]757 private abstract static class InitializationTask implements Callable<Void> {
[6779]758
759 private final String name;
760
761 protected InitializationTask(String name) {
762 this.name = name;
763 }
764
[8497]765 public abstract void initialize();
[6779]766
767 @Override
[8497]768 public Void call() {
769 Object status = null;
[6779]770 if (initListener != null) {
[8497]771 status = initListener.updateStatus(name);
[6779]772 }
773 initialize();
[8497]774 if (initListener != null) {
775 initListener.finish(status);
[6852]776 }
[6779]777 return null;
778 }
779 }
780
[1104]781 /**
[10271]782 * Returns the main layer manager that is used by the map view.
783 * @return The layer manager. The value returned will never change.
[10279]784 * @since 10279
[10271]785 */
[10279]786 public static MainLayerManager getLayerManager() {
[10271]787 return layerManager;
788 }
789
790 /**
[7816]791 * Add a new layer to the map.
[7894]792 *
[7816]793 * If no map exists, create one.
[10432]794 * <p>
795 * To be removed end of 2016
[7894]796 *
[7816]797 * @param layer the layer
[7894]798 *
[7817]799 * @see #addLayer(Layer, ProjectionBounds)
800 * @see #addLayer(Layer, ViewportData)
[10432]801 * @deprecated You can add the layer to the layer manager: {@link #getLayerManager()}
[1104]802 */
[10432]803 @Deprecated
[7816]804 public final void addLayer(final Layer layer) {
[10432]805 addLayer(layer, (ViewportData) null);
[7816]806 }
807
808 /**
809 * Add a new layer to the map.
[7894]810 *
[7816]811 * If no map exists, create one.
[7894]812 *
[7816]813 * @param layer the layer
[7817]814 * @param bounds the bounds of the layer (target zoom area); can be null, then
815 * the viewport isn't changed
[7816]816 */
[10400]817 public final void addLayer(Layer layer, ProjectionBounds bounds) {
[7817]818 addLayer(layer, bounds == null ? null : new ViewportData(bounds));
[7816]819 }
820
821 /**
822 * Add a new layer to the map.
[7894]823 *
[7816]824 * If no map exists, create one.
[7894]825 *
[7816]826 * @param layer the layer
[10395]827 * @param viewport the viewport to zoom to; can be null, then the viewport isn't changed
[7816]828 */
[10400]829 public final void addLayer(Layer layer, ViewportData viewport) {
[10271]830 getLayerManager().addLayer(layer);
[10432]831 if (viewport != null && Main.map.mapView != null) {
832 // MapView may be null in headless mode here.
[10394]833 Main.map.mapView.scheduleZoomTo(viewport);
[5670]834 }
[1104]835 }
[1814]836
[10400]837 /**
838 * Creates the map frame. Call only in EDT Thread.
[10432]839 * <p>
840 * To be removed any time
[10400]841 * @param firstLayer The first layer that was added.
842 * @param viewportData The initial viewport. Can be <code>null</code> to be automatically computed.
[10432]843 * @deprecated Not supported. MainPanel does this automatically.
[10400]844 */
[10432]845 @Deprecated
[5670]846 public synchronized void createMapFrame(Layer firstLayer, ViewportData viewportData) {
[10400]847 GuiHelper.assertCallFromEdt();
[10432]848 Main.error("createMapFrame() not supported any more.");
[5670]849 }
850
[1104]851 /**
[5357]852 * Replies <code>true</code> if there is an edit layer
[10432]853 * <p>
854 * To be removed end of 2016
[1811]855 *
[5357]856 * @return <code>true</code> if there is an edit layer
[10432]857 * @deprecated You can get the edit layer using the layer manager and then check if it is not null: {@link #getLayerManager()}
[1104]858 */
[10432]859 @Deprecated
[1825]860 public boolean hasEditLayer() {
[3071]861 if (getEditLayer() == null) return false;
[1814]862 return true;
863 }
864
865 /**
866 * Replies the current edit layer
[10432]867 * <p>
868 * To be removed end of 2016
[2224]869 *
[5357]870 * @return the current edit layer. <code>null</code>, if no current edit layer exists
[10432]871 * @deprecated You can get the edit layer using the layer manager: {@link #getLayerManager()}
[1814]872 */
[10432]873 @Deprecated
[1814]874 public OsmDataLayer getEditLayer() {
[10271]875 return getLayerManager().getEditLayer();
[1104]876 }
[626]877
[1104]878 /**
[1814]879 * Replies the current data set.
[10432]880 * <p>
881 * To be removed end of 2016
[1811]882 *
[5357]883 * @return the current data set. <code>null</code>, if no current data set exists
[10432]884 * @deprecated You can get the data set using the layer manager: {@link #getLayerManager()}
[1750]885 */
[10432]886 @Deprecated
[1814]887 public DataSet getCurrentDataSet() {
[10432]888 return getLayerManager().getEditDataSet();
[1750]889 }
[6852]890
[6546]891 /**
892 * Replies the current selected primitives, from a end-user point of view.
893 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
894 * Indeed, if the user is currently in drawing mode, only the way currently being drawn is returned,
895 * see {@link DrawAction#getInProgressSelection()}.
[6852]896 *
[6546]897 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
898 * @since 6546
899 */
900 public Collection<OsmPrimitive> getInProgressSelection() {
901 if (map != null && map.mapMode instanceof DrawAction) {
902 return ((DrawAction) map.mapMode).getInProgressSelection();
903 } else {
904 DataSet ds = getCurrentDataSet();
905 if (ds == null) return null;
906 return ds.getSelected();
907 }
908 }
[1750]909
910 /**
[3071]911 * Returns the currently active layer
[10432]912 * <p>
913 * To be removed end of 2016
[3071]914 *
[5357]915 * @return the currently active layer. <code>null</code>, if currently no active layer exists
[10432]916 * @deprecated You can get the layer using the layer manager: {@link #getLayerManager()}
[3071]917 */
[10432]918 @Deprecated
[3071]919 public Layer getActiveLayer() {
[10271]920 return getLayerManager().getActiveLayer();
[3071]921 }
922
[4869]923 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
[3252]924
[4897]925 public static void redirectToMainContentPane(JComponent source) {
926 RedirectInputMap.redirect(source, contentPanePrivate);
927 }
[626]928
[5278]929 public static void registerActionShortcut(JosmAction action) {
930 registerActionShortcut(action, action.getShortcut());
931 }
932
[3252]933 public static void registerActionShortcut(Action action, Shortcut shortcut) {
[5002]934 KeyStroke keyStroke = shortcut.getKeyStroke();
[3252]935 if (keyStroke == null)
936 return;
937
938 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
939 Object existing = inputMap.get(keyStroke);
940 if (existing != null && !existing.equals(action)) {
[6248]941 info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
[3252]942 }
943 inputMap.put(keyStroke, action);
944
945 contentPanePrivate.getActionMap().put(action, action);
946 }
947
[5382]948 public static void unregisterShortcut(Shortcut shortcut) {
[3327]949 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
[3252]950 }
951
[3444]952 public static void unregisterActionShortcut(JosmAction action) {
953 unregisterActionShortcut(action, action.getShortcut());
954 }
955
956 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
[5382]957 unregisterShortcut(shortcut);
[3444]958 contentPanePrivate.getActionMap().remove(action);
959 }
[6070]960
[5696]961 /**
962 * Replies the registered action for the given shortcut
963 * @param shortcut The shortcut to look for
964 * @return the registered action for the given shortcut
965 * @since 5696
966 */
967 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
968 KeyStroke keyStroke = shortcut.getKeyStroke();
969 if (keyStroke == null)
970 return null;
971 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
972 if (action instanceof Action)
973 return (Action) action;
974 return null;
975 }
[3444]976
[1104]977 ///////////////////////////////////////////////////////////////////////////
978 // Implementation part
979 ///////////////////////////////////////////////////////////////////////////
[626]980
[5829]981 /**
[6070]982 * Global panel.
[5829]983 */
[10432]984 public static final JPanel panel = mainPanel;
[626]985
[10601]986 private final CommandQueueListener redoUndoListener = (queueSize, redoSize) -> {
[1104]987 menu.undo.setEnabled(queueSize > 0);
988 menu.redo.setEnabled(redoSize > 0);
[10601]989 };
[1722]990
[1104]991 /**
992 * Should be called before the main constructor to setup some parameter stuff
993 * @param args The parsed argument list.
994 */
[5279]995 public static void preConstructorInit(Map<Option, Collection<String>> args) {
[2272]996 ProjectionPreference.setProjection();
[626]997
[10212]998 String defaultlaf = platform.getDefaultStyle();
999 String laf = Main.pref.get("laf", defaultlaf);
[1104]1000 try {
[10212]1001 UIManager.setLookAndFeel(laf);
1002 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
1003 // Try to find look and feel in plugin classloaders
[10463]1004 Main.trace(e);
[10212]1005 Class<?> klass = null;
1006 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
1007 try {
1008 klass = cl.loadClass(laf);
1009 break;
1010 } catch (ClassNotFoundException ex) {
[10463]1011 Main.trace(ex);
[7634]1012 }
[10212]1013 }
1014 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
1015 try {
1016 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
1017 } catch (ReflectiveOperationException ex) {
[10463]1018 warn(ex, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage());
[10212]1019 } catch (UnsupportedLookAndFeelException ex) {
1020 info("Look and Feel not supported: " + laf);
[7634]1021 Main.pref.put("laf", defaultlaf);
[10463]1022 trace(ex);
[7634]1023 }
[10212]1024 } else {
1025 info("Look and Feel not found: " + laf);
[2708]1026 Main.pref.put("laf", defaultlaf);
[1188]1027 }
[10212]1028 } catch (UnsupportedLookAndFeelException e) {
1029 info("Look and Feel not supported: " + laf);
1030 Main.pref.put("laf", defaultlaf);
[10463]1031 trace(e);
[10212]1032 } catch (InstantiationException | IllegalAccessException e) {
[6642]1033 error(e);
[1104]1034 }
[10212]1035 toolbar = new ToolbarPreferences();
1036 contentPanePrivate.updateUI();
1037 panel.updateUI();
1038
[1104]1039 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
1040 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
1041 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
1042 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
[9222]1043 // Ensures caret color is the same than text foreground color, see #12257
[10580]1044 // See http://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
[9222]1045 for (String p : Arrays.asList(
1046 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
1047 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
1048 }
[626]1049
[3433]1050 I18n.translateJavaInternalMessages();
[3378]1051
[1990]1052 // init default coordinate format
1053 //
1054 try {
1055 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
1056 } catch (IllegalArgumentException iae) {
[10463]1057 Main.trace(iae);
[1990]1058 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
1059 }
[1104]1060 }
[626]1061
[5829]1062 protected static void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
[5279]1063 if (args.containsKey(Option.DOWNLOAD)) {
[7005]1064 List<File> fileList = new ArrayList<>();
[5279]1065 for (String s : args.get(Option.DOWNLOAD)) {
[8809]1066 DownloadParamType.paramType(s).download(s, fileList);
[1750]1067 }
[8510]1068 if (!fileList.isEmpty()) {
[3924]1069 OpenFileAction.openFiles(fileList, true);
[2798]1070 }
[1750]1071 }
[5279]1072 if (args.containsKey(Option.DOWNLOADGPS)) {
1073 for (String s : args.get(Option.DOWNLOADGPS)) {
[8809]1074 DownloadParamType.paramType(s).downloadGps(s);
[1750]1075 }
1076 }
[5279]1077 if (args.containsKey(Option.SELECTION)) {
1078 for (String s : args.get(Option.SELECTION)) {
[3317]1079 SearchAction.search(s, SearchAction.SearchMode.add);
[1750]1080 }
1081 }
[1104]1082 }
[626]1083
[5519]1084 /**
[8509]1085 * Asks user to perform "save layer" operations (save on disk and/or upload data to server) for all
1086 * {@link AbstractModifiableLayer} before JOSM exits.
1087 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations.
1088 * {@code false} if the user cancels.
[5519]1089 * @since 2025
1090 */
[2025]1091 public static boolean saveUnsavedModifications() {
[6336]1092 if (!isDisplayingMapView()) return true;
[10271]1093 return saveUnsavedModifications(getLayerManager().getLayersOfType(AbstractModifiableLayer.class), true);
[5519]1094 }
1095
1096 /**
[7358]1097 * Asks user to perform "save layer" operations (save on disk and/or upload data to server) before data layers deletion.
[6070]1098 *
[7402]1099 * @param selectedLayers The layers to check. Only instances of {@link AbstractModifiableLayer} are considered.
[5519]1100 * @param exit {@code true} if JOSM is exiting, {@code false} otherwise.
[8509]1101 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations.
1102 * {@code false} if the user cancels.
[5519]1103 * @since 5519
1104 */
[6565]1105 public static boolean saveUnsavedModifications(Iterable<? extends Layer> selectedLayers, boolean exit) {
[5519]1106 SaveLayersDialog dialog = new SaveLayersDialog(parent);
[7402]1107 List<AbstractModifiableLayer> layersWithUnmodifiedChanges = new ArrayList<>();
[5519]1108 for (Layer l: selectedLayers) {
[7402]1109 if (!(l instanceof AbstractModifiableLayer)) {
[5519]1110 continue;
[2025]1111 }
[8510]1112 AbstractModifiableLayer odl = (AbstractModifiableLayer) l;
[9751]1113 if (odl.isModified() &&
1114 ((!odl.isSavable() && !odl.isUploadable()) ||
1115 odl.requiresSaveToFile() ||
1116 (odl.requiresUploadToServer() && !odl.isUploadDiscouraged()))) {
[5519]1117 layersWithUnmodifiedChanges.add(odl);
1118 }
[2025]1119 }
[5519]1120 if (exit) {
1121 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
1122 } else {
1123 dialog.prepareForSavingAndUpdatingLayersBeforeDelete();
1124 }
[2025]1125 if (!layersWithUnmodifiedChanges.isEmpty()) {
1126 dialog.getModel().populate(layersWithUnmodifiedChanges);
1127 dialog.setVisible(true);
1128 switch(dialog.getUserAction()) {
[2485]1129 case PROCEED: return true;
[7801]1130 case CANCEL:
[2485]1131 default: return false;
[2025]1132 }
1133 }
[2274]1134
[2025]1135 return true;
1136 }
1137
[5829]1138 /**
[8412]1139 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
1140 * If there are some unsaved data layers, asks first for user confirmation.
[6342]1141 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
1142 * @param exitCode The return code
[5829]1143 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
1144 * @since 3378
1145 */
[6125]1146 public static boolean exitJosm(boolean exit, int exitCode) {
[3378]1147 if (Main.saveUnsavedModifications()) {
[10387]1148 if (Main.main != null) {
1149 Main.main.shutdown();
1150 }
[8412]1151
[3378]1152 if (exit) {
[6125]1153 System.exit(exitCode);
[5829]1154 }
1155 return true;
1156 }
1157 return false;
[3378]1158 }
1159
[10340]1160 protected void shutdown() {
1161 worker.shutdown();
1162 ImageProvider.shutdown(false);
1163 JCSCacheManager.shutdown();
1164 if (map != null) {
1165 map.rememberToggleDialogWidth();
1166 }
1167 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
[10432]1168 getLayerManager().resetState();
[10340]1169 try {
1170 pref.saveDefaults();
1171 } catch (IOException ex) {
[10420]1172 Main.warn(ex, tr("Failed to save default preferences."));
[10340]1173 }
1174 worker.shutdownNow();
1175 ImageProvider.shutdown(true);
1176 }
1177
[2798]1178 /**
1179 * The type of a command line parameter, to be used in switch statements.
[5195]1180 * @see #paramType
[2798]1181 */
[8809]1182 enum DownloadParamType {
1183 httpUrl {
1184 @Override
1185 void download(String s, Collection<File> fileList) {
1186 new OpenLocationAction().openUrl(false, s);
1187 }
[2798]1188
[8809]1189 @Override
1190 void downloadGps(String s) {
1191 final Bounds b = OsmUrlToBounds.parse(s);
1192 if (b == null) {
1193 JOptionPane.showMessageDialog(
1194 Main.parent,
1195 tr("Ignoring malformed URL: \"{0}\"", s),
1196 tr("Warning"),
1197 JOptionPane.WARNING_MESSAGE
1198 );
1199 return;
1200 }
1201 downloadFromParamBounds(true, b);
1202 }
1203 }, fileUrl {
1204 @Override
1205 void download(String s, Collection<File> fileList) {
1206 File f = null;
1207 try {
1208 f = new File(new URI(s));
1209 } catch (URISyntaxException e) {
[10463]1210 Main.warn(e);
[8809]1211 JOptionPane.showMessageDialog(
1212 Main.parent,
1213 tr("Ignoring malformed file URL: \"{0}\"", s),
1214 tr("Warning"),
1215 JOptionPane.WARNING_MESSAGE
1216 );
1217 }
1218 if (f != null) {
1219 fileList.add(f);
1220 }
1221 }
1222 }, bounds {
[2798]1223
[8809]1224 /**
1225 * Download area specified on the command line as bounds string.
1226 * @param rawGps Flag to download raw GPS tracks
1227 * @param s The bounds parameter
1228 */
1229 private void downloadFromParamBounds(final boolean rawGps, String s) {
1230 final StringTokenizer st = new StringTokenizer(s, ",");
1231 if (st.countTokens() == 4) {
1232 Bounds b = new Bounds(
1233 new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())),
1234 new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))
1235 );
1236 Main.downloadFromParamBounds(rawGps, b);
1237 }
1238 }
1239
1240 @Override
1241 void download(String param, Collection<File> fileList) {
1242 downloadFromParamBounds(false, param);
1243 }
1244
1245 @Override
1246 void downloadGps(String param) {
1247 downloadFromParamBounds(true, param);
1248 }
1249 }, fileName {
1250 @Override
1251 void download(String s, Collection<File> fileList) {
1252 fileList.add(new File(s));
1253 }
1254 };
1255
1256 /**
1257 * Performs the download
1258 * @param param represents the object to be downloaded
1259 * @param fileList files which shall be opened, should be added to this collection
1260 */
1261 abstract void download(String param, Collection<File> fileList);
1262
1263 /**
1264 * Performs the GPS download
1265 * @param param represents the object to be downloaded
1266 */
1267 void downloadGps(String param) {
[2798]1268 JOptionPane.showMessageDialog(
1269 Main.parent,
[8809]1270 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
[2798]1271 tr("Warning"),
1272 JOptionPane.WARNING_MESSAGE
[8809]1273 );
[1104]1274 }
[626]1275
[8809]1276 /**
1277 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
1278 *
1279 * @param s A parameter string
1280 * @return The guessed parameter type
1281 */
1282 static DownloadParamType paramType(String s) {
1283 if (s.startsWith("http:") || s.startsWith("https:")) return DownloadParamType.httpUrl;
1284 if (s.startsWith("file:")) return DownloadParamType.fileUrl;
1285 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
1286 if (s.matches(coorPattern + "(," + coorPattern + "){3}")) return DownloadParamType.bounds;
1287 // everything else must be a file name
1288 return DownloadParamType.fileName;
[1104]1289 }
1290 }
[1023]1291
[2798]1292 /**
1293 * Download area specified as Bounds value.
1294 * @param rawGps Flag to download raw GPS tracks
1295 * @param b The bounds value
1296 */
1297 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
1298 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1299 // asynchronously launch the download task ...
1300 Future<?> future = task.download(true, b, null);
1301 // ... and the continuation when the download is finished (this will wait for the download to finish)
1302 Main.worker.execute(new PostDownloadHandler(task, future));
1303 }
1304
[5829]1305 /**
1306 * Identifies the current operating system family and initializes the platform hook accordingly.
1307 * @since 1849
1308 */
[1849]1309 public static void determinePlatformHook() {
[1104]1310 String os = System.getProperty("os.name");
1311 if (os == null) {
[6248]1312 warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
[1104]1313 platform = new PlatformHookUnixoid();
[8404]1314 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("windows")) {
[1104]1315 platform = new PlatformHookWindows();
[6990]1316 } else if ("Linux".equals(os) || "Solaris".equals(os) ||
1317 "SunOS".equals(os) || "AIX".equals(os) ||
1318 "FreeBSD".equals(os) || "NetBSD".equals(os) || "OpenBSD".equals(os)) {
[1104]1319 platform = new PlatformHookUnixoid();
[8404]1320 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("mac os x")) {
[1104]1321 platform = new PlatformHookOsx();
1322 } else {
[6248]1323 warn("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
[1104]1324 platform = new PlatformHookUnixoid();
1325 }
1326 }
[1023]1327
[5829]1328 /**
[10580]1329 * Checks that JOSM is at least running with Java 8.
[7001]1330 * @since 7001
[5829]1331 */
[7001]1332 public static void checkJavaVersion() {
[3815]1333 String version = System.getProperty("java.version");
1334 if (version != null) {
[10580]1335 if (version.matches("^(1\\.)?[89].*"))
[3815]1336 return;
[10580]1337 if (version.matches("^(1\\.)?[567].*")) {
[6901]1338 JMultilineLabel ho = new JMultilineLabel("<html>"+
[7001]1339 tr("<h2>JOSM requires Java version {0}.</h2>"+
1340 "Detected Java version: {1}.<br>"+
[3815]1341 "You can <ul><li>update your Java (JRE) or</li>"+
[7001]1342 "<li>use an earlier (Java {2} compatible) version of JOSM.</li></ul>"+
[10580]1343 "More Info:", "8", version, "7")+"</html>");
[6143]1344 JTextArea link = new JTextArea(HelpUtil.getWikiBaseHelpUrl()+"/Help/SystemRequirements");
[3815]1345 link.setEditable(false);
1346 link.setBackground(panel.getBackground());
1347 JPanel panel = new JPanel(new GridBagLayout());
1348 GridBagConstraints gbc = new GridBagConstraints();
1349 gbc.gridwidth = GridBagConstraints.REMAINDER;
1350 gbc.anchor = GridBagConstraints.WEST;
1351 gbc.weightx = 1.0;
1352 panel.add(ho, gbc);
1353 panel.add(link, gbc);
[10001]1354 final String exitStr = tr("Exit JOSM");
1355 final String continueStr = tr("Continue, try anyway");
[7083]1356 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION,
[10001]1357 JOptionPane.ERROR_MESSAGE, null, new String[] {exitStr, continueStr}, exitStr);
[3815]1358 if (ret == 0) {
1359 System.exit(0);
1360 }
1361 return;
1362 }
1363 }
[6248]1364 error("Could not recognize Java Version: "+version);
[3815]1365 }
[4126]1366
1367 /* ----------------------------------------------------------------------------------------- */
1368 /* projection handling - Main is a registry for a single, global projection instance */
1369 /* */
1370 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
1371 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
1372 /* ----------------------------------------------------------------------------------------- */
1373 /**
1374 * The projection method used.
[4897]1375 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
1376 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
[4126]1377 */
[8126]1378 private static volatile Projection proj;
[4126]1379
1380 /**
1381 * Replies the current projection.
[4489]1382 *
[5357]1383 * @return the currently active projection
[4126]1384 */
1385 public static Projection getProjection() {
1386 return proj;
1387 }
1388
1389 /**
1390 * Sets the current projection
[4489]1391 *
[4126]1392 * @param p the projection
1393 */
1394 public static void setProjection(Projection p) {
1395 CheckParameterUtil.ensureParameterNotNull(p);
1396 Projection oldValue = proj;
[5460]1397 Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
[4126]1398 proj = p;
[5234]1399 fireProjectionChanged(oldValue, proj, b);
[4126]1400 }
1401
1402 /*
1403 * Keep WeakReferences to the listeners. This relieves clients from the burden of
1404 * explicitly removing the listeners and allows us to transparently register every
1405 * created dataset as projection change listener.
1406 */
[7005]1407 private static final List<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<>();
[4126]1408
[5234]1409 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
[4126]1410 if (newValue == null ^ oldValue == null
[7083]1411 || (newValue != null && oldValue != null && !Objects.equals(newValue.toCode(), oldValue.toCode()))) {
[10486]1412 if (Main.map != null) {
1413 // This needs to be called first
1414 Main.map.mapView.fixProjection();
1415 }
[8510]1416 synchronized (Main.class) {
[4126]1417 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
[8510]1418 while (it.hasNext()) {
[4126]1419 WeakReference<ProjectionChangeListener> wr = it.next();
[4724]1420 ProjectionChangeListener listener = wr.get();
1421 if (listener == null) {
[4126]1422 it.remove();
1423 continue;
1424 }
[4724]1425 listener.projectionChanged(oldValue, newValue);
[4126]1426 }
1427 }
[5234]1428 if (newValue != null && oldBounds != null) {
1429 Main.map.mapView.zoomTo(oldBounds);
[4126]1430 }
1431 /* TODO - remove layers with fixed projection */
1432 }
1433 }
1434
1435 /**
[5538]1436 * Register a projection change listener.
[4489]1437 *
[5357]1438 * @param listener the listener. Ignored if <code>null</code>.
[4126]1439 */
1440 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
1441 if (listener == null) return;
1442 synchronized (Main.class) {
1443 for (WeakReference<ProjectionChangeListener> wr : listeners) {
1444 // already registered ? => abort
1445 if (wr.get() == listener) return;
1446 }
[7005]1447 listeners.add(new WeakReference<>(listener));
[4126]1448 }
1449 }
1450
1451 /**
[5538]1452 * Removes a projection change listener.
[4489]1453 *
[5357]1454 * @param listener the listener. Ignored if <code>null</code>.
[4126]1455 */
1456 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
1457 if (listener == null) return;
[8510]1458 synchronized (Main.class) {
[4126]1459 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
[8510]1460 while (it.hasNext()) {
[4126]1461 WeakReference<ProjectionChangeListener> wr = it.next();
[5538]1462 // remove the listener - and any other listener which got garbage
[4126]1463 // collected in the meantime
1464 if (wr.get() == null || wr.get() == listener) {
1465 it.remove();
1466 }
1467 }
1468 }
1469 }
[5538]1470
1471 /**
1472 * Listener for window switch events.
[6070]1473 *
[5538]1474 * These are events, when the user activates a window of another application
1475 * or comes back to JOSM. Window switches from one JOSM window to another
1476 * are not reported.
1477 */
[8512]1478 public interface WindowSwitchListener {
[5538]1479 /**
1480 * Called when the user activates a window of another application.
1481 */
1482 void toOtherApplication();
[9059]1483
[5538]1484 /**
[9059]1485 * Called when the user comes from a window of another application back to JOSM.
[5538]1486 */
1487 void fromOtherApplication();
1488 }
1489
[7005]1490 private static final List<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<>();
[5538]1491
1492 /**
1493 * Register a window switch listener.
1494 *
1495 * @param listener the listener. Ignored if <code>null</code>.
1496 */
1497 public static void addWindowSwitchListener(WindowSwitchListener listener) {
1498 if (listener == null) return;
1499 synchronized (Main.class) {
1500 for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
1501 // already registered ? => abort
1502 if (wr.get() == listener) return;
1503 }
1504 boolean wasEmpty = windowSwitchListeners.isEmpty();
[7005]1505 windowSwitchListeners.add(new WeakReference<>(listener));
[5538]1506 if (wasEmpty) {
1507 // The following call will have no effect, when there is no window
1508 // at the time. Therefore, MasterWindowListener.setup() will also be
1509 // called, as soon as the main window is shown.
1510 MasterWindowListener.setup();
1511 }
1512 }
1513 }
1514
1515 /**
1516 * Removes a window switch listener.
1517 *
1518 * @param listener the listener. Ignored if <code>null</code>.
1519 */
1520 public static void removeWindowSwitchListener(WindowSwitchListener listener) {
1521 if (listener == null) return;
[8510]1522 synchronized (Main.class) {
[5538]1523 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
[8510]1524 while (it.hasNext()) {
[5538]1525 WeakReference<WindowSwitchListener> wr = it.next();
1526 // remove the listener - and any other listener which got garbage
1527 // collected in the meantime
1528 if (wr.get() == null || wr.get() == listener) {
1529 it.remove();
1530 }
1531 }
1532 if (windowSwitchListeners.isEmpty()) {
1533 MasterWindowListener.teardown();
1534 }
1535 }
1536 }
1537
1538 /**
1539 * WindowListener, that is registered on all Windows of the application.
1540 *
1541 * Its purpose is to notify WindowSwitchListeners, that the user switches to
1542 * another application, e.g. a browser, or back to JOSM.
1543 *
1544 * When changing from JOSM to another application and back (e.g. two times
1545 * alt+tab), the active Window within JOSM may be different.
1546 * Therefore, we need to register listeners to <strong>all</strong> (visible)
1547 * Windows in JOSM, and it does not suffice to monitor the one that was
1548 * deactivated last.
1549 *
1550 * This class is only "active" on demand, i.e. when there is at least one
1551 * WindowSwitchListener registered.
1552 */
1553 protected static class MasterWindowListener extends WindowAdapter {
1554
1555 private static MasterWindowListener INSTANCE;
1556
[8126]1557 public static synchronized MasterWindowListener getInstance() {
[5538]1558 if (INSTANCE == null) {
1559 INSTANCE = new MasterWindowListener();
1560 }
1561 return INSTANCE;
1562 }
1563
1564 /**
1565 * Register listeners to all non-hidden windows.
1566 *
1567 * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
1568 */
1569 public static void setup() {
1570 if (!windowSwitchListeners.isEmpty()) {
1571 for (Window w : Window.getWindows()) {
1572 if (w.isShowing()) {
1573 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1574 w.addWindowListener(getInstance());
1575 }
1576 }
1577 }
1578 }
1579 }
1580
1581 /**
1582 * Unregister all listeners.
1583 */
1584 public static void teardown() {
1585 for (Window w : Window.getWindows()) {
1586 w.removeWindowListener(getInstance());
1587 }
1588 }
1589
1590 @Override
1591 public void windowActivated(WindowEvent e) {
1592 if (e.getOppositeWindow() == null) { // we come from a window of a different application
1593 // fire WindowSwitchListeners
1594 synchronized (Main.class) {
1595 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
[8510]1596 while (it.hasNext()) {
[5538]1597 WeakReference<WindowSwitchListener> wr = it.next();
1598 WindowSwitchListener listener = wr.get();
1599 if (listener == null) {
1600 it.remove();
1601 continue;
1602 }
1603 listener.fromOtherApplication();
1604 }
1605 }
1606 }
1607 }
1608
1609 @Override
1610 public void windowDeactivated(WindowEvent e) {
1611 // set up windows that have been created in the meantime
1612 for (Window w : Window.getWindows()) {
1613 if (!w.isShowing()) {
1614 w.removeWindowListener(getInstance());
1615 } else {
1616 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1617 w.addWindowListener(getInstance());
1618 }
1619 }
1620 }
1621 if (e.getOppositeWindow() == null) { // we go to a window of a different application
1622 // fire WindowSwitchListeners
1623 synchronized (Main.class) {
1624 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
[8510]1625 while (it.hasNext()) {
[5538]1626 WeakReference<WindowSwitchListener> wr = it.next();
1627 WindowSwitchListener listener = wr.get();
1628 if (listener == null) {
1629 it.remove();
1630 continue;
1631 }
1632 listener.toOtherApplication();
1633 }
1634 }
1635 }
1636 }
1637 }
1638
[5957]1639 /**
1640 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1641 * @param listener The MapFrameListener
[8020]1642 * @param fireWhenMapViewPresent If true, will fire an initial mapFrameInitialized event
1643 * when the MapFrame is present. Otherwise will only fire when the MapFrame is created
1644 * or destroyed.
[5957]1645 * @return {@code true} if the listeners collection changed as a result of the call
[8020]1646 */
1647 public static boolean addMapFrameListener(MapFrameListener listener, boolean fireWhenMapViewPresent) {
[10432]1648 if (fireWhenMapViewPresent) {
1649 return mainPanel.addAndFireMapFrameListener(listener);
1650 } else {
1651 return mainPanel.addMapFrameListener(listener);
[8020]1652 }
1653 }
1654
1655 /**
1656 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1657 * @param listener The MapFrameListener
1658 * @return {@code true} if the listeners collection changed as a result of the call
[5957]1659 * @since 5957
1660 */
1661 public static boolean addMapFrameListener(MapFrameListener listener) {
[10432]1662 return mainPanel.addMapFrameListener(listener);
[5957]1663 }
1664
1665 /**
1666 * Unregisters the given {@code MapFrameListener} from MapFrame changes
1667 * @param listener The MapFrameListener
1668 * @return {@code true} if the listeners collection changed as a result of the call
1669 * @since 5957
1670 */
1671 public static boolean removeMapFrameListener(MapFrameListener listener) {
[10432]1672 return mainPanel.removeMapFrameListener(listener);
[5957]1673 }
[6642]1674
1675 /**
1676 * Adds a new network error that occur to give a hint about broken Internet connection.
1677 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
[6852]1678 *
[6642]1679 * @param url The accessed URL that caused the error
1680 * @param t The network error
1681 * @return The previous error associated to the given resource, if any. Can be {@code null}
[6643]1682 * @since 6642
[6642]1683 */
1684 public static Throwable addNetworkError(URL url, Throwable t) {
1685 if (url != null && t != null) {
1686 Throwable old = addNetworkError(url.toExternalForm(), t);
1687 if (old != null) {
1688 Main.warn("Already here "+old);
1689 }
1690 return old;
1691 }
1692 return null;
1693 }
1694
1695 /**
1696 * Adds a new network error that occur to give a hint about broken Internet connection.
1697 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
[6852]1698 *
[6642]1699 * @param url The accessed URL that caused the error
1700 * @param t The network error
1701 * @return The previous error associated to the given resource, if any. Can be {@code null}
[6643]1702 * @since 6642
[6642]1703 */
1704 public static Throwable addNetworkError(String url, Throwable t) {
1705 if (url != null && t != null) {
[6806]1706 return NETWORK_ERRORS.put(url, t);
[6642]1707 }
1708 return null;
1709 }
1710
1711 /**
1712 * Returns the network errors that occured until now.
1713 * @return the network errors that occured until now, indexed by URL
1714 * @since 6639
1715 */
1716 public static Map<String, Throwable> getNetworkErrors() {
[7005]1717 return new HashMap<>(NETWORK_ERRORS);
[6642]1718 }
[6897]1719
1720 /**
[8356]1721 * Returns the command-line arguments used to run the application.
1722 * @return the command-line arguments used to run the application
1723 * @since 8356
1724 */
1725 public static List<String> getCommandLineArgs() {
1726 return Collections.unmodifiableList(COMMAND_LINE_ARGS);
1727 }
1728
1729 /**
[6897]1730 * Returns the JOSM website URL.
1731 * @return the josm website URL
1732 * @since 6897
1733 */
1734 public static String getJOSMWebsite() {
[6920]1735 if (Main.pref != null)
[6897]1736 return Main.pref.get("josm.url", JOSM_WEBSITE);
1737 return JOSM_WEBSITE;
1738 }
1739
1740 /**
1741 * Returns the JOSM XML URL.
1742 * @return the josm XML URL
1743 * @since 6897
1744 */
1745 public static String getXMLBase() {
[6920]1746 // Always return HTTP (issues reported with HTTPS)
[6900]1747 return "http://josm.openstreetmap.de";
[6897]1748 }
1749
1750 /**
1751 * Returns the OSM website URL.
1752 * @return the OSM website URL
1753 * @since 6897
1754 */
1755 public static String getOSMWebsite() {
[6920]1756 if (Main.pref != null)
[6897]1757 return Main.pref.get("osm.url", OSM_WEBSITE);
1758 return OSM_WEBSITE;
1759 }
[6957]1760
1761 /**
[7678]1762 * Replies the base URL for browsing information about a primitive.
1763 * @return the base URL, i.e. https://www.openstreetmap.org
1764 * @since 7678
1765 */
1766 public static String getBaseBrowseUrl() {
1767 if (Main.pref != null)
1768 return Main.pref.get("osm-browse.url", getOSMWebsite());
1769 return getOSMWebsite();
1770 }
1771
1772 /**
1773 * Replies the base URL for browsing information about a user.
1774 * @return the base URL, i.e. https://www.openstreetmap.org/user
1775 * @since 7678
1776 */
1777 public static String getBaseUserUrl() {
1778 if (Main.pref != null)
1779 return Main.pref.get("osm-user.url", getOSMWebsite() + "/user");
1780 return getOSMWebsite() + "/user";
1781 }
1782
1783 /**
[6957]1784 * Determines if we are currently running on OSX.
1785 * @return {@code true} if we are currently running on OSX
1786 * @since 6957
1787 */
1788 public static boolean isPlatformOsx() {
1789 return Main.platform instanceof PlatformHookOsx;
1790 }
[7335]1791
1792 /**
1793 * Determines if we are currently running on Windows.
1794 * @return {@code true} if we are currently running on Windows
1795 * @since 7335
1796 */
1797 public static boolean isPlatformWindows() {
1798 return Main.platform instanceof PlatformHookWindows;
1799 }
[7434]1800
1801 /**
1802 * Determines if the given online resource is currently offline.
1803 * @param r the online resource
1804 * @return {@code true} if {@code r} is offline and should not be accessed
1805 * @since 7434
1806 */
1807 public static boolean isOffline(OnlineResource r) {
1808 return OFFLINE_RESOURCES.contains(r) || OFFLINE_RESOURCES.contains(OnlineResource.ALL);
1809 }
1810
1811 /**
1812 * Sets the given online resource to offline state.
1813 * @param r the online resource
1814 * @return {@code true} if {@code r} was not already offline
1815 * @since 7434
1816 */
1817 public static boolean setOffline(OnlineResource r) {
1818 return OFFLINE_RESOURCES.add(r);
1819 }
1820
1821 /**
[8506]1822 * Sets the given online resource to online state.
1823 * @param r the online resource
1824 * @return {@code true} if {@code r} was offline
1825 * @since 8506
1826 */
1827 public static boolean setOnline(OnlineResource r) {
1828 return OFFLINE_RESOURCES.remove(r);
1829 }
1830
1831 /**
[7434]1832 * Replies the set of online resources currently offline.
1833 * @return the set of online resources currently offline
1834 * @since 7434
1835 */
1836 public static Set<OnlineResource> getOfflineResources() {
[10044]1837 return EnumSet.copyOf(OFFLINE_RESOURCES);
[7434]1838 }
[626]1839}
Note: See TracBrowser for help on using the repository browser.