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

Last change on this file since 3102 was 3071, checked in by mjulius, 14 years ago

fixes #4648 - User panel not showing data when toggled from hidden to shown

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