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

Last change on this file since 5112 was 5112, checked in by simon04, 12 years ago

fix #4077 - patch by sfriedle - Unsaved changes pops up when closing JOSM after undoing all changes

  • Property svn:eol-style set to native
File size: 31.4 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm;
3import static org.openstreetmap.josm.tools.I18n.tr;
4
5import java.awt.BorderLayout;
6import java.awt.Component;
7import java.awt.GridBagConstraints;
8import java.awt.GridBagLayout;
9import java.awt.event.ComponentEvent;
10import java.awt.event.ComponentListener;
11import java.awt.event.KeyEvent;
12import java.awt.event.WindowAdapter;
13import java.awt.event.WindowEvent;
14import java.io.File;
15import java.lang.ref.WeakReference;
16import java.net.URI;
17import java.net.URISyntaxException;
18import java.util.ArrayList;
19import java.util.Collection;
20import java.util.Iterator;
21import java.util.List;
22import java.util.Map;
23import java.util.StringTokenizer;
24import java.util.concurrent.ExecutorService;
25import java.util.concurrent.Future;
26import java.util.regex.Matcher;
27import java.util.regex.Pattern;
28
29import javax.swing.Action;
30import javax.swing.InputMap;
31import javax.swing.JComponent;
32import javax.swing.JFrame;
33import javax.swing.JLabel;
34import javax.swing.JOptionPane;
35import javax.swing.JPanel;
36import javax.swing.JTextArea;
37import javax.swing.KeyStroke;
38import javax.swing.UIManager;
39
40import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
41import org.openstreetmap.josm.actions.JosmAction;
42import org.openstreetmap.josm.actions.OpenFileAction;
43import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
44import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
45import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
46import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
47import org.openstreetmap.josm.actions.mapmode.MapMode;
48import org.openstreetmap.josm.actions.search.SearchAction;
49import org.openstreetmap.josm.data.Bounds;
50import org.openstreetmap.josm.data.Preferences;
51import org.openstreetmap.josm.data.UndoRedoHandler;
52import org.openstreetmap.josm.data.coor.CoordinateFormat;
53import org.openstreetmap.josm.data.coor.LatLon;
54import org.openstreetmap.josm.data.osm.DataSet;
55import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy;
56import org.openstreetmap.josm.data.projection.Projection;
57import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
58import org.openstreetmap.josm.data.validation.OsmValidator;
59import org.openstreetmap.josm.gui.GettingStarted;
60import org.openstreetmap.josm.gui.MainMenu;
61import org.openstreetmap.josm.gui.MapFrame;
62import org.openstreetmap.josm.gui.MapView;
63import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
64import org.openstreetmap.josm.gui.io.SaveLayersDialog;
65import org.openstreetmap.josm.gui.layer.Layer;
66import org.openstreetmap.josm.gui.layer.OsmDataLayer;
67import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
68import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
69import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
70import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
71import org.openstreetmap.josm.gui.preferences.map.ProjectionPreference;
72import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
73import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
74import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
75import org.openstreetmap.josm.gui.util.RedirectInputMap;
76import org.openstreetmap.josm.io.OsmApi;
77import org.openstreetmap.josm.plugins.PluginHandler;
78import org.openstreetmap.josm.tools.CheckParameterUtil;
79import org.openstreetmap.josm.tools.I18n;
80import org.openstreetmap.josm.tools.ImageProvider;
81import org.openstreetmap.josm.tools.OpenBrowser;
82import org.openstreetmap.josm.tools.OsmUrlToBounds;
83import org.openstreetmap.josm.tools.PlatformHook;
84import org.openstreetmap.josm.tools.PlatformHookOsx;
85import org.openstreetmap.josm.tools.PlatformHookUnixoid;
86import org.openstreetmap.josm.tools.PlatformHookWindows;
87import org.openstreetmap.josm.tools.Shortcut;
88import org.openstreetmap.josm.tools.Utils;
89import org.openstreetmap.josm.tools.WindowGeometry;
90
91abstract public class Main {
92
93 /**
94 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
95 * it only shows the MOTD panel.
96 *
97 * @return true if JOSM currently displays a map view
98 */
99 static public boolean isDisplayingMapView() {
100 if (map == null) return false;
101 if (map.mapView == null) return false;
102 return true;
103 }
104 /**
105 * Global parent component for all dialogs and message boxes
106 */
107 public static Component parent;
108 /**
109 * Global application.
110 */
111 public static Main main;
112 /**
113 * The worker thread slave. This is for executing all long and intensive
114 * calculations. The executed runnables are guaranteed to be executed separately
115 * and sequential.
116 */
117 public final static ExecutorService worker = new ProgressMonitorExecutor();
118 /**
119 * Global application preferences
120 */
121 public static Preferences pref;
122
123 /**
124 * The global paste buffer.
125 */
126 public static final PrimitiveDeepCopy pasteBuffer = new PrimitiveDeepCopy();
127 public static Layer pasteSource;
128
129 /**
130 * The MapFrame. Use setMapFrame to set or clear it.
131 */
132 public static MapFrame map;
133 /**
134 * True, when in applet mode
135 */
136 public static boolean applet = false;
137
138 /**
139 * The toolbar preference control to register new actions.
140 */
141 public static ToolbarPreferences toolbar;
142
143 public UndoRedoHandler undoRedo = new UndoRedoHandler();
144
145 public static PleaseWaitProgressMonitor currentProgressMonitor;
146
147 /**
148 * The main menu bar at top of screen.
149 */
150 public final MainMenu menu;
151
152 public final OsmValidator validator;
153 /**
154 * The MOTD Layer.
155 */
156 private GettingStarted gettingStarted = new GettingStarted();
157
158 /**
159 * Print a message if logging is on.
160 */
161 static public int log_level = 2;
162 static public void warn(String msg) {
163 if (log_level < 1)
164 return;
165 System.out.println(msg);
166 }
167 static public void info(String msg) {
168 if (log_level < 2)
169 return;
170 System.out.println(msg);
171 }
172 static public void debug(String msg) {
173 if (log_level < 3)
174 return;
175 System.out.println(msg);
176 }
177
178 /**
179 * Platform specific code goes in here.
180 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
181 * So if you need to hook into those early ones, split your class and send the one with the early hooks
182 * to the JOSM team for inclusion.
183 */
184 public static PlatformHook platform;
185
186 /**
187 * Wheather or not the java vm is openjdk
188 * We use this to work around openjdk bugs
189 */
190 public static boolean isOpenjdk;
191
192 /**
193 * Set or clear (if passed <code>null</code>) the map.
194 */
195 public final void setMapFrame(final MapFrame map) {
196 MapFrame old = Main.map;
197 panel.setVisible(false);
198 panel.removeAll();
199 if (map != null) {
200 map.fillPanel(panel);
201 } else {
202 old.destroy();
203 panel.add(gettingStarted, BorderLayout.CENTER);
204 }
205 panel.setVisible(true);
206 redoUndoListener.commandChanged(0,0);
207
208 Main.map = map;
209
210 PluginHandler.notifyMapFrameChanged(old, map);
211 if (map == null && currentProgressMonitor != null) {
212 currentProgressMonitor.showForegroundDialog();
213 }
214 }
215
216 /**
217 * Remove the specified layer from the map. If it is the last layer,
218 * remove the map as well.
219 */
220 public final void removeLayer(final Layer layer) {
221 if (map != null) {
222 map.mapView.removeLayer(layer);
223 if (map != null && map.mapView.getAllLayers().isEmpty()) {
224 setMapFrame(null);
225 }
226 }
227 }
228
229 private static InitStatusListener initListener = null;
230
231 public static interface InitStatusListener {
232
233 void updateStatus(String event);
234 }
235
236 public static void setInitStatusListener(InitStatusListener listener) {
237 initListener = listener;
238 }
239
240 public Main() {
241 main = this;
242 isOpenjdk = System.getProperty("java.vm.name").toUpperCase().indexOf("OPENJDK") != -1;
243
244 if (initListener != null) {
245 initListener.updateStatus(tr("Executing platform startup hook"));
246 }
247 platform.startupHook();
248
249 // We try to establish an API connection early, so that any API
250 // capabilities are already known to the editor instance. However
251 // if it goes wrong that's not critical at this stage.
252 if (initListener != null) {
253 initListener.updateStatus(tr("Initializing OSM API"));
254 }
255 try {
256 OsmApi.getOsmApi().initialize(null, true);
257 } catch (Exception x) {
258 // ignore any exception here.
259 }
260
261 if (initListener != null) {
262 initListener.updateStatus(tr("Building main menu"));
263 }
264 contentPanePrivate.add(panel, BorderLayout.CENTER);
265 panel.add(gettingStarted, BorderLayout.CENTER);
266 menu = new MainMenu();
267
268 undoRedo.addCommandQueueListener(redoUndoListener);
269
270 // creating toolbar
271 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
272
273 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
274 KeyEvent.VK_F1, Shortcut.DIRECT));
275
276 if (initListener != null) {
277 initListener.updateStatus(tr("Initializing presets"));
278 }
279 TaggingPresetPreference.initialize();
280
281 if (initListener != null) {
282 initListener.updateStatus(tr("Initializing map styles"));
283 }
284 MapPaintPreference.initialize();
285
286 if (initListener != null) {
287 initListener.updateStatus(tr("Loading imagery preferences"));
288 }
289 ImageryPreference.initialize();
290
291 if (initListener != null) {
292 initListener.updateStatus(tr("Initializing validator"));
293 }
294 validator = new OsmValidator();
295 MapView.addLayerChangeListener(validator);
296
297 // hooks for the jmapviewer component
298 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
299 @Override
300 public void openLink(String url) {
301 OpenBrowser.displayUrl(url);
302 }
303 });
304 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
305
306 if (initListener != null) {
307 initListener.updateStatus(tr("Updating user interface"));
308 }
309
310 toolbar.refreshToolbarControl();
311
312 toolbar.control.updateUI();
313 contentPanePrivate.updateUI();
314
315 }
316
317 /**
318 * Add a new layer to the map. If no map exists, create one.
319 */
320 public final void addLayer(final Layer layer) {
321 if (map == null) {
322 final MapFrame mapFrame = new MapFrame(contentPanePrivate);
323 setMapFrame(mapFrame);
324 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction(), layer);
325 mapFrame.setVisible(true);
326 mapFrame.initializeDialogsPane();
327 // bootstrapping problem: make sure the layer list dialog is going to
328 // listen to change events of the very first layer
329 //
330 layer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
331 }
332 map.mapView.addLayer(layer);
333 }
334
335 /**
336 * Replies true if there is an edit layer
337 *
338 * @return true if there is an edit layer
339 */
340 public boolean hasEditLayer() {
341 if (getEditLayer() == null) return false;
342 return true;
343 }
344
345 /**
346 * Replies the current edit layer
347 *
348 * @return the current edit layer. null, if no current edit layer exists
349 */
350 public OsmDataLayer getEditLayer() {
351 if (map == null) return null;
352 if (map.mapView == null) return null;
353 return map.mapView.getEditLayer();
354 }
355
356 /**
357 * Replies the current data set.
358 *
359 * @return the current data set. null, if no current data set exists
360 */
361 public DataSet getCurrentDataSet() {
362 if (!hasEditLayer()) return null;
363 return getEditLayer().data;
364 }
365
366 /**
367 * Returns the currently active layer
368 *
369 * @return the currently active layer. null, if currently no active layer exists
370 */
371 public Layer getActiveLayer() {
372 if (map == null) return null;
373 if (map.mapView == null) return null;
374 return map.mapView.getActiveLayer();
375 }
376
377 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
378
379 public static void redirectToMainContentPane(JComponent source) {
380 RedirectInputMap.redirect(source, contentPanePrivate);
381 }
382
383 public static void registerActionShortcut(Action action, Shortcut shortcut) {
384 KeyStroke keyStroke = shortcut.getKeyStroke();
385 if (keyStroke == null)
386 return;
387
388 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
389 Object existing = inputMap.get(keyStroke);
390 if (existing != null && !existing.equals(action)) {
391 System.out.println(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
392 }
393 inputMap.put(keyStroke, action);
394
395 contentPanePrivate.getActionMap().put(action, action);
396 }
397
398 public static void unregisterActionShortcut(Shortcut shortcut) {
399 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
400 }
401
402 public static void unregisterActionShortcut(JosmAction action) {
403 unregisterActionShortcut(action, action.getShortcut());
404 }
405
406 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
407 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
408 contentPanePrivate.getActionMap().remove(action);
409 }
410
411 ///////////////////////////////////////////////////////////////////////////
412 // Implementation part
413 ///////////////////////////////////////////////////////////////////////////
414
415 public static final JPanel panel = new JPanel(new BorderLayout());
416
417 protected static WindowGeometry geometry;
418 protected static int windowState = JFrame.NORMAL;
419
420 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
421 public void commandChanged(final int queueSize, final int redoSize) {
422 menu.undo.setEnabled(queueSize > 0);
423 menu.redo.setEnabled(redoSize > 0);
424 }
425 };
426
427 /**
428 * Should be called before the main constructor to setup some parameter stuff
429 * @param args The parsed argument list.
430 */
431 public static void preConstructorInit(Map<String, Collection<String>> args) {
432 ProjectionPreference.setProjection();
433
434 try {
435 String defaultlaf = platform.getDefaultStyle();
436 String laf = Main.pref.get("laf", defaultlaf);
437 try {
438 UIManager.setLookAndFeel(laf);
439 }
440 catch (final java.lang.ClassNotFoundException e) {
441 System.out.println("Look and Feel not found: " + laf);
442 Main.pref.put("laf", defaultlaf);
443 }
444 catch (final javax.swing.UnsupportedLookAndFeelException e) {
445 System.out.println("Look and Feel not supported: " + laf);
446 Main.pref.put("laf", defaultlaf);
447 }
448 toolbar = new ToolbarPreferences();
449 contentPanePrivate.updateUI();
450 panel.updateUI();
451 } catch (final Exception e) {
452 e.printStackTrace();
453 }
454 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
455 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
456 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
457 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
458
459 I18n.translateJavaInternalMessages();
460
461 // init default coordinate format
462 //
463 try {
464 //CoordinateFormat format = CoordinateFormat.valueOf(Main.pref.get("coordinates"));
465 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
466 } catch (IllegalArgumentException iae) {
467 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
468 }
469
470 geometry = WindowGeometry.mainWindow("gui.geometry",
471 (args.containsKey("geometry") ? args.get("geometry").iterator().next() : null),
472 !args.containsKey("no-maximize"));
473 }
474
475 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
476 if (args.containsKey("download")) {
477 List<File> fileList = new ArrayList<File>();
478 for (String s : args.get("download")) {
479 File f = null;
480 switch(paramType(s)) {
481 case httpUrl:
482 downloadFromParamHttp(false, s);
483 break;
484 case bounds:
485 downloadFromParamBounds(false, s);
486 break;
487 case fileUrl:
488 try {
489 f = new File(new URI(s));
490 } catch (URISyntaxException e) {
491 JOptionPane.showMessageDialog(
492 Main.parent,
493 tr("Ignoring malformed file URL: \"{0}\"", s),
494 tr("Warning"),
495 JOptionPane.WARNING_MESSAGE
496 );
497 }
498 if (f!=null) {
499 fileList.add(f);
500 }
501 break;
502 case fileName:
503 f = new File(s);
504 fileList.add(f);
505 break;
506 }
507 }
508 if(!fileList.isEmpty())
509 {
510 OpenFileAction.openFiles(fileList, true);
511 }
512 }
513 if (args.containsKey("downloadgps")) {
514 for (String s : args.get("downloadgps")) {
515 switch(paramType(s)) {
516 case httpUrl:
517 downloadFromParamHttp(true, s);
518 break;
519 case bounds:
520 downloadFromParamBounds(true, s);
521 break;
522 case fileUrl:
523 case fileName:
524 JOptionPane.showMessageDialog(
525 Main.parent,
526 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
527 tr("Warning"),
528 JOptionPane.WARNING_MESSAGE
529 );
530 }
531 }
532 }
533 if (args.containsKey("selection")) {
534 for (String s : args.get("selection")) {
535 SearchAction.search(s, SearchAction.SearchMode.add);
536 }
537 }
538 }
539
540 public static boolean saveUnsavedModifications() {
541 if (map == null) return true;
542 SaveLayersDialog dialog = new SaveLayersDialog(Main.parent);
543 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
544 for (OsmDataLayer l: Main.map.mapView.getLayersOfType(OsmDataLayer.class)) {
545 if ((l.requiresSaveToFile() || l.requiresUploadToServer()) && l.data.isModified()) {
546 layersWithUnmodifiedChanges.add(l);
547 }
548 }
549 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
550 if (!layersWithUnmodifiedChanges.isEmpty()) {
551 dialog.getModel().populate(layersWithUnmodifiedChanges);
552 dialog.setVisible(true);
553 switch(dialog.getUserAction()) {
554 case CANCEL: return false;
555 case PROCEED: return true;
556 default: return false;
557 }
558 }
559
560 return true;
561 }
562
563 public static boolean exitJosm(boolean exit) {
564 if (Main.saveUnsavedModifications()) {
565 geometry.remember("gui.geometry");
566 if (map != null) {
567 map.rememberToggleDialogWidth();
568 }
569 pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
570 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
571 if (Main.isDisplayingMapView()) {
572 Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
573 for (Layer l: layers) {
574 Main.map.mapView.removeLayer(l);
575 }
576 }
577 if (exit) {
578 System.exit(0);
579 return true;
580 } else
581 return true;
582 } else
583 return false;
584 }
585
586 /**
587 * The type of a command line parameter, to be used in switch statements.
588 * @see paramType
589 */
590 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
591
592 /**
593 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
594 * @param s A parameter string
595 * @return The guessed parameter type
596 */
597 private DownloadParamType paramType(String s) {
598 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
599 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
600 String coorPattern = "\\s*[0-9]+(\\.[0-9]+)?\\s*";
601 if(s.matches(coorPattern+"(,"+coorPattern+"){3}")) return DownloadParamType.bounds;
602 // everything else must be a file name
603 return DownloadParamType.fileName;
604 }
605
606 /**
607 * Download area specified on the command line as OSM URL.
608 * @param rawGps Flag to download raw GPS tracks
609 * @param s The URL parameter
610 */
611 private static void downloadFromParamHttp(final boolean rawGps, String s) {
612 final Bounds b = OsmUrlToBounds.parse(s);
613 if (b == null) {
614 JOptionPane.showMessageDialog(
615 Main.parent,
616 tr("Ignoring malformed URL: \"{0}\"", s),
617 tr("Warning"),
618 JOptionPane.WARNING_MESSAGE
619 );
620 } else {
621 downloadFromParamBounds(rawGps, b);
622 }
623 }
624
625 /**
626 * Download area specified on the command line as bounds string.
627 * @param rawGps Flag to download raw GPS tracks
628 * @param s The bounds parameter
629 */
630 private static void downloadFromParamBounds(final boolean rawGps, String s) {
631 final StringTokenizer st = new StringTokenizer(s, ",");
632 if (st.countTokens() == 4) {
633 Bounds b = new Bounds(
634 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
635 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
636 );
637 downloadFromParamBounds(rawGps, b);
638 }
639 }
640
641 /**
642 * Download area specified as Bounds value.
643 * @param rawGps Flag to download raw GPS tracks
644 * @param b The bounds value
645 * @see downloadFromParamBounds(final boolean rawGps, String s)
646 * @see downloadFromParamHttp
647 */
648 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
649 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
650 // asynchronously launch the download task ...
651 Future<?> future = task.download(true, b, null);
652 // ... and the continuation when the download is finished (this will wait for the download to finish)
653 Main.worker.execute(new PostDownloadHandler(task, future));
654 }
655
656 public static void determinePlatformHook() {
657 String os = System.getProperty("os.name");
658 if (os == null) {
659 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
660 platform = new PlatformHookUnixoid();
661 } else if (os.toLowerCase().startsWith("windows")) {
662 platform = new PlatformHookWindows();
663 } else if (os.equals("Linux") || os.equals("Solaris") ||
664 os.equals("SunOS") || os.equals("AIX") ||
665 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
666 platform = new PlatformHookUnixoid();
667 } else if (os.toLowerCase().startsWith("mac os x")) {
668 platform = new PlatformHookOsx();
669 } else {
670 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
671 platform = new PlatformHookUnixoid();
672 }
673 }
674
675 private static class WindowPositionSizeListener extends WindowAdapter implements
676 ComponentListener {
677 @Override
678 public void windowStateChanged(WindowEvent e) {
679 Main.windowState = e.getNewState();
680 }
681
682 @Override
683 public void componentHidden(ComponentEvent e) {
684 }
685
686 @Override
687 public void componentMoved(ComponentEvent e) {
688 handleComponentEvent(e);
689 }
690
691 @Override
692 public void componentResized(ComponentEvent e) {
693 handleComponentEvent(e);
694 }
695
696 @Override
697 public void componentShown(ComponentEvent e) {
698 }
699
700 private void handleComponentEvent(ComponentEvent e) {
701 Component c = e.getComponent();
702 if (c instanceof JFrame && c.isVisible() && Main.windowState == JFrame.NORMAL) {
703 Main.geometry = new WindowGeometry((JFrame) c);
704 }
705 }
706 }
707 public static void addListener() {
708 parent.addComponentListener(new WindowPositionSizeListener());
709 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
710 }
711
712 public static void checkJava6() {
713 String version = System.getProperty("java.version");
714 if (version != null) {
715 if (version.startsWith("1.6") || version.startsWith("6") ||
716 version.startsWith("1.7") || version.startsWith("7"))
717 return;
718 if (version.startsWith("1.5") || version.startsWith("5")) {
719 JLabel ho = new JLabel("<html>"+
720 tr("<h2>JOSM requires Java version 6.</h2>"+
721 "Detected Java version: {0}.<br>"+
722 "You can <ul><li>update your Java (JRE) or</li>"+
723 "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
724 "More Info:", version)+"</html>");
725 JTextArea link = new JTextArea("http://josm.openstreetmap.de/wiki/Help/SystemRequirements");
726 link.setEditable(false);
727 link.setBackground(panel.getBackground());
728 JPanel panel = new JPanel(new GridBagLayout());
729 GridBagConstraints gbc = new GridBagConstraints();
730 gbc.gridwidth = GridBagConstraints.REMAINDER;
731 gbc.anchor = GridBagConstraints.WEST;
732 gbc.weightx = 1.0;
733 panel.add(ho, gbc);
734 panel.add(link, gbc);
735 final String EXIT = tr("Exit JOSM");
736 final String CONTINUE = tr("Continue, try anyway");
737 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
738 if (ret == 0) {
739 System.exit(0);
740 }
741 return;
742 }
743 }
744 System.err.println("Error: Could not recognize Java Version: "+version);
745 }
746
747 /* ----------------------------------------------------------------------------------------- */
748 /* projection handling - Main is a registry for a single, global projection instance */
749 /* */
750 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
751 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
752 /* ----------------------------------------------------------------------------------------- */
753 /**
754 * The projection method used.
755 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
756 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
757 */
758 private static Projection proj;
759
760 /**
761 * Replies the current projection.
762 *
763 * @return
764 */
765 public static Projection getProjection() {
766 return proj;
767 }
768
769 /**
770 * Sets the current projection
771 *
772 * @param p the projection
773 */
774 public static void setProjection(Projection p) {
775 CheckParameterUtil.ensureParameterNotNull(p);
776 Projection oldValue = proj;
777 proj = p;
778 fireProjectionChanged(oldValue, proj);
779 }
780
781 /*
782 * Keep WeakReferences to the listeners. This relieves clients from the burden of
783 * explicitly removing the listeners and allows us to transparently register every
784 * created dataset as projection change listener.
785 */
786 private static final ArrayList<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
787
788 private static void fireProjectionChanged(Projection oldValue, Projection newValue) {
789 if (newValue == null ^ oldValue == null
790 || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
791
792 synchronized(Main.class) {
793 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
794 while(it.hasNext()){
795 WeakReference<ProjectionChangeListener> wr = it.next();
796 ProjectionChangeListener listener = wr.get();
797 if (listener == null) {
798 it.remove();
799 continue;
800 }
801 listener.projectionChanged(oldValue, newValue);
802 }
803 }
804 if (newValue != null) {
805 Bounds b = (Main.map != null && Main.map.mapView != null) ? Main.map.mapView.getRealBounds() : null;
806 if (b != null){
807 Main.map.mapView.zoomTo(b);
808 }
809 }
810 /* TODO - remove layers with fixed projection */
811 }
812 }
813
814 /**
815 * Register a projection change listener
816 *
817 * @param listener the listener. Ignored if null.
818 */
819 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
820 if (listener == null) return;
821 synchronized (Main.class) {
822 for (WeakReference<ProjectionChangeListener> wr : listeners) {
823 // already registered ? => abort
824 if (wr.get() == listener) return;
825 }
826 listeners.add(new WeakReference<ProjectionChangeListener>(listener));
827 }
828 }
829
830 /**
831 * Removes a projection change listener
832 *
833 * @param listener the listener. Ignored if null.
834 */
835 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
836 if (listener == null) return;
837 synchronized(Main.class){
838 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
839 while(it.hasNext()){
840 WeakReference<ProjectionChangeListener> wr = it.next();
841 // remove the listener - and any other listener which god garbage
842 // collected in the meantime
843 if (wr.get() == null || wr.get() == listener) {
844 it.remove();
845 }
846 }
847 }
848 }
849}
Note: See TracBrowser for help on using the repository browser.