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

Last change on this file since 2719 was 2715, checked in by stoecker, 14 years ago

fixed #3772, #4139 - fixed help browser - the external start never worked for official releases, the blocking of helpbrowser for dialogs will be fixed after Java 1.6 switch

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