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

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

sonar - fix some errors, mainly NPEs

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