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

Last change on this file since 1849 was 1849, checked in by stoecker, 15 years ago

fix #3084 - patch by Pieren

  • 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
223 *
224 * @return true if there is an edit layer
225 */
226 public boolean hasEditLayer() {
227 if (map == null) return false;
228 if (map.mapView == null) return false;
229 if (map.mapView.getEditLayer() == null) return false;
230 return true;
231 }
232
233 /**
234 * Replies the current edit layer
235 *
236 * @return the current edit layer. null, if no current edit layer exists
237 */
238 public OsmDataLayer getEditLayer() {
239 if (map == null) return null;
240 if (map.mapView == null) return null;
241 return map.mapView.getEditLayer();
242 }
243
244 /**
245 * Replies the current data set.
246 *
247 * @return the current data set. null, if no current data set exists
248 */
249 public DataSet getCurrentDataSet() {
250 if (!hasEditLayer()) return null;
251 return getEditLayer().data;
252 }
253
254 /**
255 * Use this to register shortcuts to
256 */
257 public static final JPanel contentPane = new JPanel(new BorderLayout());
258
259 ///////////////////////////////////////////////////////////////////////////
260 // Implementation part
261 ///////////////////////////////////////////////////////////////////////////
262
263 public static JPanel panel = new JPanel(new BorderLayout());
264
265 protected static Rectangle bounds;
266
267 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
268 public void commandChanged(final int queueSize, final int redoSize) {
269 menu.undo.setEnabled(queueSize > 0);
270 menu.redo.setEnabled(redoSize > 0);
271 }
272 };
273
274 static public void setProjection(String name)
275 {
276 Bounds b = (map != null && map.mapView != null) ? map.mapView.getRealBounds() : null;
277 Projection oldProj = Main.proj;
278 try {
279 Main.proj = (Projection)Class.forName(name).newInstance();
280 } catch (final Exception e) {
281 JOptionPane.showMessageDialog(null, tr("The projection {0} could not be activated. Using Mercator", name));
282 Main.proj = new Mercator();
283 }
284 if(!Main.proj.equals(oldProj))
285 {
286 if(b != null) {
287 map.mapView.zoomTo(b);
288 /* TODO - remove layers with fixed projection */
289 }
290 }
291 }
292
293 /**
294 * Should be called before the main constructor to setup some parameter stuff
295 * @param args The parsed argument list.
296 */
297 public static void preConstructorInit(Map<String, Collection<String>> args) {
298 setProjection(Main.pref.get("projection", Mercator.class.getName()));
299
300 try {
301 try {
302 String laf = Main.pref.get("laf");
303 if(laf != null && laf.length() > 0) {
304 UIManager.setLookAndFeel(laf);
305 }
306 }
307 catch (final javax.swing.UnsupportedLookAndFeelException e) {
308 System.out.println("Look and Feel not supported: " + Main.pref.get("laf"));
309 }
310 toolbar = new ToolbarPreferences();
311 contentPane.updateUI();
312 panel.updateUI();
313 } catch (final Exception e) {
314 e.printStackTrace();
315 }
316 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
317 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
318 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
319 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
320
321 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
322 String geometry = Main.pref.get("gui.geometry");
323 if (args.containsKey("geometry")) {
324 geometry = args.get("geometry").iterator().next();
325 }
326 if (geometry.length() != 0) {
327 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
328 if (m.matches()) {
329 int w = Integer.valueOf(m.group(1));
330 int h = Integer.valueOf(m.group(2));
331 int x = 0, y = 0;
332 if (m.group(3) != null) {
333 x = Integer.valueOf(m.group(5));
334 y = Integer.valueOf(m.group(7));
335 if (m.group(4).equals("-")) {
336 x = screenDimension.width - x - w;
337 }
338 if (m.group(6).equals("-")) {
339 y = screenDimension.height - y - h;
340 }
341 }
342 bounds = new Rectangle(x,y,w,h);
343 if(!Main.pref.get("gui.geometry").equals(geometry)) {
344 // remember this geometry
345 Main.pref.put("gui.geometry", geometry);
346 }
347 } else {
348 System.out.println("Ignoring malformed geometry: "+geometry);
349 }
350 }
351 if (bounds == null) {
352 bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
353 }
354 }
355
356 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
357 if (args.containsKey("download")) {
358 for (String s : args.get("download")) {
359 downloadFromParamString(false, s);
360 }
361 }
362 if (args.containsKey("downloadgps")) {
363 for (String s : args.get("downloadgps")) {
364 downloadFromParamString(true, s);
365 }
366 }
367 if (args.containsKey("selection")) {
368 for (String s : args.get("selection")) {
369 SearchAction.search(s, SearchAction.SearchMode.add, false, false);
370 }
371 }
372 }
373
374 public static boolean breakBecauseUnsavedChanges() {
375 Shortcut.savePrefs();
376 if (map != null) {
377 boolean modified = false;
378 boolean uploadedModified = false;
379 for (final Layer l : map.mapView.getAllLayers()) {
380 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
381 modified = true;
382 uploadedModified = ((OsmDataLayer)l).uploadedModified;
383 break;
384 }
385 }
386 if (modified) {
387 final String msg = uploadedModified ? "\n"
388 +tr("Hint: Some changes came from uploading new data to the server.") : "";
389 int result = new ExtendedDialog(parent, tr("Unsaved Changes"),
390 new javax.swing.JLabel(tr("There are unsaved changes. Discard the changes and continue?")+msg),
391 new String[] {tr("Save and Exit"), tr("Discard and Exit"), tr("Cancel")},
392 new String[] {"save.png", "exit.png", "cancel.png"}).getValue();
393
394 // Save before exiting
395 if(result == 1) {
396 Boolean savefailed = false;
397 for (final Layer l : map.mapView.getAllLayers()) {
398 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
399 SaveAction save = new SaveAction();
400 if(!save.doSave(l)) {
401 savefailed = true;
402 }
403 }
404 }
405 return savefailed;
406 }
407 else if(result != 2) // Cancel exiting unless the 2nd button was clicked
408 return true;
409 }
410 }
411 return false;
412 }
413
414 private static void downloadFromParamString(final boolean rawGps, String s) {
415 if (s.startsWith("http:")) {
416 final Bounds b = OsmUrlToBounds.parse(s);
417 if (b == null) {
418 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed URL: \"{0}\"", s));
419 } else {
420 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
421 DownloadTask osmTask = new DownloadOsmTask();
422 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon(), null);
423 }
424 return;
425 }
426
427 if (s.startsWith("file:")) {
428 try {
429 main.menu.openFile.openFile(new File(new URI(s)));
430 } catch (URISyntaxException e) {
431 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file URL: \"{0}\"", s));
432 }
433 return;
434 }
435
436 final StringTokenizer st = new StringTokenizer(s, ",");
437 if (st.countTokens() == 4) {
438 try {
439 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
440 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), null);
441 return;
442 } catch (final NumberFormatException e) {
443 }
444 }
445
446 main.menu.openFile.openFile(new File(s));
447 }
448
449 public static void determinePlatformHook() {
450 String os = System.getProperty("os.name");
451 if (os == null) {
452 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
453 platform = new PlatformHookUnixoid();
454 } else if (os.toLowerCase().startsWith("windows")) {
455 platform = new PlatformHookWindows();
456 } else if (os.equals("Linux") || os.equals("Solaris") ||
457 os.equals("SunOS") || os.equals("AIX") ||
458 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
459 platform = new PlatformHookUnixoid();
460 } else if (os.toLowerCase().startsWith("mac os x")) {
461 platform = new PlatformHookOsx();
462 } else {
463 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
464 platform = new PlatformHookUnixoid();
465 }
466 }
467
468 static public void saveGuiGeometry() {
469 // save the current window geometry
470 String newGeometry = "";
471 try {
472 if (((JFrame)parent).getExtendedState() == JFrame.NORMAL) {
473 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
474 Rectangle bounds = parent.getBounds();
475 int width = (int)bounds.getWidth();
476 int height = (int)bounds.getHeight();
477 int x = (int)bounds.getX();
478 int y = (int)bounds.getY();
479 if (width > screenDimension.width) {
480 width = screenDimension.width;
481 }
482 if (height > screenDimension.height) {
483 width = screenDimension.height;
484 }
485 if (x < 0) {
486 x = 0;
487 }
488 if (y < 0) {
489 y = 0;
490 }
491 newGeometry = width + "x" + height + "+" + x + "+" + y;
492 }
493 }
494 catch (Exception e) {
495 System.out.println("Failed to save GUI geometry: " + e);
496 }
497 pref.put("gui.geometry", newGeometry);
498 }
499
500
501}
Note: See TracBrowser for help on using the repository browser.