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

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

replaced JOptionDialog.show... by OptionPaneUtil.show....
improved relation editor

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