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

Last change on this file since 2657 was 2613, checked in by Gubaer, 14 years ago

new: global in-memory cache for downloaded changesets
new: toggle dialog for changesets
new: downloading of changesets (currently without changeset content, will follow later)

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