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

Last change on this file since 2875 was 2869, checked in by jttt, 14 years ago

Removed ToggleDialog.tearDown(). All listeners should be unregistered in hideNotify()

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