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

Last change on this file since 1724 was 1722, checked in by stoecker, 15 years ago

Large rework in projection handling - now allows only switching and more specific projections
TODO:

  • allow subprojections (i.e. settings for projections)
  • setup preferences for subprojections
  • better support of the new projection depending world bounds (how to handle valid data outside of world)
  • do not allow to zoom out of the world - zoom should stop when whole world is displayed
  • fix Lambert and SwissGrid to handle new OutOfWorld style and subprojections
  • fix new UTM projection
  • handle layers with fixed projection on projection change
  • allow easier projection switching (e.g. in menu)

NOTE:
This checkin very likely will cause problems. Please report or fix them. Older plugins may have trouble. The SVN plugins
have been fixed but may have problems nevertheless. This is a BIG change, but will make JOSMs internal structure much cleaner
and reduce lots of projection related problems.

  • Property svn:eol-style set to native
File size: 18.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.net.URI;
13import java.net.URISyntaxException;
14import java.util.Collection;
15import java.util.Locale;
16import java.util.Map;
17import java.util.StringTokenizer;
18import java.util.concurrent.ExecutorService;
19import java.util.concurrent.Executors;
20import java.util.regex.Matcher;
21import java.util.regex.Pattern;
22
23import javax.swing.JComponent;
24import javax.swing.JFrame;
25import javax.swing.JOptionPane;
26import javax.swing.JPanel;
27import javax.swing.UIManager;
28
29import org.openstreetmap.josm.actions.SaveAction;
30import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
31import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
32import org.openstreetmap.josm.actions.mapmode.MapMode;
33import org.openstreetmap.josm.actions.search.SearchAction;
34import org.openstreetmap.josm.data.Bounds;
35import org.openstreetmap.josm.data.Preferences;
36import org.openstreetmap.josm.data.UndoRedoHandler;
37import org.openstreetmap.josm.data.osm.DataSet;
38import org.openstreetmap.josm.data.projection.Mercator;
39import org.openstreetmap.josm.data.projection.Projection;
40import org.openstreetmap.josm.gui.ExtendedDialog;
41import org.openstreetmap.josm.gui.GettingStarted;
42import org.openstreetmap.josm.gui.MainMenu;
43import org.openstreetmap.josm.gui.MapFrame;
44import org.openstreetmap.josm.gui.PleaseWaitDialog;
45import org.openstreetmap.josm.gui.SplashScreen;
46import org.openstreetmap.josm.gui.download.DownloadDialog.DownloadTask;
47import org.openstreetmap.josm.gui.layer.Layer;
48import org.openstreetmap.josm.gui.layer.OsmDataLayer;
49import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
50import org.openstreetmap.josm.gui.preferences.MapPaintPreference;
51import org.openstreetmap.josm.gui.preferences.TaggingPresetPreference;
52import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
53import org.openstreetmap.josm.plugins.PluginHandler;
54import org.openstreetmap.josm.tools.ImageProvider;
55import org.openstreetmap.josm.tools.OsmUrlToBounds;
56import org.openstreetmap.josm.tools.PlatformHook;
57import org.openstreetmap.josm.tools.PlatformHookOsx;
58import org.openstreetmap.josm.tools.PlatformHookUnixoid;
59import org.openstreetmap.josm.tools.PlatformHookWindows;
60import org.openstreetmap.josm.tools.Shortcut;
61
62abstract public class Main {
63 /**
64 * Global parent component for all dialogs and message boxes
65 */
66 public static Component parent;
67 /**
68 * Global application.
69 */
70 public static Main main;
71 /**
72 * The worker thread slave. This is for executing all long and intensive
73 * calculations. The executed runnables are guaranteed to be executed separately
74 * and sequential.
75 */
76 public final static ExecutorService worker = Executors.newSingleThreadExecutor();
77 /**
78 * Global application preferences
79 */
80 public static Preferences pref = new Preferences();
81 /**
82 * The global dataset.
83 */
84 public static DataSet ds = new DataSet();
85 /**
86 * The global paste buffer.
87 */
88 public static DataSet pasteBuffer = new DataSet();
89 public static Layer pasteSource;
90 /**
91 * The projection method used.
92 */
93 public static Projection proj;
94 /**
95 * The MapFrame. Use setMapFrame to set or clear it.
96 */
97 public static MapFrame map;
98 /**
99 * The dialog that gets displayed during background task execution.
100 */
101 public static PleaseWaitDialog pleaseWaitDlg;
102
103 /**
104 * True, when in applet mode
105 */
106 public static boolean applet = false;
107
108 /**
109 * The toolbar preference control to register new actions.
110 */
111 public static ToolbarPreferences toolbar;
112
113
114 public UndoRedoHandler undoRedo = new UndoRedoHandler();
115
116 /**
117 * The main menu bar at top of screen.
118 */
119 public final MainMenu menu;
120
121 /**
122 * The MOTD Layer.
123 */
124 private GettingStarted gettingStarted=new GettingStarted();
125
126 /**
127 * Print a debug message if debugging is on.
128 */
129 static public int debug_level = 1;
130 static public final void debug(String msg) {
131 if (debug_level <= 0)
132 return;
133 System.out.println(msg);
134 }
135
136 /**
137 * Platform specific code goes in here.
138 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
139 * So if you need to hook into those early ones, split your class and send the one with the early hooks
140 * to the JOSM team for inclusion.
141 */
142 public static PlatformHook platform;
143
144 /**
145 * Set or clear (if passed <code>null</code>) the map.
146 */
147 public final void setMapFrame(final MapFrame map) {
148 MapFrame old = Main.map;
149 Main.map = map;
150 panel.setVisible(false);
151 panel.removeAll();
152 if (map != null)
153 map.fillPanel(panel);
154 else {
155 old.destroy();
156 panel.add(gettingStarted, BorderLayout.CENTER);
157 }
158 panel.setVisible(true);
159 redoUndoListener.commandChanged(0,0);
160
161 PluginHandler.setMapFrame(old, map);
162 }
163
164 /**
165 * Remove the specified layer from the map. If it is the last layer,
166 * remove the map as well.
167 */
168 public final void removeLayer(final Layer layer) {
169 if (map != null) {
170 map.mapView.removeLayer(layer);
171 if (layer instanceof OsmDataLayer)
172 ds = new DataSet();
173 if (map.mapView.getAllLayers().isEmpty())
174 setMapFrame(null);
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) splash.setStatus(tr("Creating main GUI"));
190 menu = new MainMenu();
191
192 undoRedo.listenerCommands.add(redoUndoListener);
193
194 // creating toolbar
195 contentPane.add(toolbar.control, BorderLayout.NORTH);
196
197 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
198 .put(Shortcut.registerShortcut("system:help", tr("Help"),
199 KeyEvent.VK_F1, Shortcut.GROUP_DIRECT).getKeyStroke(), "Help");
200 contentPane.getActionMap().put("Help", menu.help);
201
202 TaggingPresetPreference.initialize();
203 MapPaintPreference.initialize();
204
205 toolbar.refreshToolbarControl();
206
207 toolbar.control.updateUI();
208 contentPane.updateUI();
209 }
210
211 /**
212 * Add a new layer to the map. If no map exists, create one.
213 */
214 public final void addLayer(final Layer layer) {
215 if (map == null) {
216 final MapFrame mapFrame = new MapFrame();
217 setMapFrame(mapFrame);
218 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
219 mapFrame.setVisible(true);
220 mapFrame.setVisibleDialogs();
221 }
222 map.mapView.addLayer(layer);
223 }
224 /**
225 * @return The edit osm layer. If none exists, it will be created.
226 */
227 public final OsmDataLayer editLayer() {
228 if (map == null || map.mapView.editLayer == null)
229 menu.newAction.actionPerformed(null);
230 return map.mapView.editLayer;
231 }
232
233 /**
234 * Use this to register shortcuts to
235 */
236 public static final JPanel contentPane = new JPanel(new BorderLayout());
237
238 ///////////////////////////////////////////////////////////////////////////
239 // Implementation part
240 ///////////////////////////////////////////////////////////////////////////
241
242 public static JPanel panel = new JPanel(new BorderLayout());
243
244 protected static Rectangle bounds;
245
246 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
247 public void commandChanged(final int queueSize, final int redoSize) {
248 menu.undo.setEnabled(queueSize > 0);
249 menu.redo.setEnabled(redoSize > 0);
250 }
251 };
252
253 static public void setProjection(String name)
254 {
255 Bounds b = (map != null && map.mapView != null) ? map.mapView.getRealBounds() : null;
256 Projection oldProj = Main.proj;
257 try {
258 Main.proj = (Projection)Class.forName(name).newInstance();
259 } catch (final Exception e) {
260 JOptionPane.showMessageDialog(null, tr("The projection {0} could not be activated. Using Mercator", name));
261 Main.proj = new Mercator();
262 }
263 if(!Main.proj.equals(oldProj))
264 {
265 if(b != null)
266 map.mapView.zoomTo(b);
267 /* TODO - remove layers with fixed projection */
268 }
269 }
270
271 /**
272 * Should be called before the main constructor to setup some parameter stuff
273 * @param args The parsed argument list.
274 */
275 public static void preConstructorInit(Map<String, Collection<String>> args) {
276 setProjection(Main.pref.get("projection", Mercator.class.getName()));
277
278 try {
279 try {
280 String laf = Main.pref.get("laf");
281 if(laf != null && laf.length() > 0)
282 UIManager.setLookAndFeel(laf);
283 }
284 catch (final javax.swing.UnsupportedLookAndFeelException e) {
285 System.out.println("Look and Feel not supported: " + Main.pref.get("laf"));
286 }
287 toolbar = new ToolbarPreferences();
288 contentPane.updateUI();
289 panel.updateUI();
290 } catch (final Exception e) {
291 e.printStackTrace();
292 }
293 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
294 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
295 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
296 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
297
298 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
299 String geometry = Main.pref.get("gui.geometry");
300 if (args.containsKey("geometry")) {
301 geometry = args.get("geometry").iterator().next();
302 }
303 if (geometry.length() != 0) {
304 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
305 if (m.matches()) {
306 int w = Integer.valueOf(m.group(1));
307 int h = Integer.valueOf(m.group(2));
308 int x = 0, y = 0;
309 if (m.group(3) != null) {
310 x = Integer.valueOf(m.group(5));
311 y = Integer.valueOf(m.group(7));
312 if (m.group(4).equals("-"))
313 x = screenDimension.width - x - w;
314 if (m.group(6).equals("-"))
315 y = screenDimension.height - y - h;
316 }
317 bounds = new Rectangle(x,y,w,h);
318 if(!Main.pref.get("gui.geometry").equals(geometry)) {
319 // remember this geometry
320 Main.pref.put("gui.geometry", geometry);
321 }
322 } else {
323 System.out.println("Ignoring malformed geometry: "+geometry);
324 }
325 }
326 if (bounds == null)
327 bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
328
329 // preinitialize a wait dialog for all early downloads (e.g. via command line)
330 pleaseWaitDlg = new PleaseWaitDialog(null);
331 }
332
333 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
334 // initialize the pleaseWaitDialog with the application as parent to handle focus stuff
335 pleaseWaitDlg = new PleaseWaitDialog(parent);
336
337 if (args.containsKey("download"))
338 for (String s : args.get("download"))
339 downloadFromParamString(false, s);
340 if (args.containsKey("downloadgps"))
341 for (String s : args.get("downloadgps"))
342 downloadFromParamString(true, s);
343 if (args.containsKey("selection"))
344 for (String s : args.get("selection"))
345 SearchAction.search(s, SearchAction.SearchMode.add, false, false);
346 }
347
348 public static boolean breakBecauseUnsavedChanges() {
349 Shortcut.savePrefs();
350 if (map != null) {
351 boolean modified = false;
352 boolean uploadedModified = false;
353 for (final Layer l : map.mapView.getAllLayers()) {
354 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
355 modified = true;
356 uploadedModified = ((OsmDataLayer)l).uploadedModified;
357 break;
358 }
359 }
360 if (modified) {
361 final String msg = uploadedModified ? "\n"
362 +tr("Hint: Some changes came from uploading new data to the server.") : "";
363 int result = new ExtendedDialog(parent, tr("Unsaved Changes"),
364 new javax.swing.JLabel(tr("There are unsaved changes. Discard the changes and continue?")+msg),
365 new String[] {tr("Save and Exit"), tr("Discard and Exit"), tr("Cancel")},
366 new String[] {"save.png", "exit.png", "cancel.png"}).getValue();
367
368 // Save before exiting
369 if(result == 1) {
370 Boolean savefailed = false;
371 for (final Layer l : map.mapView.getAllLayers()) {
372 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
373 SaveAction save = new SaveAction(l);
374 if(!save.doSave())
375 savefailed = true;
376 }
377 }
378 return savefailed;
379 }
380 else if(result != 2) // Cancel exiting unless the 2nd button was clicked
381 return true;
382 }
383 }
384 return false;
385 }
386
387 private static void downloadFromParamString(final boolean rawGps, String s) {
388 if (s.startsWith("http:")) {
389 final Bounds b = OsmUrlToBounds.parse(s);
390 if (b == null)
391 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed URL: \"{0}\"", s));
392 else {
393 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
394 DownloadTask osmTask = new DownloadOsmTask();
395 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
396 }
397 return;
398 }
399
400 if (s.startsWith("file:")) {
401 try {
402 main.menu.openFile.openFile(new File(new URI(s)));
403 } catch (URISyntaxException e) {
404 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file URL: \"{0}\"", s));
405 }
406 return;
407 }
408
409 final StringTokenizer st = new StringTokenizer(s, ",");
410 if (st.countTokens() == 4) {
411 try {
412 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
413 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
414 return;
415 } catch (final NumberFormatException e) {
416 }
417 }
418
419 main.menu.openFile.openFile(new File(s));
420 }
421
422 protected static void determinePlatformHook() {
423 String os = System.getProperty("os.name");
424 if (os == null) {
425 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
426 platform = new PlatformHookUnixoid();
427 } else if (os.toLowerCase().startsWith("windows")) {
428 platform = new PlatformHookWindows();
429 } else if (os.equals("Linux") || os.equals("Solaris") ||
430 os.equals("SunOS") || os.equals("AIX") ||
431 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
432 platform = new PlatformHookUnixoid();
433 } else if (os.toLowerCase().startsWith("mac os x")) {
434 platform = new PlatformHookOsx();
435 } else {
436 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
437 platform = new PlatformHookUnixoid();
438 }
439 }
440
441 static public String getLanguageCodeU()
442 {
443 String languageCode = getLanguageCode();
444 if(languageCode.equals("en"))
445 return "";
446 return languageCode.substring(0,1).toUpperCase() + languageCode.substring(1) + ":";
447 }
448 static public String getLanguageCode()
449 {
450 String full = Locale.getDefault().toString();
451 if (full.equals("iw_IL"))
452 return "he";
453 /* list of non-single codes supported by josm */
454 else if (full.equals("en_GB"))
455 return full;
456 return Locale.getDefault().getLanguage();
457 }
458
459 static public void saveGuiGeometry() {
460 // save the current window geometry
461 String newGeometry = "";
462 try {
463 if (((JFrame)parent).getExtendedState() == JFrame.NORMAL) {
464 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
465 Rectangle bounds = parent.getBounds();
466 int width = (int)bounds.getWidth();
467 int height = (int)bounds.getHeight();
468 int x = (int)bounds.getX();
469 int y = (int)bounds.getY();
470 if (width > screenDimension.width)
471 width = screenDimension.width;
472 if (height > screenDimension.height)
473 width = screenDimension.height;
474 if (x < 0)
475 x = 0;
476 if (y < 0)
477 y = 0;
478 newGeometry = width + "x" + height + "+" + x + "+" + y;
479 }
480 }
481 catch (Exception e) {
482 System.out.println("Failed to save GUI geometry: " + e);
483 }
484 pref.put("gui.geometry", newGeometry);
485 }
486}
Note: See TracBrowser for help on using the repository browser.