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

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

fixed #3324: Loading a File -> status message

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