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

Last change on this file since 2318 was 2305, checked in by jttt, 14 years ago

Use PrimitiveData for Copy, Paste and Paste tags actions

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