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

Last change on this file since 2552 was 2512, checked in by stoecker, 14 years ago

i18n updated, fixed files to reduce problems when applying patches, fix #4017

  • 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.HelpBrowserProxy;
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 setMapFrame(null);
191 }
192 }
193 }
194
195 public Main() {
196 this(null);
197 }
198
199 public Main(SplashScreen splash) {
200 main = this;
201 // platform = determinePlatformHook();
202 platform.startupHook();
203 contentPane.add(panel, BorderLayout.CENTER);
204 panel.add(gettingStarted, BorderLayout.CENTER);
205
206 if(splash != null) {
207 splash.setStatus(tr("Creating main GUI"));
208 }
209 menu = new MainMenu();
210
211 undoRedo.listenerCommands.add(redoUndoListener);
212
213 // creating toolbar
214 contentPane.add(toolbar.control, BorderLayout.NORTH);
215
216 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
217 .put(Shortcut.registerShortcut("system:help", tr("Help"),
218 KeyEvent.VK_F1, Shortcut.GROUP_DIRECT).getKeyStroke(), "Help");
219 contentPane.getActionMap().put("Help", menu.help);
220
221 TaggingPresetPreference.initialize();
222 MapPaintPreference.initialize();
223
224 toolbar.refreshToolbarControl();
225
226 toolbar.control.updateUI();
227 contentPane.updateUI();
228 }
229
230 /**
231 * Add a new layer to the map. If no map exists, create one.
232 */
233 public final void addLayer(final Layer layer) {
234 if (map == null) {
235 final MapFrame mapFrame = new MapFrame();
236 setMapFrame(mapFrame);
237 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
238 mapFrame.setVisible(true);
239 mapFrame.initializeDialogsPane();
240 // bootstrapping problem: make sure the layer list dialog is going to
241 // listen to change events of the very first layer
242 //
243 layer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
244 }
245 map.mapView.addLayer(layer);
246 }
247
248 /**
249 * Replies true if there is an edit layer
250 *
251 * @return true if there is an edit layer
252 */
253 public boolean hasEditLayer() {
254 if (map == null) return false;
255 if (map.mapView == null) return false;
256 if (map.mapView.getEditLayer() == null) return false;
257 return true;
258 }
259
260 /**
261 * Replies the current edit layer
262 *
263 * @return the current edit layer. null, if no current edit layer exists
264 */
265 public OsmDataLayer getEditLayer() {
266 if (map == null) return null;
267 if (map.mapView == null) return null;
268 return map.mapView.getEditLayer();
269 }
270
271 /**
272 * Replies the current data set.
273 *
274 * @return the current data set. null, if no current data set exists
275 */
276 public DataSet getCurrentDataSet() {
277 if (!hasEditLayer()) return null;
278 return getEditLayer().data;
279 }
280
281 /**
282 * Use this to register shortcuts to
283 */
284 public static final JPanel contentPane = new JPanel(new BorderLayout());
285
286 ///////////////////////////////////////////////////////////////////////////
287 // Implementation part
288 ///////////////////////////////////////////////////////////////////////////
289
290 public static JPanel panel = new JPanel(new BorderLayout());
291
292 protected static Rectangle bounds;
293
294 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
295 public void commandChanged(final int queueSize, final int redoSize) {
296 menu.undo.setEnabled(queueSize > 0);
297 menu.redo.setEnabled(redoSize > 0);
298 }
299 };
300
301 /**
302 * Should be called before the main constructor to setup some parameter stuff
303 * @param args The parsed argument list.
304 */
305 public static void preConstructorInit(Map<String, Collection<String>> args) {
306 ProjectionPreference.setProjection();
307
308 try {
309 try {
310 String laf = Main.pref.get("laf", platform.getDefaultStyle());
311 if(laf != null && laf.length() > 0) {
312 UIManager.setLookAndFeel(laf);
313 }
314 }
315 catch (final javax.swing.UnsupportedLookAndFeelException e) {
316 System.out.println("Look and Feel not supported: " + Main.pref.get("laf"));
317 }
318 toolbar = new ToolbarPreferences();
319 contentPane.updateUI();
320 panel.updateUI();
321 } catch (final Exception e) {
322 e.printStackTrace();
323 }
324 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
325 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
326 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
327 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
328
329 // init default coordinate format
330 //
331 try {
332 //CoordinateFormat format = CoordinateFormat.valueOf(Main.pref.get("coordinates"));
333 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
334 } catch (IllegalArgumentException iae) {
335 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
336 }
337
338 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
339 String geometry = Main.pref.get("gui.geometry");
340 if (args.containsKey("geometry")) {
341 geometry = args.get("geometry").iterator().next();
342 }
343 if (geometry.length() != 0) {
344 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
345 if (m.matches()) {
346 int w = Integer.valueOf(m.group(1));
347 int h = Integer.valueOf(m.group(2));
348 int x = 0, y = 0;
349 if (m.group(3) != null) {
350 x = Integer.valueOf(m.group(5));
351 y = Integer.valueOf(m.group(7));
352 if (m.group(4).equals("-")) {
353 x = screenDimension.width - x - w;
354 }
355 if (m.group(6).equals("-")) {
356 y = screenDimension.height - y - h;
357 }
358 }
359 bounds = new Rectangle(x,y,w,h);
360 if(!Main.pref.get("gui.geometry").equals(geometry)) {
361 // remember this geometry
362 Main.pref.put("gui.geometry", geometry);
363 }
364 } else {
365 System.out.println("Ignoring malformed geometry: "+geometry);
366 }
367 }
368 if (bounds == null) {
369 bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
370 }
371 }
372
373 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
374 if (args.containsKey("download")) {
375 for (String s : args.get("download")) {
376 downloadFromParamString(false, s);
377 }
378 }
379 if (args.containsKey("downloadgps")) {
380 for (String s : args.get("downloadgps")) {
381 downloadFromParamString(true, s);
382 }
383 }
384 if (args.containsKey("selection")) {
385 for (String s : args.get("selection")) {
386 SearchAction.search(s, SearchAction.SearchMode.add, false, false);
387 }
388 }
389 }
390
391 /**
392 * Run any cleanup operation before exit
393 *
394 */
395 public static void cleanupBeforeExit() {
396 // try to close and exit the help browser running in another process
397 //
398 HelpBrowserProxy.getInstance().exit();
399 }
400
401 public static boolean saveUnsavedModifications() {
402 if (map == null) return true;
403 SaveLayersDialog dialog = new SaveLayersDialog(Main.parent);
404 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
405 for (OsmDataLayer l: Main.map.mapView.getLayersOfType(OsmDataLayer.class)) {
406 if (l.requiresSaveToFile() || l.requiresUploadToServer()) {
407 layersWithUnmodifiedChanges.add(l);
408 }
409 }
410 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
411 if (!layersWithUnmodifiedChanges.isEmpty()) {
412 dialog.getModel().populate(layersWithUnmodifiedChanges);
413 dialog.setVisible(true);
414 switch(dialog.getUserAction()) {
415 case CANCEL: return false;
416 case PROCEED: return true;
417 default: return false;
418 }
419 }
420
421 return true;
422 }
423
424 private static void downloadFromParamString(final boolean rawGps, String s) {
425 if (s.startsWith("http:")) {
426 final Bounds b = OsmUrlToBounds.parse(s);
427 if (b == null) {
428 JOptionPane.showMessageDialog(
429 Main.parent,
430 tr("Ignoring malformed URL: \"{0}\"", s),
431 tr("Warning"),
432 JOptionPane.WARNING_MESSAGE
433 );
434 } else {
435 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
436 DownloadTask osmTask = new DownloadOsmTask();
437 Future<?> future = osmTask.download(true, b, null);
438 Main.worker.submit(new PostDownloadHandler(osmTask, future));
439 }
440 return;
441 }
442
443 if (s.startsWith("file:")) {
444 File f = null;
445 try {
446 f = new File(new URI(s));
447 } catch (URISyntaxException e) {
448 JOptionPane.showMessageDialog(
449 Main.parent,
450 tr("Ignoring malformed file URL: \"{0}\"", s),
451 tr("Warning"),
452 JOptionPane.WARNING_MESSAGE
453 );
454 }
455 try {
456 if (f!=null) {
457 OpenFileAction.openFile(f);
458 }
459 } catch(IllegalDataException e) {
460 e.printStackTrace();
461 JOptionPane.showMessageDialog(
462 Main.parent,
463 tr("<html>Could not read file ''{0}\''.<br> Error is: <br>{1}</html>", f.getName(), e.getMessage()),
464 tr("Error"),
465 JOptionPane.ERROR_MESSAGE
466 );
467 }catch(IOException e) {
468 e.printStackTrace();
469 JOptionPane.showMessageDialog(
470 Main.parent,
471 tr("<html>Could not read file ''{0}\''.<br> Error is: <br>{1}</html>", f.getName(), e.getMessage()),
472 tr("Error"),
473 JOptionPane.ERROR_MESSAGE
474 );
475 }
476 return;
477 }
478
479 final StringTokenizer st = new StringTokenizer(s, ",");
480 if (st.countTokens() == 4) {
481 Bounds b = new Bounds(
482 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
483 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
484 );
485 try {
486 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
487 // asynchronously launch the download task ...
488 Future<?> future = task.download(true, b, null);
489 // ... and the continuation when the download is finished (this will wait for the download to finish)
490 Main.worker.execute(new PostDownloadHandler(task, future));
491 return;
492 } catch (final NumberFormatException e) {
493 }
494 }
495 File f = new File(s);
496 try {
497 OpenFileAction.openFile(f);
498 }catch(IllegalDataException e) {
499 e.printStackTrace();
500 JOptionPane.showMessageDialog(
501 Main.parent,
502 tr("<html>Could not read file ''{0}\''.<br> Error is: <br>{1}</html>", f.getName(), e.getMessage()),
503 tr("Error"),
504 JOptionPane.ERROR_MESSAGE
505 );
506 }catch(IOException e) {
507 e.printStackTrace();
508 JOptionPane.showMessageDialog(
509 Main.parent,
510 tr("<html>Could not read file ''{0}\''.<br> Error is: <br>{1}</html>", f.getName(), e.getMessage()),
511 tr("Error"),
512 JOptionPane.ERROR_MESSAGE
513 );
514 }
515 }
516
517 public static void determinePlatformHook() {
518 String os = System.getProperty("os.name");
519 if (os == null) {
520 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
521 platform = new PlatformHookUnixoid();
522 } else if (os.toLowerCase().startsWith("windows")) {
523 platform = new PlatformHookWindows();
524 } else if (os.equals("Linux") || os.equals("Solaris") ||
525 os.equals("SunOS") || os.equals("AIX") ||
526 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
527 platform = new PlatformHookUnixoid();
528 } else if (os.toLowerCase().startsWith("mac os x")) {
529 platform = new PlatformHookOsx();
530 } else {
531 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
532 platform = new PlatformHookUnixoid();
533 }
534 }
535
536 static public void saveGuiGeometry() {
537 // save the current window geometry and the width of the toggle dialog area
538 String newGeometry = "";
539 String newToggleDlgWidth = null;
540 try {
541 if (((JFrame)parent).getExtendedState() == JFrame.NORMAL) {
542 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
543 Rectangle bounds = parent.getBounds();
544 int width = (int)bounds.getWidth();
545 int height = (int)bounds.getHeight();
546 int x = (int)bounds.getX();
547 int y = (int)bounds.getY();
548 if (width > screenDimension.width) {
549 width = screenDimension.width;
550 }
551 if (height > screenDimension.height) {
552 width = screenDimension.height;
553 }
554 if (x < 0) {
555 x = 0;
556 }
557 if (y < 0) {
558 y = 0;
559 }
560 newGeometry = width + "x" + height + "+" + x + "+" + y;
561 }
562
563 if (map != null) {
564 newToggleDlgWidth = Integer.toString(map.getToggleDlgWidth());
565 if (newToggleDlgWidth.equals(Integer.toString(map.DEF_TOGGLE_DLG_WIDTH))) {
566 newToggleDlgWidth = "";
567 }
568 }
569 }
570 catch (Exception e) {
571 System.out.println("Failed to save GUI geometry: " + e);
572 e.printStackTrace();
573 }
574 pref.put("gui.geometry", newGeometry);
575 if (newToggleDlgWidth != null) {
576 pref.put("toggleDialogs.width", newToggleDlgWidth);
577 }
578 }
579}
Note: See TracBrowser for help on using the repository browser.