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

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

removed dependencies to Main.ds, removed Main.ds
removed AddVisitor, NameVisitor, DeleteVisitor - unnecessary double dispatching for these simple cases

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