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

Last change on this file since 2876 was 2876, checked in by bastiK, 14 years ago

fix #3745 - fullscreen geometry not restored (patch by bomm)

  • Property svn:eol-style set to native
File size: 23.4 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm;
3import static org.openstreetmap.josm.tools.I18n.tr;
4
5import java.awt.BorderLayout;
6import java.awt.Component;
7import java.awt.Dimension;
8import java.awt.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 * Set or clear (if passed <code>null</code>) the map.
158 */
159 public final void setMapFrame(final MapFrame map) {
160 MapFrame old = Main.map;
161 panel.setVisible(false);
162 panel.removeAll();
163 if (map != null) {
164 map.fillPanel(panel);
165 } else {
166 old.destroy();
167 panel.add(gettingStarted, BorderLayout.CENTER);
168 }
169 panel.setVisible(true);
170 redoUndoListener.commandChanged(0,0);
171
172 Main.map = map;
173
174 PluginHandler.notifyMapFrameChanged(old, map);
175 }
176
177 /**
178 * Remove the specified layer from the map. If it is the last layer,
179 * remove the map as well.
180 */
181 public final void removeLayer(final Layer layer) {
182 if (map != null) {
183 map.mapView.removeLayer(layer);
184 if (map.mapView.getAllLayers().isEmpty()) {
185 setMapFrame(null);
186 }
187 }
188 }
189
190 public Main() {
191 main = this;
192 // platform = determinePlatformHook();
193 platform.startupHook();
194 contentPane.add(panel, BorderLayout.CENTER);
195 panel.add(gettingStarted, BorderLayout.CENTER);
196 menu = new MainMenu();
197
198 undoRedo.listenerCommands.add(redoUndoListener);
199
200 // creating toolbar
201 contentPane.add(toolbar.control, BorderLayout.NORTH);
202
203 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
204 .put(Shortcut.registerShortcut("system:help", tr("Help"),
205 KeyEvent.VK_F1, Shortcut.GROUP_DIRECT).getKeyStroke(), "Help");
206 contentPane.getActionMap().put("Help", menu.help);
207
208 TaggingPresetPreference.initialize();
209 MapPaintPreference.initialize();
210
211 toolbar.refreshToolbarControl();
212
213 toolbar.control.updateUI();
214 contentPane.updateUI();
215 }
216
217 /**
218 * Add a new layer to the map. If no map exists, create one.
219 */
220 public final void addLayer(final Layer layer) {
221 if (map == null) {
222 final MapFrame mapFrame = new MapFrame();
223 setMapFrame(mapFrame);
224 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
225 mapFrame.setVisible(true);
226 mapFrame.initializeDialogsPane();
227 // bootstrapping problem: make sure the layer list dialog is going to
228 // listen to change events of the very first layer
229 //
230 layer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
231 }
232 map.mapView.addLayer(layer);
233 }
234
235 /**
236 * Replies true if there is an edit layer
237 *
238 * @return true if there is an edit layer
239 */
240 public boolean hasEditLayer() {
241 if (map == null) return false;
242 if (map.mapView == null) return false;
243 if (map.mapView.getEditLayer() == null) return false;
244 return true;
245 }
246
247 /**
248 * Replies the current edit layer
249 *
250 * @return the current edit layer. null, if no current edit layer exists
251 */
252 public OsmDataLayer getEditLayer() {
253 if (map == null) return null;
254 if (map.mapView == null) return null;
255 return map.mapView.getEditLayer();
256 }
257
258 /**
259 * Replies the current data set.
260 *
261 * @return the current data set. null, if no current data set exists
262 */
263 public DataSet getCurrentDataSet() {
264 if (!hasEditLayer()) return null;
265 return getEditLayer().data;
266 }
267
268 /**
269 * Use this to register shortcuts to
270 */
271 public static final JPanel contentPane = new JPanel(new BorderLayout());
272
273 ///////////////////////////////////////////////////////////////////////////
274 // Implementation part
275 ///////////////////////////////////////////////////////////////////////////
276
277 public static JPanel panel = new JPanel(new BorderLayout());
278
279 protected static Rectangle bounds;
280 protected static int windowState = JFrame.NORMAL;
281
282 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
283 public void commandChanged(final int queueSize, final int redoSize) {
284 menu.undo.setEnabled(queueSize > 0);
285 menu.redo.setEnabled(redoSize > 0);
286 }
287 };
288
289 /**
290 * Should be called before the main constructor to setup some parameter stuff
291 * @param args The parsed argument list.
292 */
293 public static void preConstructorInit(Map<String, Collection<String>> args) {
294 ProjectionPreference.setProjection();
295
296 try {
297 String defaultlaf = platform.getDefaultStyle();
298 String laf = Main.pref.get("laf", defaultlaf);
299 try {
300 UIManager.setLookAndFeel(laf);
301 }
302 catch (final java.lang.ClassNotFoundException e) {
303 System.out.println("Look and Feel not found: " + laf);
304 Main.pref.put("laf", defaultlaf);
305 }
306 catch (final javax.swing.UnsupportedLookAndFeelException e) {
307 System.out.println("Look and Feel not supported: " + laf);
308 Main.pref.put("laf", defaultlaf);
309 }
310 toolbar = new ToolbarPreferences();
311 contentPane.updateUI();
312 panel.updateUI();
313 } catch (final Exception e) {
314 e.printStackTrace();
315 }
316 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
317 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
318 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
319 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
320
321 // init default coordinate format
322 //
323 try {
324 //CoordinateFormat format = CoordinateFormat.valueOf(Main.pref.get("coordinates"));
325 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
326 } catch (IllegalArgumentException iae) {
327 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
328 }
329
330 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
331 String geometry = null;
332 if (args.containsKey("geometry")) {
333 geometry = args.get("geometry").iterator().next();
334 // Main.debug("Main window geometry from args: \""+geometry+"\"");
335 } else {
336 geometry = Main.pref.get("gui.geometry");
337 // Main.debug("Main window geometry from preferences: \""+geometry+"\"");
338 }
339 if (geometry.length() != 0) {
340 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
341 if (m.matches()) {
342 int w = Integer.valueOf(m.group(1));
343 int h = Integer.valueOf(m.group(2));
344 int x = 0, y = 0;
345 if (m.group(3) != null) {
346 x = Integer.valueOf(m.group(5));
347 y = Integer.valueOf(m.group(7));
348 if (m.group(4).equals("-")) {
349 x = screenDimension.width - x - w;
350 }
351 if (m.group(6).equals("-")) {
352 y = screenDimension.height - y - h;
353 }
354 }
355 // copied from WindowsGeometry.applySafe()
356 if (x > Toolkit.getDefaultToolkit().getScreenSize().width - 10) {
357 x = 0;
358 }
359 if (y > Toolkit.getDefaultToolkit().getScreenSize().height - 10) {
360 y = 0;
361 }
362 bounds = new Rectangle(x,y,w,h);
363 if(!Main.pref.get("gui.geometry").equals(geometry)) {
364 // remember this geometry
365 // Main.debug("Main window: saving geometry \"" + geometry + "\"");
366 Main.pref.put("gui.geometry", geometry);
367 }
368 } else {
369 System.out.println("Ignoring malformed geometry: "+geometry);
370 }
371 }
372 if (bounds == null) {
373 bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
374 }
375 // Main.debug("window geometry: "+bounds);
376 }
377
378 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
379 if (args.containsKey("download")) {
380 List<File> fileList = new ArrayList<File>();
381 for (String s : args.get("download")) {
382 File f = null;
383 switch(paramType(s)) {
384 case httpUrl:
385 downloadFromParamHttp(false, s);
386 break;
387 case bounds:
388 downloadFromParamBounds(false, s);
389 break;
390 case fileUrl:
391 try {
392 f = new File(new URI(s));
393 } catch (URISyntaxException e) {
394 JOptionPane.showMessageDialog(
395 Main.parent,
396 tr("Ignoring malformed file URL: \"{0}\"", s),
397 tr("Warning"),
398 JOptionPane.WARNING_MESSAGE
399 );
400 }
401 if (f!=null) {
402 fileList.add(f);
403 }
404 break;
405 case fileName:
406 f = new File(s);
407 fileList.add(f);
408 break;
409 }
410 }
411 if(!fileList.isEmpty())
412 {
413 OpenFileAction.openFiles(fileList);
414 }
415 }
416 if (args.containsKey("downloadgps")) {
417 for (String s : args.get("downloadgps")) {
418 switch(paramType(s)) {
419 case httpUrl:
420 downloadFromParamHttp(true, s);
421 break;
422 case bounds:
423 downloadFromParamBounds(true, s);
424 break;
425 case fileUrl:
426 case fileName:
427 JOptionPane.showMessageDialog(
428 Main.parent,
429 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
430 tr("Warning"),
431 JOptionPane.WARNING_MESSAGE
432 );
433 }
434 }
435 }
436 if (args.containsKey("selection")) {
437 for (String s : args.get("selection")) {
438 SearchAction.search(s, SearchAction.SearchMode.add, false, false);
439 }
440 }
441 }
442
443 public static boolean saveUnsavedModifications() {
444 if (map == null) return true;
445 SaveLayersDialog dialog = new SaveLayersDialog(Main.parent);
446 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
447 for (OsmDataLayer l: Main.map.mapView.getLayersOfType(OsmDataLayer.class)) {
448 if (l.requiresSaveToFile() || l.requiresUploadToServer()) {
449 layersWithUnmodifiedChanges.add(l);
450 }
451 }
452 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
453 if (!layersWithUnmodifiedChanges.isEmpty()) {
454 dialog.getModel().populate(layersWithUnmodifiedChanges);
455 dialog.setVisible(true);
456 switch(dialog.getUserAction()) {
457 case CANCEL: return false;
458 case PROCEED: return true;
459 default: return false;
460 }
461 }
462
463 return true;
464 }
465
466 /**
467 * The type of a command line parameter, to be used in switch statements.
468 * @see paramType
469 */
470 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
471
472 /**
473 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
474 * @param s A parameter string
475 * @return The guessed parameter type
476 */
477 private DownloadParamType paramType(String s) {
478 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
479 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
480 final StringTokenizer st = new StringTokenizer(s, ",");
481 // we assume a string with exactly 3 commas is a bounds parameter
482 if (st.countTokens() == 4) return DownloadParamType.bounds;
483 // everything else must be a file name
484 return DownloadParamType.fileName;
485 }
486
487 /**
488 * Download area specified on the command line as OSM URL.
489 * @param rawGps Flag to download raw GPS tracks
490 * @param s The URL parameter
491 */
492 private static void downloadFromParamHttp(final boolean rawGps, String s) {
493 final Bounds b = OsmUrlToBounds.parse(s);
494 if (b == null) {
495 JOptionPane.showMessageDialog(
496 Main.parent,
497 tr("Ignoring malformed URL: \"{0}\"", s),
498 tr("Warning"),
499 JOptionPane.WARNING_MESSAGE
500 );
501 } else {
502 downloadFromParamBounds(rawGps, b);
503 }
504 }
505
506 /**
507 * Download area specified on the command line as bounds string.
508 * @param rawGps Flag to download raw GPS tracks
509 * @param s The bounds parameter
510 */
511 private static void downloadFromParamBounds(final boolean rawGps, String s) {
512 final StringTokenizer st = new StringTokenizer(s, ",");
513 if (st.countTokens() == 4) {
514 Bounds b = new Bounds(
515 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
516 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
517 );
518 downloadFromParamBounds(rawGps, b);
519 }
520 }
521
522 /**
523 * Download area specified as Bounds value.
524 * @param rawGps Flag to download raw GPS tracks
525 * @param b The bounds value
526 * @see downloadFromParamBounds(final boolean rawGps, String s)
527 * @see downloadFromParamHttp
528 */
529 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
530 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
531 // asynchronously launch the download task ...
532 Future<?> future = task.download(true, b, null);
533 // ... and the continuation when the download is finished (this will wait for the download to finish)
534 Main.worker.execute(new PostDownloadHandler(task, future));
535 }
536
537 public static void determinePlatformHook() {
538 String os = System.getProperty("os.name");
539 if (os == null) {
540 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
541 platform = new PlatformHookUnixoid();
542 } else if (os.toLowerCase().startsWith("windows")) {
543 platform = new PlatformHookWindows();
544 } else if (os.equals("Linux") || os.equals("Solaris") ||
545 os.equals("SunOS") || os.equals("AIX") ||
546 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
547 platform = new PlatformHookUnixoid();
548 } else if (os.toLowerCase().startsWith("mac os x")) {
549 platform = new PlatformHookOsx();
550 } else {
551 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
552 platform = new PlatformHookUnixoid();
553 }
554 }
555
556 static public void saveGuiGeometry() {
557 // save the current window geometry and the width of the toggle dialog area
558 String newGeometry = "";
559 String newToggleDlgWidth = null;
560 try {
561 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
562 int width = (int)bounds.getWidth();
563 int height = (int)bounds.getHeight();
564 int x = (int)bounds.getX();
565 int y = (int)bounds.getY();
566 if (width > screenDimension.width) {
567 width = screenDimension.width;
568 }
569 if (height > screenDimension.height) {
570 width = screenDimension.height;
571 }
572 if (x < 0) {
573 x = 0;
574 }
575 if (y < 0) {
576 y = 0;
577 }
578 newGeometry = width + "x" + height + "+" + x + "+" + y;
579
580 if (map != null) {
581 newToggleDlgWidth = Integer.toString(map.getToggleDlgWidth());
582 if (newToggleDlgWidth.equals(Integer.toString(map.DEF_TOGGLE_DLG_WIDTH))) {
583 newToggleDlgWidth = "";
584 }
585 }
586 }
587 catch (Exception e) {
588 System.out.println("Failed to get GUI geometry: " + e);
589 e.printStackTrace();
590 }
591 boolean maximized = (windowState & JFrame.MAXIMIZED_BOTH) != 0;
592 // Main.debug("Main window: saving geometry \"" + newGeometry + "\" " + (maximized?"maximized":"normal"));
593 pref.put("gui.maximized", maximized);
594 pref.put("gui.geometry", newGeometry);
595 if (newToggleDlgWidth != null) {
596 pref.put("toggleDialogs.width", newToggleDlgWidth);
597 }
598 }
599 private static class WindowPositionSizeListener extends WindowAdapter implements
600 ComponentListener {
601
602 @Override
603 public void windowStateChanged(WindowEvent e) {
604 Main.windowState = e.getNewState();
605 // Main.debug("Main window state changed to " + Main.windowState);
606 }
607
608 public void componentHidden(ComponentEvent e) {
609 }
610
611 public void componentMoved(ComponentEvent e) {
612 handleComponentEvent(e);
613 }
614
615 public void componentResized(ComponentEvent e) {
616 handleComponentEvent(e);
617 }
618
619 public void componentShown(ComponentEvent e) {
620 }
621
622 private void handleComponentEvent(ComponentEvent e) {
623 Component c = e.getComponent();
624 if (c instanceof JFrame) {
625 if (Main.windowState == JFrame.NORMAL) {
626 Main.bounds = ((JFrame) c).getBounds();
627 // Main.debug("Main window: new geometry " + Main.bounds);
628 } else {
629 // Main.debug("Main window state is " + Main.windowState);
630 }
631 }
632 }
633
634 }
635 public static void addListener() {
636 parent.addComponentListener(new WindowPositionSizeListener());
637 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
638 }
639}
Note: See TracBrowser for help on using the repository browser.