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

Last change on this file since 4567 was 4567, checked in by stoecker, 12 years ago

fix #6875 - patch by Larry0ua - Data Layer can be changed after selecting another layer

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