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

Last change on this file since 2817 was 2817, checked in by Gubaer, 14 years ago

fixed #3063: Downloading a plugin yields 3 dialogs at the same time: Downloading plugin / You should restart JOSM / Plugin downloaded
fixed #3628: JOSM blocking itself updating broken plugin
fixed #4187: JOSM deleted random files from disk after start (data loss)
fixed #4199: new version - plugins update vs josm start [should be fixed. Be careful if you have two JOSM instances running. Auto-update of plugins in the second instance will fail because plugin files are locked by the first instance]
fixed #4034: JOSM should auto-download plugin list when it hasn't been downloaded before [JOSM now displays a hint]

fixed: splash screen showing again even if plugins are auto-updated
new: progress indication integrated in splash screen
new: cancelable, asynchronous download of plugins from preferences
new: cancelable, asynchronous download of plugin list from plugin download sites
new: asynchronous loading of plugin information, launch of preferences dialog accelerated
refactored: clean up, documentation of plugin management code (PluginHandler)

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