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

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

see #3550 - fixed resizable side views - patch by bastiK

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