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

Last change on this file since 3965 was 3956, checked in by bastiK, 13 years ago

Turn off the new features introduced in [3934] for now. There are still minor technical problems (see #6037) and a release is due.

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