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

Last change on this file since 6312 was 6311, checked in by Don-vip, 11 years ago

Avoid NPE when logging exception without message

  • Property svn:eol-style set to native
File size: 47.4 KB
RevLine 
[298]1// License: GPL. Copyright 2007 by Immanuel Scholz and others
[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;
[5481]20import java.text.MessageFormat;
[2025]21import java.util.ArrayList;
[5538]22import java.util.Arrays;
[301]23import java.util.Collection;
[4126]24import java.util.Iterator;
[2025]25import java.util.List;
[301]26import java.util.Map;
27import java.util.StringTokenizer;
[5134]28import java.util.concurrent.Callable;
[1465]29import java.util.concurrent.ExecutorService;
[5134]30import java.util.concurrent.Executors;
[2322]31import java.util.concurrent.Future;
[301]32
[3252]33import javax.swing.Action;
34import javax.swing.InputMap;
[301]35import javax.swing.JComponent;
[1356]36import javax.swing.JFrame;
[3815]37import javax.swing.JLabel;
[301]38import javax.swing.JOptionPane;
39import javax.swing.JPanel;
[3815]40import javax.swing.JTextArea;
[3252]41import javax.swing.KeyStroke;
[301]42import javax.swing.UIManager;
[6248]43import javax.swing.UnsupportedLookAndFeelException;
[301]44
[4489]45import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
[3444]46import org.openstreetmap.josm.actions.JosmAction;
[2047]47import org.openstreetmap.josm.actions.OpenFileAction;
[301]48import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
49import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
[2322]50import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
51import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
[301]52import org.openstreetmap.josm.actions.mapmode.MapMode;
53import org.openstreetmap.josm.actions.search.SearchAction;
54import org.openstreetmap.josm.data.Bounds;
55import org.openstreetmap.josm.data.Preferences;
56import org.openstreetmap.josm.data.UndoRedoHandler;
[1990]57import org.openstreetmap.josm.data.coor.CoordinateFormat;
[2327]58import org.openstreetmap.josm.data.coor.LatLon;
[301]59import org.openstreetmap.josm.data.osm.DataSet;
[2305]60import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy;
[301]61import org.openstreetmap.josm.data.projection.Projection;
[4126]62import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
[3669]63import org.openstreetmap.josm.data.validation.OsmValidator;
[301]64import org.openstreetmap.josm.gui.GettingStarted;
[5279]65import org.openstreetmap.josm.gui.MainApplication.Option;
[301]66import org.openstreetmap.josm.gui.MainMenu;
67import org.openstreetmap.josm.gui.MapFrame;
[5957]68import org.openstreetmap.josm.gui.MapFrameListener;
[3669]69import org.openstreetmap.josm.gui.MapView;
[5670]70import org.openstreetmap.josm.gui.NavigatableComponent.ViewportData;
[1895]71import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
[6143]72import org.openstreetmap.josm.gui.help.HelpUtil;
[2025]73import org.openstreetmap.josm.gui.io.SaveLayersDialog;
[301]74import org.openstreetmap.josm.gui.layer.Layer;
75import org.openstreetmap.josm.gui.layer.OsmDataLayer;
76import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
77import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
[4968]78import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
79import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
80import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
[5226]81import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
[4718]82import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
83import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
[4897]84import org.openstreetmap.josm.gui.util.RedirectInputMap;
[3934]85import org.openstreetmap.josm.io.OsmApi;
[4126]86import org.openstreetmap.josm.tools.CheckParameterUtil;
[3340]87import org.openstreetmap.josm.tools.I18n;
[301]88import org.openstreetmap.josm.tools.ImageProvider;
[4489]89import org.openstreetmap.josm.tools.OpenBrowser;
[1307]90import org.openstreetmap.josm.tools.OsmUrlToBounds;
[1023]91import org.openstreetmap.josm.tools.PlatformHook;
[1465]92import org.openstreetmap.josm.tools.PlatformHookOsx;
[1023]93import org.openstreetmap.josm.tools.PlatformHookUnixoid;
94import org.openstreetmap.josm.tools.PlatformHookWindows;
[1084]95import org.openstreetmap.josm.tools.Shortcut;
[4288]96import org.openstreetmap.josm.tools.Utils;
[4932]97import org.openstreetmap.josm.tools.WindowGeometry;
[626]98
[5829]99/**
100 * Abstract class holding various static global variables and methods used in large parts of JOSM application.
101 * @since 98
102 */
[626]103abstract public class Main {
[2485]104
[1104]105 /**
[6143]106 * The JOSM website URL.
107 * @since 6143
108 */
109 public static final String JOSM_WEBSITE = "http://josm.openstreetmap.de";
110
111 /**
[2343]112 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
113 * it only shows the MOTD panel.
[2512]114 *
[5357]115 * @return <code>true</code> if JOSM currently displays a map view
[2343]116 */
117 static public boolean isDisplayingMapView() {
118 if (map == null) return false;
119 if (map.mapView == null) return false;
120 return true;
121 }
[6070]122
[2343]123 /**
[1104]124 * Global parent component for all dialogs and message boxes
125 */
126 public static Component parent;
[6070]127
[1104]128 /**
129 * Global application.
130 */
131 public static Main main;
[6070]132
[1104]133 /**
[5831]134 * Command-line arguments used to run the application.
135 */
136 public static String[] commandLineArgs;
[6070]137
[5831]138 /**
[1104]139 * The worker thread slave. This is for executing all long and intensive
140 * calculations. The executed runnables are guaranteed to be executed separately
141 * and sequential.
142 */
[4718]143 public final static ExecutorService worker = new ProgressMonitorExecutor();
[6070]144
[1104]145 /**
146 * Global application preferences
147 */
[3542]148 public static Preferences pref;
[1814]149
[1104]150 /**
151 * The global paste buffer.
152 */
[4869]153 public static final PrimitiveDeepCopy pasteBuffer = new PrimitiveDeepCopy();
[6070]154
[5829]155 /**
156 * The layer source from which {@link Main#pasteBuffer} data comes from.
157 */
[1592]158 public static Layer pasteSource;
[4126]159
[1104]160 /**
[5829]161 * The MapFrame. Use {@link Main#setMapFrame} to set or clear it.
[1104]162 */
163 public static MapFrame map;
[6070]164
[1104]165 /**
[5357]166 * Set to <code>true</code>, when in applet mode
[1104]167 */
168 public static boolean applet = false;
[626]169
[1104]170 /**
171 * The toolbar preference control to register new actions.
172 */
173 public static ToolbarPreferences toolbar;
[626]174
[5829]175 /**
176 * The commands undo/redo handler.
177 */
[1104]178 public UndoRedoHandler undoRedo = new UndoRedoHandler();
[626]179
[5831]180 /**
181 * The progress monitor being currently displayed.
182 */
[4718]183 public static PleaseWaitProgressMonitor currentProgressMonitor;
184
[1104]185 /**
186 * The main menu bar at top of screen.
187 */
[5134]188 public MainMenu menu;
[626]189
[5481]190 /**
191 * The data validation handler.
192 */
[5134]193 public OsmValidator validator;
[1104]194 /**
[1356]195 * The MOTD Layer.
196 */
[3669]197 private GettingStarted gettingStarted = new GettingStarted();
[1356]198
[5957]199 private static final Collection<MapFrameListener> mapFrameListeners = new ArrayList<MapFrameListener>();
200
[1356]201 /**
[6248]202 * Logging level (4 = debug, 3 = info, 2 = warn, 1 = error, 0 = none).
203 * @since 6248
[1104]204 */
[6248]205 public static int logLevel = 3;
206
[5481]207 /**
[6248]208 * Prints an error message if logging is on.
[5481]209 * @param msg The message to print.
[6248]210 * @since 6248
[5481]211 */
[6248]212 public static void error(String msg) {
213 if (logLevel < 1)
[4190]214 return;
[6248]215 System.err.println(tr("ERROR: {0}", msg));
216 }
217
218 /**
219 * Prints a warning message if logging is on.
220 * @param msg The message to print.
221 */
222 public static void warn(String msg) {
223 if (logLevel < 2)
224 return;
[5854]225 System.err.println(tr("WARNING: {0}", msg));
[4190]226 }
[6248]227
[5481]228 /**
[6248]229 * Prints an informational message if logging is on.
[5481]230 * @param msg The message to print.
231 */
[6248]232 public static void info(String msg) {
233 if (logLevel < 3)
[4190]234 return;
[6248]235 System.out.println(tr("INFO: {0}", msg));
[4190]236 }
[6248]237
[5481]238 /**
[6248]239 * Prints a debug message if logging is on.
[5481]240 * @param msg The message to print.
241 */
[6248]242 public static void debug(String msg) {
243 if (logLevel < 4)
[1104]244 return;
[6248]245 System.out.println(tr("DEBUG: {0}", msg));
[1104]246 }
[6248]247
[5481]248 /**
[6248]249 * Prints a formated error message if logging is on. Calls {@link MessageFormat#format}
[5481]250 * function to format text.
251 * @param msg The formated message to print.
252 * @param objects The objects to insert into format string.
[6248]253 * @since 6248
[5481]254 */
[6248]255 public static void error(String msg, Object... objects) {
256 error(MessageFormat.format(msg, objects));
257 }
258
259 /**
260 * Prints a formated warning message if logging is on. Calls {@link MessageFormat#format}
261 * function to format text.
262 * @param msg The formated message to print.
263 * @param objects The objects to insert into format string.
264 */
265 public static void warn(String msg, Object... objects) {
[5481]266 warn(MessageFormat.format(msg, objects));
267 }
[6248]268
[5481]269 /**
[6248]270 * Prints a formated informational message if logging is on. Calls {@link MessageFormat#format}
[5481]271 * function to format text.
272 * @param msg The formated message to print.
273 * @param objects The objects to insert into format string.
274 */
[6248]275 public static void info(String msg, Object... objects) {
[5481]276 info(MessageFormat.format(msg, objects));
277 }
[6248]278
[5481]279 /**
[6248]280 * Prints a formated debug message if logging is on. Calls {@link MessageFormat#format}
[5481]281 * function to format text.
282 * @param msg The formated message to print.
283 * @param objects The objects to insert into format string.
284 */
[6248]285 public static void debug(String msg, Object... objects) {
[5481]286 debug(MessageFormat.format(msg, objects));
287 }
[6248]288
289 /**
290 * Prints an error message for the given Throwable.
291 * @param t The throwable object causing the error
292 * @since 6248
293 */
294 public static void error(Throwable t) {
[6311]295 error(getErrorMessage(t));
[6248]296 }
297
298 /**
299 * Prints a warning message for the given Throwable.
300 * @param t The throwable object causing the error
301 * @since 6248
302 */
303 public static void warn(Throwable t) {
[6311]304 warn(getErrorMessage(t));
[6248]305 }
[6311]306
307 private static String getErrorMessage(Throwable t) {
308 StringBuilder sb = new StringBuilder(t.getClass().getName());
309 String msg = t.getMessage();
310 if (msg != null) {
311 sb.append(": ").append(msg.trim());
312 }
313 return sb.toString();
314 }
[301]315
[1104]316 /**
317 * Platform specific code goes in here.
318 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
319 * So if you need to hook into those early ones, split your class and send the one with the early hooks
320 * to the JOSM team for inclusion.
321 */
322 public static PlatformHook platform;
[1023]323
[1104]324 /**
[5262]325 * Whether or not the java vm is openjdk
[2987]326 * We use this to work around openjdk bugs
327 */
328 public static boolean isOpenjdk;
329
330 /**
[1104]331 * Set or clear (if passed <code>null</code>) the map.
[5829]332 * @param map The map to set {@link Main#map} to. Can be null.
[1104]333 */
334 public final void setMapFrame(final MapFrame map) {
335 MapFrame old = Main.map;
336 panel.setVisible(false);
337 panel.removeAll();
[1750]338 if (map != null) {
[1104]339 map.fillPanel(panel);
[1750]340 } else {
[1104]341 old.destroy();
[1356]342 panel.add(gettingStarted, BorderLayout.CENTER);
[1104]343 }
344 panel.setVisible(true);
345 redoUndoListener.commandChanged(0,0);
[301]346
[2485]347 Main.map = map;
348
[5957]349 for (MapFrameListener listener : mapFrameListeners ) {
350 listener.mapFrameInitialized(old, map);
351 }
[4718]352 if (map == null && currentProgressMonitor != null) {
353 currentProgressMonitor.showForegroundDialog();
354 }
[1104]355 }
[626]356
[1104]357 /**
[1169]358 * Remove the specified layer from the map. If it is the last layer,
[1096]359 * remove the map as well.
[5831]360 * @param layer The layer to remove
[1104]361 */
[5896]362 public final synchronized void removeLayer(final Layer layer) {
[1633]363 if (map != null) {
364 map.mapView.removeLayer(layer);
[6265]365 if (map.mapView.getAllLayers().isEmpty()) {
[1633]366 setMapFrame(null);
[1750]367 }
[1633]368 }
[1104]369 }
[626]370
[4681]371 private static InitStatusListener initListener = null;
372
373 public static interface InitStatusListener {
374
375 void updateStatus(String event);
376 }
377
378 public static void setInitStatusListener(InitStatusListener listener) {
379 initListener = listener;
380 }
381
[1104]382 public Main() {
383 main = this;
[2987]384 isOpenjdk = System.getProperty("java.vm.name").toUpperCase().indexOf("OPENJDK") != -1;
[4681]385
[4718]386 if (initListener != null) {
[4681]387 initListener.updateStatus(tr("Executing platform startup hook"));
[4718]388 }
[1104]389 platform.startupHook();
[3934]390
[5138]391 if (initListener != null) {
392 initListener.updateStatus(tr("Building main menu"));
393 }
394 contentPanePrivate.add(panel, BorderLayout.CENTER);
395 panel.add(gettingStarted, BorderLayout.CENTER);
396 menu = new MainMenu();
397
398 undoRedo.addCommandQueueListener(redoUndoListener);
399
400 // creating toolbar
401 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
402
403 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
404 KeyEvent.VK_F1, Shortcut.DIRECT));
405
[5134]406 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
407 List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
[3934]408
[5134]409 tasks.add(new Callable<Void>() {
[626]410
[5134]411 @Override
412 public Void call() throws Exception {
413 // We try to establish an API connection early, so that any API
414 // capabilities are already known to the editor instance. However
415 // if it goes wrong that's not critical at this stage.
416 if (initListener != null) {
417 initListener.updateStatus(tr("Initializing OSM API"));
418 }
419 try {
420 OsmApi.getOsmApi().initialize(null, true);
421 } catch (Exception x) {
422 // ignore any exception here.
423 }
424 return null;
425 }
426 });
[1023]427
[5134]428 tasks.add(new Callable<Void>() {
[626]429
[5134]430 @Override
431 public Void call() throws Exception {
432 if (initListener != null) {
433 initListener.updateStatus(tr("Initializing presets"));
434 }
435 TaggingPresetPreference.initialize();
[5177]436 // some validator tests require the presets to be initialized
437 // TODO remove this dependency for parallel initialization
438 if (initListener != null) {
439 initListener.updateStatus(tr("Initializing validator"));
440 }
441 validator = new OsmValidator();
442 MapView.addLayerChangeListener(validator);
[5134]443 return null;
444 }
445 });
446
447 tasks.add(new Callable<Void>() {
448
449 @Override
450 public Void call() throws Exception {
451 if (initListener != null) {
452 initListener.updateStatus(tr("Initializing map styles"));
453 }
454 MapPaintPreference.initialize();
455 return null;
456 }
457 });
458
459 tasks.add(new Callable<Void>() {
460
461 @Override
462 public Void call() throws Exception {
463 if (initListener != null) {
464 initListener.updateStatus(tr("Loading imagery preferences"));
465 }
466 ImageryPreference.initialize();
467 return null;
468 }
469 });
470
471 try {
[5195]472 for (Future<Void> i : Executors.newFixedThreadPool(
473 Runtime.getRuntime().availableProcessors()).invokeAll(tasks)) {
474 i.get();
475 }
476 } catch (Exception ex) {
[5134]477 throw new RuntimeException(ex);
[4718]478 }
[3669]479
[4489]480 // hooks for the jmapviewer component
481 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
482 @Override
483 public void openLink(String url) {
484 OpenBrowser.displayUrl(url);
485 }
486 });
487 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
488
[4718]489 if (initListener != null) {
[4681]490 initListener.updateStatus(tr("Updating user interface"));
[4718]491 }
[4681]492
[1104]493 toolbar.refreshToolbarControl();
[626]494
[1104]495 toolbar.control.updateUI();
[3252]496 contentPanePrivate.updateUI();
[3934]497
[1104]498 }
[626]499
[1104]500 /**
501 * Add a new layer to the map. If no map exists, create one.
502 */
[5262]503 public final synchronized void addLayer(final Layer layer) {
[5670]504 boolean noMap = map == null;
505 if (noMap) {
506 createMapFrame(layer, null);
[1104]507 }
[5391]508 layer.hookUpMapView();
[1104]509 map.mapView.addLayer(layer);
[5670]510 if (noMap) {
511 Main.map.setVisible(true);
512 }
[1104]513 }
[1814]514
[5670]515 public synchronized void createMapFrame(Layer firstLayer, ViewportData viewportData) {
516 MapFrame mapFrame = new MapFrame(contentPanePrivate, viewportData);
517 setMapFrame(mapFrame);
518 if (firstLayer != null) {
519 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction(), firstLayer);
520 }
521 mapFrame.initializeDialogsPane();
522 // bootstrapping problem: make sure the layer list dialog is going to
523 // listen to change events of the very first layer
524 //
[5889]525 if (firstLayer != null) {
526 firstLayer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
527 }
[5670]528 }
529
[1104]530 /**
[5357]531 * Replies <code>true</code> if there is an edit layer
[1811]532 *
[5357]533 * @return <code>true</code> if there is an edit layer
[1104]534 */
[1825]535 public boolean hasEditLayer() {
[3071]536 if (getEditLayer() == null) return false;
[1814]537 return true;
538 }
539
540 /**
541 * Replies the current edit layer
[2224]542 *
[5357]543 * @return the current edit layer. <code>null</code>, if no current edit layer exists
[1814]544 */
545 public OsmDataLayer getEditLayer() {
546 if (map == null) return null;
547 if (map.mapView == null) return null;
[1750]548 return map.mapView.getEditLayer();
[1104]549 }
[626]550
[1104]551 /**
[1814]552 * Replies the current data set.
[1811]553 *
[5357]554 * @return the current data set. <code>null</code>, if no current data set exists
[1750]555 */
[1814]556 public DataSet getCurrentDataSet() {
[1825]557 if (!hasEditLayer()) return null;
[1814]558 return getEditLayer().data;
[1750]559 }
560
561 /**
[3071]562 * Returns the currently active layer
563 *
[5357]564 * @return the currently active layer. <code>null</code>, if currently no active layer exists
[3071]565 */
566 public Layer getActiveLayer() {
567 if (map == null) return null;
568 if (map.mapView == null) return null;
569 return map.mapView.getActiveLayer();
570 }
571
[4869]572 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
[3252]573
[4897]574 public static void redirectToMainContentPane(JComponent source) {
575 RedirectInputMap.redirect(source, contentPanePrivate);
576 }
[626]577
[5278]578 public static void registerActionShortcut(JosmAction action) {
579 registerActionShortcut(action, action.getShortcut());
580 }
581
[3252]582 public static void registerActionShortcut(Action action, Shortcut shortcut) {
[5002]583 KeyStroke keyStroke = shortcut.getKeyStroke();
[3252]584 if (keyStroke == null)
585 return;
586
587 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
588 Object existing = inputMap.get(keyStroke);
589 if (existing != null && !existing.equals(action)) {
[6248]590 info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
[3252]591 }
592 inputMap.put(keyStroke, action);
593
594 contentPanePrivate.getActionMap().put(action, action);
595 }
596
[5382]597 public static void unregisterShortcut(Shortcut shortcut) {
[3327]598 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
[3252]599 }
600
[3444]601 public static void unregisterActionShortcut(JosmAction action) {
602 unregisterActionShortcut(action, action.getShortcut());
603 }
604
605 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
[5382]606 unregisterShortcut(shortcut);
[3444]607 contentPanePrivate.getActionMap().remove(action);
608 }
[6070]609
[5696]610 /**
611 * Replies the registered action for the given shortcut
612 * @param shortcut The shortcut to look for
613 * @return the registered action for the given shortcut
614 * @since 5696
615 */
616 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
617 KeyStroke keyStroke = shortcut.getKeyStroke();
618 if (keyStroke == null)
619 return null;
620 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
621 if (action instanceof Action)
622 return (Action) action;
623 return null;
624 }
[3444]625
[1104]626 ///////////////////////////////////////////////////////////////////////////
627 // Implementation part
628 ///////////////////////////////////////////////////////////////////////////
[626]629
[5829]630 /**
[6070]631 * Global panel.
[5829]632 */
[4869]633 public static final JPanel panel = new JPanel(new BorderLayout());
[626]634
[4932]635 protected static WindowGeometry geometry;
[2876]636 protected static int windowState = JFrame.NORMAL;
[626]637
[1104]638 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
[6084]639 @Override
[1104]640 public void commandChanged(final int queueSize, final int redoSize) {
641 menu.undo.setEnabled(queueSize > 0);
642 menu.redo.setEnabled(redoSize > 0);
643 }
644 };
[1722]645
[1104]646 /**
647 * Should be called before the main constructor to setup some parameter stuff
648 * @param args The parsed argument list.
649 */
[5279]650 public static void preConstructorInit(Map<Option, Collection<String>> args) {
[2272]651 ProjectionPreference.setProjection();
[626]652
[1104]653 try {
[2708]654 String defaultlaf = platform.getDefaultStyle();
[2709]655 String laf = Main.pref.get("laf", defaultlaf);
[1188]656 try {
[2709]657 UIManager.setLookAndFeel(laf);
[1188]658 }
[6248]659 catch (final ClassNotFoundException e) {
660 info("Look and Feel not found: " + laf);
[2708]661 Main.pref.put("laf", defaultlaf);
662 }
[6248]663 catch (final UnsupportedLookAndFeelException e) {
664 info("Look and Feel not supported: " + laf);
[2708]665 Main.pref.put("laf", defaultlaf);
[1188]666 }
[1104]667 toolbar = new ToolbarPreferences();
[3252]668 contentPanePrivate.updateUI();
[1104]669 panel.updateUI();
670 } catch (final Exception e) {
671 e.printStackTrace();
672 }
673 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
674 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
675 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
676 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
[626]677
[3433]678 I18n.translateJavaInternalMessages();
[3378]679
[1990]680 // init default coordinate format
681 //
682 try {
683 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
684 } catch (IllegalArgumentException iae) {
685 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
686 }
687
[4932]688 geometry = WindowGeometry.mainWindow("gui.geometry",
[5279]689 (args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null),
690 !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
[1104]691 }
[626]692
[5829]693 protected static void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
[5279]694 if (args.containsKey(Option.DOWNLOAD)) {
[2798]695 List<File> fileList = new ArrayList<File>();
[5279]696 for (String s : args.get(Option.DOWNLOAD)) {
[2798]697 File f = null;
698 switch(paramType(s)) {
699 case httpUrl:
700 downloadFromParamHttp(false, s);
701 break;
702 case bounds:
703 downloadFromParamBounds(false, s);
704 break;
705 case fileUrl:
706 try {
707 f = new File(new URI(s));
708 } catch (URISyntaxException e) {
709 JOptionPane.showMessageDialog(
710 Main.parent,
711 tr("Ignoring malformed file URL: \"{0}\"", s),
712 tr("Warning"),
713 JOptionPane.WARNING_MESSAGE
[4718]714 );
[2798]715 }
716 if (f!=null) {
717 fileList.add(f);
718 }
719 break;
720 case fileName:
721 f = new File(s);
722 fileList.add(f);
723 break;
724 }
[1750]725 }
[2798]726 if(!fileList.isEmpty())
727 {
[3924]728 OpenFileAction.openFiles(fileList, true);
[2798]729 }
[1750]730 }
[5279]731 if (args.containsKey(Option.DOWNLOADGPS)) {
732 for (String s : args.get(Option.DOWNLOADGPS)) {
[2798]733 switch(paramType(s)) {
734 case httpUrl:
735 downloadFromParamHttp(true, s);
736 break;
737 case bounds:
738 downloadFromParamBounds(true, s);
739 break;
740 case fileUrl:
741 case fileName:
742 JOptionPane.showMessageDialog(
743 Main.parent,
744 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
745 tr("Warning"),
746 JOptionPane.WARNING_MESSAGE
[4718]747 );
[2798]748 }
[1750]749 }
750 }
[5279]751 if (args.containsKey(Option.SELECTION)) {
752 for (String s : args.get(Option.SELECTION)) {
[3317]753 SearchAction.search(s, SearchAction.SearchMode.add);
[1750]754 }
755 }
[1104]756 }
[626]757
[5519]758 /**
759 * Asks user to perform "save layer" operations (save .osm on disk and/or upload osm data to server) for all {@link OsmDataLayer} before JOSM exits.
760 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations. {@code false} if the user cancels.
761 * @since 2025
762 */
[2025]763 public static boolean saveUnsavedModifications() {
[5519]764 if (map == null || map.mapView == null) return true;
765 return saveUnsavedModifications(map.mapView.getLayersOfType(OsmDataLayer.class), true);
766 }
767
768 /**
769 * Asks user to perform "save layer" operations (save .osm on disk and/or upload osm data to server) before osm layers deletion.
[6070]770 *
[5519]771 * @param selectedLayers The layers to check. Only instances of {@link OsmDataLayer} are considered.
772 * @param exit {@code true} if JOSM is exiting, {@code false} otherwise.
773 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations. {@code false} if the user cancels.
774 * @since 5519
775 */
776 public static boolean saveUnsavedModifications(List<? extends Layer> selectedLayers, boolean exit) {
777 SaveLayersDialog dialog = new SaveLayersDialog(parent);
[2025]778 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
[5519]779 for (Layer l: selectedLayers) {
780 if (!(l instanceof OsmDataLayer)) {
781 continue;
[2025]782 }
[5519]783 OsmDataLayer odl = (OsmDataLayer)l;
784 if ((odl.requiresSaveToFile() || (odl.requiresUploadToServer() && !odl.isUploadDiscouraged())) && odl.data.isModified()) {
785 layersWithUnmodifiedChanges.add(odl);
786 }
[2025]787 }
[5519]788 if (exit) {
789 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
790 } else {
791 dialog.prepareForSavingAndUpdatingLayersBeforeDelete();
792 }
[2025]793 if (!layersWithUnmodifiedChanges.isEmpty()) {
794 dialog.getModel().populate(layersWithUnmodifiedChanges);
795 dialog.setVisible(true);
796 switch(dialog.getUserAction()) {
[2485]797 case CANCEL: return false;
798 case PROCEED: return true;
799 default: return false;
[2025]800 }
801 }
[2274]802
[2025]803 return true;
804 }
805
[5829]806 /**
807 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM). If there are some unsaved data layers, asks first for user confirmation.
808 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a return code of 0.
809 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
810 * @since 3378
811 */
[6125]812 public static boolean exitJosm(boolean exit, int exitCode) {
[3378]813 if (Main.saveUnsavedModifications()) {
[4932]814 geometry.remember("gui.geometry");
[5829]815 if (map != null) {
[4932]816 map.rememberToggleDialogWidth();
817 }
818 pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
[3378]819 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
820 if (Main.isDisplayingMapView()) {
821 Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
822 for (Layer l: layers) {
[5897]823 Main.main.removeLayer(l);
[3378]824 }
825 }
826 if (exit) {
[6125]827 System.exit(exitCode);
[5829]828 }
829 return true;
830 }
831 return false;
[3378]832 }
833
[2798]834 /**
835 * The type of a command line parameter, to be used in switch statements.
[5195]836 * @see #paramType
[2798]837 */
838 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
839
840 /**
841 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
842 * @param s A parameter string
843 * @return The guessed parameter type
844 */
[5829]845 private static DownloadParamType paramType(String s) {
[2798]846 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
847 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
[5240]848 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
[4901]849 if(s.matches(coorPattern+"(,"+coorPattern+"){3}")) return DownloadParamType.bounds;
[2798]850 // everything else must be a file name
851 return DownloadParamType.fileName;
852 }
853
854 /**
855 * Download area specified on the command line as OSM URL.
856 * @param rawGps Flag to download raw GPS tracks
857 * @param s The URL parameter
858 */
859 private static void downloadFromParamHttp(final boolean rawGps, String s) {
860 final Bounds b = OsmUrlToBounds.parse(s);
861 if (b == null) {
862 JOptionPane.showMessageDialog(
863 Main.parent,
864 tr("Ignoring malformed URL: \"{0}\"", s),
865 tr("Warning"),
866 JOptionPane.WARNING_MESSAGE
[4718]867 );
[2798]868 } else {
869 downloadFromParamBounds(rawGps, b);
[1104]870 }
[2798]871 }
[626]872
[2798]873 /**
874 * Download area specified on the command line as bounds string.
875 * @param rawGps Flag to download raw GPS tracks
876 * @param s The bounds parameter
877 */
878 private static void downloadFromParamBounds(final boolean rawGps, String s) {
[1104]879 final StringTokenizer st = new StringTokenizer(s, ",");
880 if (st.countTokens() == 4) {
[2327]881 Bounds b = new Bounds(
[2485]882 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
883 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
[4718]884 );
[2798]885 downloadFromParamBounds(rawGps, b);
[1104]886 }
887 }
[1023]888
[2798]889 /**
890 * Download area specified as Bounds value.
891 * @param rawGps Flag to download raw GPS tracks
892 * @param b The bounds value
[5195]893 * @see #downloadFromParamBounds(boolean, String)
894 * @see #downloadFromParamHttp
[2798]895 */
896 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
897 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
898 // asynchronously launch the download task ...
899 Future<?> future = task.download(true, b, null);
900 // ... and the continuation when the download is finished (this will wait for the download to finish)
901 Main.worker.execute(new PostDownloadHandler(task, future));
902 }
903
[5829]904 /**
905 * Identifies the current operating system family and initializes the platform hook accordingly.
906 * @since 1849
907 */
[1849]908 public static void determinePlatformHook() {
[1104]909 String os = System.getProperty("os.name");
910 if (os == null) {
[6248]911 warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
[1104]912 platform = new PlatformHookUnixoid();
913 } else if (os.toLowerCase().startsWith("windows")) {
914 platform = new PlatformHookWindows();
[1169]915 } else if (os.equals("Linux") || os.equals("Solaris") ||
[1750]916 os.equals("SunOS") || os.equals("AIX") ||
917 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
[1104]918 platform = new PlatformHookUnixoid();
919 } else if (os.toLowerCase().startsWith("mac os x")) {
920 platform = new PlatformHookOsx();
921 } else {
[6248]922 warn("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
[1104]923 platform = new PlatformHookUnixoid();
924 }
925 }
[1023]926
[2876]927 private static class WindowPositionSizeListener extends WindowAdapter implements
928 ComponentListener {
929 @Override
930 public void windowStateChanged(WindowEvent e) {
931 Main.windowState = e.getNewState();
932 }
933
[4932]934 @Override
[2876]935 public void componentHidden(ComponentEvent e) {
936 }
937
[4932]938 @Override
[2876]939 public void componentMoved(ComponentEvent e) {
940 handleComponentEvent(e);
941 }
942
[4932]943 @Override
[2876]944 public void componentResized(ComponentEvent e) {
945 handleComponentEvent(e);
946 }
947
[4932]948 @Override
[2876]949 public void componentShown(ComponentEvent e) {
950 }
951
952 private void handleComponentEvent(ComponentEvent e) {
953 Component c = e.getComponent();
[5514]954 if (c instanceof JFrame && c.isVisible()) {
955 if(Main.windowState == JFrame.NORMAL) {
956 Main.geometry = new WindowGeometry((JFrame) c);
957 } else {
958 Main.geometry.fixScreen((JFrame) c);
959 }
[2876]960 }
961 }
962 }
[6070]963
[5829]964 protected static void addListener() {
[2876]965 parent.addComponentListener(new WindowPositionSizeListener());
966 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
967 }
[3815]968
[5829]969 /**
970 * Checks that JOSM is at least running with Java 6.
971 * @since 3815
972 */
[3815]973 public static void checkJava6() {
974 String version = System.getProperty("java.version");
975 if (version != null) {
976 if (version.startsWith("1.6") || version.startsWith("6") ||
[5829]977 version.startsWith("1.7") || version.startsWith("7") ||
978 version.startsWith("1.8") || version.startsWith("8"))
[3815]979 return;
980 if (version.startsWith("1.5") || version.startsWith("5")) {
981 JLabel ho = new JLabel("<html>"+
982 tr("<h2>JOSM requires Java version 6.</h2>"+
983 "Detected Java version: {0}.<br>"+
984 "You can <ul><li>update your Java (JRE) or</li>"+
985 "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
986 "More Info:", version)+"</html>");
[6143]987 JTextArea link = new JTextArea(HelpUtil.getWikiBaseHelpUrl()+"/Help/SystemRequirements");
[3815]988 link.setEditable(false);
989 link.setBackground(panel.getBackground());
990 JPanel panel = new JPanel(new GridBagLayout());
991 GridBagConstraints gbc = new GridBagConstraints();
992 gbc.gridwidth = GridBagConstraints.REMAINDER;
993 gbc.anchor = GridBagConstraints.WEST;
994 gbc.weightx = 1.0;
995 panel.add(ho, gbc);
996 panel.add(link, gbc);
997 final String EXIT = tr("Exit JOSM");
998 final String CONTINUE = tr("Continue, try anyway");
999 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
1000 if (ret == 0) {
1001 System.exit(0);
1002 }
1003 return;
1004 }
1005 }
[6248]1006 error("Could not recognize Java Version: "+version);
[3815]1007 }
[4126]1008
1009 /* ----------------------------------------------------------------------------------------- */
1010 /* projection handling - Main is a registry for a single, global projection instance */
1011 /* */
1012 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
1013 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
1014 /* ----------------------------------------------------------------------------------------- */
1015 /**
1016 * The projection method used.
[4897]1017 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
1018 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
[4126]1019 */
[4897]1020 private static Projection proj;
[4126]1021
1022 /**
1023 * Replies the current projection.
[4489]1024 *
[5357]1025 * @return the currently active projection
[4126]1026 */
1027 public static Projection getProjection() {
1028 return proj;
1029 }
1030
1031 /**
1032 * Sets the current projection
[4489]1033 *
[4126]1034 * @param p the projection
1035 */
1036 public static void setProjection(Projection p) {
1037 CheckParameterUtil.ensureParameterNotNull(p);
1038 Projection oldValue = proj;
[5460]1039 Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
[4126]1040 proj = p;
[5234]1041 fireProjectionChanged(oldValue, proj, b);
[4126]1042 }
1043
1044 /*
1045 * Keep WeakReferences to the listeners. This relieves clients from the burden of
1046 * explicitly removing the listeners and allows us to transparently register every
1047 * created dataset as projection change listener.
1048 */
1049 private static final ArrayList<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
1050
[5234]1051 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
[4126]1052 if (newValue == null ^ oldValue == null
[4288]1053 || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
[4126]1054
1055 synchronized(Main.class) {
1056 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
[5538]1057 while (it.hasNext()){
[4126]1058 WeakReference<ProjectionChangeListener> wr = it.next();
[4724]1059 ProjectionChangeListener listener = wr.get();
1060 if (listener == null) {
[4126]1061 it.remove();
1062 continue;
1063 }
[4724]1064 listener.projectionChanged(oldValue, newValue);
[4126]1065 }
1066 }
[5234]1067 if (newValue != null && oldBounds != null) {
1068 Main.map.mapView.zoomTo(oldBounds);
[4126]1069 }
1070 /* TODO - remove layers with fixed projection */
1071 }
1072 }
1073
1074 /**
[5538]1075 * Register a projection change listener.
[4489]1076 *
[5357]1077 * @param listener the listener. Ignored if <code>null</code>.
[4126]1078 */
1079 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
1080 if (listener == null) return;
1081 synchronized (Main.class) {
1082 for (WeakReference<ProjectionChangeListener> wr : listeners) {
1083 // already registered ? => abort
1084 if (wr.get() == listener) return;
1085 }
[4774]1086 listeners.add(new WeakReference<ProjectionChangeListener>(listener));
[4126]1087 }
1088 }
1089
1090 /**
[5538]1091 * Removes a projection change listener.
[4489]1092 *
[5357]1093 * @param listener the listener. Ignored if <code>null</code>.
[4126]1094 */
1095 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
1096 if (listener == null) return;
1097 synchronized(Main.class){
1098 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
[5538]1099 while (it.hasNext()){
[4126]1100 WeakReference<ProjectionChangeListener> wr = it.next();
[5538]1101 // remove the listener - and any other listener which got garbage
[4126]1102 // collected in the meantime
1103 if (wr.get() == null || wr.get() == listener) {
1104 it.remove();
1105 }
1106 }
1107 }
1108 }
[5538]1109
1110 /**
1111 * Listener for window switch events.
[6070]1112 *
[5538]1113 * These are events, when the user activates a window of another application
1114 * or comes back to JOSM. Window switches from one JOSM window to another
1115 * are not reported.
1116 */
1117 public static interface WindowSwitchListener {
1118 /**
1119 * Called when the user activates a window of another application.
1120 */
1121 void toOtherApplication();
1122 /**
1123 * Called when the user comes from a window of another application
1124 * back to JOSM.
1125 */
1126 void fromOtherApplication();
1127 }
1128
1129 private static final ArrayList<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<WeakReference<WindowSwitchListener>>();
1130
1131 /**
1132 * Register a window switch listener.
1133 *
1134 * @param listener the listener. Ignored if <code>null</code>.
1135 */
1136 public static void addWindowSwitchListener(WindowSwitchListener listener) {
1137 if (listener == null) return;
1138 synchronized (Main.class) {
1139 for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
1140 // already registered ? => abort
1141 if (wr.get() == listener) return;
1142 }
1143 boolean wasEmpty = windowSwitchListeners.isEmpty();
1144 windowSwitchListeners.add(new WeakReference<WindowSwitchListener>(listener));
1145 if (wasEmpty) {
1146 // The following call will have no effect, when there is no window
1147 // at the time. Therefore, MasterWindowListener.setup() will also be
1148 // called, as soon as the main window is shown.
1149 MasterWindowListener.setup();
1150 }
1151 }
1152 }
1153
1154 /**
1155 * Removes a window switch listener.
1156 *
1157 * @param listener the listener. Ignored if <code>null</code>.
1158 */
1159 public static void removeWindowSwitchListener(WindowSwitchListener listener) {
1160 if (listener == null) return;
1161 synchronized (Main.class){
1162 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1163 while (it.hasNext()){
1164 WeakReference<WindowSwitchListener> wr = it.next();
1165 // remove the listener - and any other listener which got garbage
1166 // collected in the meantime
1167 if (wr.get() == null || wr.get() == listener) {
1168 it.remove();
1169 }
1170 }
1171 if (windowSwitchListeners.isEmpty()) {
1172 MasterWindowListener.teardown();
1173 }
1174 }
1175 }
1176
1177 /**
1178 * WindowListener, that is registered on all Windows of the application.
1179 *
1180 * Its purpose is to notify WindowSwitchListeners, that the user switches to
1181 * another application, e.g. a browser, or back to JOSM.
1182 *
1183 * When changing from JOSM to another application and back (e.g. two times
1184 * alt+tab), the active Window within JOSM may be different.
1185 * Therefore, we need to register listeners to <strong>all</strong> (visible)
1186 * Windows in JOSM, and it does not suffice to monitor the one that was
1187 * deactivated last.
1188 *
1189 * This class is only "active" on demand, i.e. when there is at least one
1190 * WindowSwitchListener registered.
1191 */
1192 protected static class MasterWindowListener extends WindowAdapter {
1193
1194 private static MasterWindowListener INSTANCE;
1195
1196 public static MasterWindowListener getInstance() {
1197 if (INSTANCE == null) {
1198 INSTANCE = new MasterWindowListener();
1199 }
1200 return INSTANCE;
1201 }
1202
1203 /**
1204 * Register listeners to all non-hidden windows.
1205 *
1206 * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
1207 */
1208 public static void setup() {
1209 if (!windowSwitchListeners.isEmpty()) {
1210 for (Window w : Window.getWindows()) {
1211 if (w.isShowing()) {
1212 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1213 w.addWindowListener(getInstance());
1214 }
1215 }
1216 }
1217 }
1218 }
1219
1220 /**
1221 * Unregister all listeners.
1222 */
1223 public static void teardown() {
1224 for (Window w : Window.getWindows()) {
1225 w.removeWindowListener(getInstance());
1226 }
1227 }
1228
1229 @Override
1230 public void windowActivated(WindowEvent e) {
1231 if (e.getOppositeWindow() == null) { // we come from a window of a different application
1232 // fire WindowSwitchListeners
1233 synchronized (Main.class) {
1234 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1235 while (it.hasNext()){
1236 WeakReference<WindowSwitchListener> wr = it.next();
1237 WindowSwitchListener listener = wr.get();
1238 if (listener == null) {
1239 it.remove();
1240 continue;
1241 }
1242 listener.fromOtherApplication();
1243 }
1244 }
1245 }
1246 }
1247
1248 @Override
1249 public void windowDeactivated(WindowEvent e) {
1250 // set up windows that have been created in the meantime
1251 for (Window w : Window.getWindows()) {
1252 if (!w.isShowing()) {
1253 w.removeWindowListener(getInstance());
1254 } else {
1255 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1256 w.addWindowListener(getInstance());
1257 }
1258 }
1259 }
1260 if (e.getOppositeWindow() == null) { // we go to a window of a different application
1261 // fire WindowSwitchListeners
1262 synchronized (Main.class) {
1263 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1264 while (it.hasNext()){
1265 WeakReference<WindowSwitchListener> wr = it.next();
1266 WindowSwitchListener listener = wr.get();
1267 if (listener == null) {
1268 it.remove();
1269 continue;
1270 }
1271 listener.toOtherApplication();
1272 }
1273 }
1274 }
1275 }
1276 }
1277
[5957]1278 /**
1279 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1280 * @param listener The MapFrameListener
1281 * @return {@code true} if the listeners collection changed as a result of the call
1282 * @since 5957
1283 */
1284 public static boolean addMapFrameListener(MapFrameListener listener) {
1285 return listener != null ? mapFrameListeners.add(listener) : false;
1286 }
1287
1288 /**
1289 * Unregisters the given {@code MapFrameListener} from MapFrame changes
1290 * @param listener The MapFrameListener
1291 * @return {@code true} if the listeners collection changed as a result of the call
1292 * @since 5957
1293 */
1294 public static boolean removeMapFrameListener(MapFrameListener listener) {
1295 return listener != null ? mapFrameListeners.remove(listener) : false;
1296 }
[626]1297}
Note: See TracBrowser for help on using the repository browser.