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

Last change on this file since 4190 was 4190, checked in by stoecker, 13 years ago

add more output function in main, we should use these instead of System.out.println()

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