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

Last change on this file since 4175 was 4126, checked in by bastiK, 13 years ago

memory optimizations for Node & WayPoint (Patch by Gubaer, modified)

The field 'proj' in CachedLatLon is a waste of memory. For the 2 classes where this has the greatest impact, the cache for the projected coordinates is replaced by 2 simple double fields (east & north). On projection change, they have to be invalidated explicitly. This is handled by the DataSet & the GpxLayer.

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