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

Last change on this file since 1923 was 1895, checked in by Gubaer, 15 years ago

new: only one list of layers managed by MapView. LayerListDialog is an adapter to this list.
improved delete confirmation for multi layer delete
various bug fixes in the new LayerListDialog

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