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

Last change on this file since 1653 was 1633, checked in by stoecker, 15 years ago

fix #2688 - patch by jttt - solve NPE

  • Property svn:eol-style set to native
File size: 17.6 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 * Should be called before the main constructor to setup some parameter stuff
254 * @param args The parsed argument list.
255 */
256 public static void preConstructorInit(Map<String, Collection<String>> args) {
257 try {
258 Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
259 } catch (final Exception e) {
260 e.printStackTrace();
261 JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using Mercartor"));
262 Main.proj = new Mercator();
263 }
264
265 try {
266 try {
267 String laf = Main.pref.get("laf");
268 if(laf != null && laf.length() > 0)
269 UIManager.setLookAndFeel(laf);
270 }
271 catch (final javax.swing.UnsupportedLookAndFeelException e) {
272 System.out.println("Look and Feel not supported: " + Main.pref.get("laf"));
273 }
274 toolbar = new ToolbarPreferences();
275 contentPane.updateUI();
276 panel.updateUI();
277 } catch (final Exception e) {
278 e.printStackTrace();
279 }
280 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
281 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
282 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
283 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
284
285 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
286 String geometry = Main.pref.get("gui.geometry");
287 if (args.containsKey("geometry")) {
288 geometry = args.get("geometry").iterator().next();
289 }
290 if (geometry.length() != 0) {
291 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
292 if (m.matches()) {
293 int w = Integer.valueOf(m.group(1));
294 int h = Integer.valueOf(m.group(2));
295 int x = 0, y = 0;
296 if (m.group(3) != null) {
297 x = Integer.valueOf(m.group(5));
298 y = Integer.valueOf(m.group(7));
299 if (m.group(4).equals("-"))
300 x = screenDimension.width - x - w;
301 if (m.group(6).equals("-"))
302 y = screenDimension.height - y - h;
303 }
304 bounds = new Rectangle(x,y,w,h);
305 if(!Main.pref.get("gui.geometry").equals(geometry)) {
306 // remember this geometry
307 Main.pref.put("gui.geometry", geometry);
308 }
309 } else {
310 System.out.println("Ignoring malformed geometry: "+geometry);
311 }
312 }
313 if (bounds == null)
314 bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
315
316 // preinitialize a wait dialog for all early downloads (e.g. via command line)
317 pleaseWaitDlg = new PleaseWaitDialog(null);
318 }
319
320 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
321 // initialize the pleaseWaitDialog with the application as parent to handle focus stuff
322 pleaseWaitDlg = new PleaseWaitDialog(parent);
323
324 if (args.containsKey("download"))
325 for (String s : args.get("download"))
326 downloadFromParamString(false, s);
327 if (args.containsKey("downloadgps"))
328 for (String s : args.get("downloadgps"))
329 downloadFromParamString(true, s);
330 if (args.containsKey("selection"))
331 for (String s : args.get("selection"))
332 SearchAction.search(s, SearchAction.SearchMode.add, false, false);
333 }
334
335 public static boolean breakBecauseUnsavedChanges() {
336 Shortcut.savePrefs();
337 if (map != null) {
338 boolean modified = false;
339 boolean uploadedModified = false;
340 for (final Layer l : map.mapView.getAllLayers()) {
341 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
342 modified = true;
343 uploadedModified = ((OsmDataLayer)l).uploadedModified;
344 break;
345 }
346 }
347 if (modified) {
348 final String msg = uploadedModified ? "\n"
349 +tr("Hint: Some changes came from uploading new data to the server.") : "";
350 int result = new ExtendedDialog(parent, tr("Unsaved Changes"),
351 new javax.swing.JLabel(tr("There are unsaved changes. Discard the changes and continue?")+msg),
352 new String[] {tr("Save and Exit"), tr("Discard and Exit"), tr("Cancel")},
353 new String[] {"save.png", "exit.png", "cancel.png"}).getValue();
354
355 // Save before exiting
356 if(result == 1) {
357 Boolean savefailed = false;
358 for (final Layer l : map.mapView.getAllLayers()) {
359 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
360 SaveAction save = new SaveAction(l);
361 if(!save.doSave())
362 savefailed = true;
363 }
364 }
365 return savefailed;
366 }
367 else if(result != 2) // Cancel exiting unless the 2nd button was clicked
368 return true;
369 }
370 }
371 return false;
372 }
373
374 private static void downloadFromParamString(final boolean rawGps, String s) {
375 if (s.startsWith("http:")) {
376 final Bounds b = OsmUrlToBounds.parse(s);
377 if (b == null)
378 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed URL: \"{0}\"", s));
379 else {
380 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
381 DownloadTask osmTask = new DownloadOsmTask();
382 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
383 }
384 return;
385 }
386
387 if (s.startsWith("file:")) {
388 try {
389 main.menu.openFile.openFile(new File(new URI(s)));
390 } catch (URISyntaxException e) {
391 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file URL: \"{0}\"", s));
392 }
393 return;
394 }
395
396 final StringTokenizer st = new StringTokenizer(s, ",");
397 if (st.countTokens() == 4) {
398 try {
399 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
400 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
401 return;
402 } catch (final NumberFormatException e) {
403 }
404 }
405
406 main.menu.openFile.openFile(new File(s));
407 }
408
409 protected static void determinePlatformHook() {
410 String os = System.getProperty("os.name");
411 if (os == null) {
412 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
413 platform = new PlatformHookUnixoid();
414 } else if (os.toLowerCase().startsWith("windows")) {
415 platform = new PlatformHookWindows();
416 } else if (os.equals("Linux") || os.equals("Solaris") ||
417 os.equals("SunOS") || os.equals("AIX") ||
418 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
419 platform = new PlatformHookUnixoid();
420 } else if (os.toLowerCase().startsWith("mac os x")) {
421 platform = new PlatformHookOsx();
422 } else {
423 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
424 platform = new PlatformHookUnixoid();
425 }
426 }
427
428 static public String getLanguageCodeU()
429 {
430 String languageCode = getLanguageCode();
431 if(languageCode.equals("en"))
432 return "";
433 return languageCode.substring(0,1).toUpperCase() + languageCode.substring(1) + ":";
434 }
435 static public String getLanguageCode()
436 {
437 String full = Locale.getDefault().toString();
438 if (full.equals("iw_IL"))
439 return "he";
440 /* list of non-single codes supported by josm */
441 else if (full.equals("en_GB"))
442 return full;
443 return Locale.getDefault().getLanguage();
444 }
445
446 static public void saveGuiGeometry() {
447 // save the current window geometry
448 String newGeometry = "";
449 try {
450 if (((JFrame)parent).getExtendedState() == JFrame.NORMAL) {
451 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
452 Rectangle bounds = parent.getBounds();
453 int width = (int)bounds.getWidth();
454 int height = (int)bounds.getHeight();
455 int x = (int)bounds.getX();
456 int y = (int)bounds.getY();
457 if (width > screenDimension.width)
458 width = screenDimension.width;
459 if (height > screenDimension.height)
460 width = screenDimension.height;
461 if (x < 0)
462 x = 0;
463 if (y < 0)
464 y = 0;
465 newGeometry = width + "x" + height + "+" + x + "+" + y;
466 }
467 }
468 catch (Exception e) {
469 System.out.println("Failed to save GUI geometry: " + e);
470 }
471 pref.put("gui.geometry", newGeometry);
472 }
473}
Note: See TracBrowser for help on using the repository browser.