source: josm/src/org/openstreetmap/josm/Main.java@ 210

Last change on this file since 210 was 208, checked in by imi, 17 years ago
  • fixed a NPE when hitting a mapmode shortcut after all layers have been closed
File size: 13.2 KB
Line 
1package org.openstreetmap.josm;
2import static org.openstreetmap.josm.tools.I18n.tr;
3
4import java.awt.BorderLayout;
5import java.awt.Component;
6import java.awt.Dimension;
7import java.awt.Rectangle;
8import java.awt.Toolkit;
9import java.awt.event.KeyEvent;
10import java.io.File;
11import java.net.URI;
12import java.net.URISyntaxException;
13import java.util.Collection;
14import java.util.LinkedList;
15import java.util.Map;
16import java.util.SortedMap;
17import java.util.StringTokenizer;
18import java.util.TreeMap;
19import java.util.concurrent.Executor;
20import java.util.concurrent.Executors;
21import java.util.regex.Matcher;
22import java.util.regex.Pattern;
23
24import javax.swing.JComponent;
25import javax.swing.JOptionPane;
26import javax.swing.JPanel;
27import javax.swing.KeyStroke;
28import javax.swing.UIManager;
29
30import org.openstreetmap.josm.actions.DownloadAction;
31import org.openstreetmap.josm.actions.DownloadAction.DownloadTask;
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.osm.DataSet;
37import org.openstreetmap.josm.data.projection.Epsg4326;
38import org.openstreetmap.josm.data.projection.Projection;
39import org.openstreetmap.josm.gui.MainMenu;
40import org.openstreetmap.josm.gui.MapFrame;
41import org.openstreetmap.josm.gui.PleaseWaitDialog;
42import org.openstreetmap.josm.gui.MapView.LayerChangeListener;
43import org.openstreetmap.josm.gui.layer.Layer;
44import org.openstreetmap.josm.gui.layer.OsmDataLayer;
45import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
46import org.openstreetmap.josm.gui.preferences.AnnotationPresetPreference;
47import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
48import org.openstreetmap.josm.plugins.PluginException;
49import org.openstreetmap.josm.plugins.PluginInformation;
50import org.openstreetmap.josm.plugins.PluginProxy;
51import org.openstreetmap.josm.tools.ImageProvider;
52
53abstract public class Main {
54 /**
55 * Global parent component for all dialogs and message boxes
56 */
57 public static Component parent;
58 /**
59 * Global application window. Use this as JOPtionPane-parent to center on application.
60 */
61 public static Main main;
62 /**
63 * The worker thread slave. This is for executing all long and intensive
64 * calculations. The executed runnables are guaranteed to be executed seperatly
65 * and sequenciel.
66 */
67 public final static Executor worker = Executors.newSingleThreadExecutor();
68 /**
69 * Global application preferences
70 */
71 public static Preferences pref = new Preferences();
72 /**
73 * The global dataset.
74 */
75 public static DataSet ds = new DataSet();
76 /**
77 * The projection method used.
78 */
79 public static Projection proj;
80 /**
81 * The MapFrame. Use setMapFrame to set or clear it.
82 */
83 public static MapFrame map;
84 /**
85 * All installed and loaded plugins (resp. their main classes)
86 */
87 public final static Collection<PluginProxy> plugins = new LinkedList<PluginProxy>();
88 /**
89 * The dialog that gets displayed during background task execution.
90 */
91 public static PleaseWaitDialog pleaseWaitDlg;
92
93 /**
94 * True, when in applet mode
95 */
96 public static boolean applet = false;
97
98 /**
99 * The toolbar preference control to register new actions.
100 */
101 public static ToolbarPreferences toolbar = new ToolbarPreferences();
102
103
104 /**
105 * The main menu bar at top of screen.
106 */
107 public final MainMenu menu;
108
109
110 /**
111 * Set or clear (if passed <code>null</code>) the map.
112 */
113 public final void setMapFrame(final MapFrame map) {
114 MapFrame old = Main.map;
115 Main.map = map;
116 panel.setVisible(false);
117 panel.removeAll();
118 if (map != null) {
119 map.fillPanel(panel);
120 panel.setVisible(true);
121 map.mapView.addLayerChangeListener(new LayerChangeListener(){
122 public void activeLayerChange(final Layer oldLayer, final Layer newLayer) {
123 setLayerMenu(newLayer.getMenuEntries());
124 }
125 public void layerAdded(final Layer newLayer) {
126 if (newLayer instanceof OsmDataLayer)
127 Main.main.editLayer().listenerCommands.add(redoUndoListener);
128 }
129 public void layerRemoved(final Layer oldLayer) {
130 if (oldLayer instanceof OsmDataLayer)
131 Main.main.editLayer().listenerCommands.add(redoUndoListener);
132 if (map.mapView.getAllLayers().isEmpty())
133 setLayerMenu(null);
134 }
135 });
136 if (map.mapView.editLayer != null)
137 map.mapView.editLayer.listenerCommands.add(redoUndoListener);
138 } else
139 old.destroy();
140 redoUndoListener.commandChanged(0,0);
141
142 for (PluginProxy plugin : plugins)
143 plugin.mapFrameInitialized(old, map);
144 }
145
146 /**
147 * Set the layer menu (changed when active layer changes).
148 */
149 public final void setLayerMenu(Component[] entries) {
150 if (entries == null || entries.length == 0)
151 menu.layerMenu.setVisible(false);
152 else {
153 menu.layerMenu.removeAll();
154 for (Component c : entries)
155 menu.layerMenu.add(c);
156 menu.layerMenu.setVisible(true);
157 }
158 }
159
160 /**
161 * Remove the specified layer from the map. If it is the last layer, remove the map as well.
162 */
163 public final void removeLayer(final Layer layer) {
164 map.mapView.removeLayer(layer);
165 if (layer instanceof OsmDataLayer) {
166 DataSet newDs = new DataSet();
167 newDs.listeners.addAll(ds.listeners);
168 ds = newDs;
169 }
170 if (map.mapView.getAllLayers().isEmpty())
171 setMapFrame(null);
172 }
173
174
175 public Main() {
176 main = this;
177 contentPane.add(panel, BorderLayout.CENTER);
178 menu = new MainMenu();
179
180 // creating toolbar
181 contentPane.add(toolbar.control, BorderLayout.NORTH);
182
183 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "Help");
184 contentPane.getActionMap().put("Help", menu.help);
185
186 AnnotationPresetPreference.initialize();
187
188 toolbar.refreshToolbarControl();
189
190 toolbar.control.updateUI();
191 contentPane.updateUI();
192 }
193
194 /**
195 * Load all plugins specified in preferences. If the parameter is <code>true</code>, all
196 * early plugins are loaded (before constructor).
197 */
198 public static void loadPlugins(boolean early) {
199 if (!Main.pref.hasKey("plugins"))
200 return;
201 SortedMap<Integer, Collection<PluginInformation>> p = new TreeMap<Integer, Collection<PluginInformation>>();
202 for (String pluginName : Main.pref.get("plugins").split(",")) {
203 File pluginFile = new File(pref.getPreferencesDir()+"plugins/"+pluginName+".jar");
204 if (pluginFile.exists()) {
205 PluginInformation info = new PluginInformation(pluginFile);
206 if (info.early != early)
207 continue;
208 if (!p.containsKey(info.stage))
209 p.put(info.stage, new LinkedList<PluginInformation>());
210 p.get(info.stage).add(info);
211 } else {
212 if (early)
213 System.out.println("Plugin not found: "+pluginName); // do not translate
214 else
215 JOptionPane.showMessageDialog(Main.parent, tr("Plugin not found: {0}.", pluginName));
216 }
217 }
218 for (Collection<PluginInformation> c : p.values()) {
219 for (PluginInformation info : c) {
220 try {
221 Class<?> klass = info.loadClass();
222 ImageProvider.sources.add(0, klass);
223 System.out.println("loading "+info.name);
224 plugins.add(info.load(klass));
225 } catch (PluginException e) {
226 e.printStackTrace();
227 if (early)
228 System.out.println("Could not load plugin: "+info.name); // do not translate
229 else
230 JOptionPane.showMessageDialog(Main.parent, tr("Could not load plugin {0}.", info.name));
231 }
232 }
233 }
234 }
235
236 /**
237 * Add a new layer to the map. If no map exist, create one.
238 */
239 public final void addLayer(final Layer layer) {
240 if (map == null) {
241 final MapFrame mapFrame = new MapFrame();
242 setMapFrame(mapFrame);
243 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
244 mapFrame.setVisible(true);
245 mapFrame.setVisibleDialogs();
246 }
247 map.mapView.addLayer(layer);
248 }
249 /**
250 * @return The edit osm layer. If none exist, it will be created.
251 */
252 public final OsmDataLayer editLayer() {
253 if (map == null || map.mapView.editLayer == null)
254 addLayer(new OsmDataLayer(ds, tr("unnamed"), null));
255 return map.mapView.editLayer;
256 }
257
258
259
260
261 /**
262 * Use this to register shortcuts to
263 */
264 public static final JPanel contentPane = new JPanel(new BorderLayout());
265
266
267 ////////////////////////////////////////////////////////////////////////////////////////
268 // Implementation part
269 ////////////////////////////////////////////////////////////////////////////////////////
270
271 public static JPanel panel = new JPanel(new BorderLayout());
272
273 protected static Rectangle bounds;
274
275 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
276 public void commandChanged(final int queueSize, final int redoSize) {
277 menu.undo.setEnabled(queueSize > 0);
278 menu.redo.setEnabled(redoSize > 0);
279 }
280 };
281
282 /**
283 * Should be called before the main constructor to setup some parameter stuff
284 * @param args The parsed argument list.
285 */
286 public static void preConstructorInit(Map<String, Collection<String>> args) {
287 try {
288 Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
289 } catch (final Exception e) {
290 e.printStackTrace();
291 JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using EPSG:4263."));
292 Main.proj = new Epsg4326();
293 }
294
295 try {
296 UIManager.setLookAndFeel(Main.pref.get("laf"));
297 contentPane.updateUI();
298 panel.updateUI();
299 } catch (final Exception e) {
300 e.printStackTrace();
301 }
302 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
303 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
304 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
305 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
306
307 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
308 if (args.containsKey("geometry")) {
309 String geometry = args.get("geometry").iterator().next();
310 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
311 if (m.matches()) {
312 int w = Integer.valueOf(m.group(1));
313 int h = Integer.valueOf(m.group(2));
314 int x = 0, y = 0;
315 if (m.group(3) != null) {
316 x = Integer.valueOf(m.group(5));
317 y = Integer.valueOf(m.group(7));
318 if (m.group(4).equals("-"))
319 x = screenDimension.width - x - w;
320 if (m.group(6).equals("-"))
321 y = screenDimension.height - y - h;
322 }
323 bounds = new Rectangle(x,y,w,h);
324 } else
325 System.out.println("Ignoring malformed geometry: "+geometry);
326 }
327 if (bounds == null)
328 bounds = !args.containsKey("no-fullscreen") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
329
330 pleaseWaitDlg = new PleaseWaitDialog();
331 }
332
333 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
334 if (args.containsKey("download"))
335 for (String s : args.get("download"))
336 downloadFromParamString(false, s);
337 if (args.containsKey("downloadgps"))
338 for (String s : args.get("downloadgps"))
339 downloadFromParamString(true, s);
340 if (args.containsKey("selection"))
341 for (String s : args.get("selection"))
342 SearchAction.search(s, SearchAction.SearchMode.add, false);
343 }
344
345 public static boolean breakBecauseUnsavedChanges() {
346 if (map != null) {
347 boolean modified = false;
348 boolean uploadedModified = false;
349 for (final Layer l : map.mapView.getAllLayers()) {
350 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
351 modified = true;
352 uploadedModified = ((OsmDataLayer)l).uploadedModified;
353 break;
354 }
355 }
356 if (modified) {
357 final String msg = uploadedModified ? "\n"+tr("Hint: Some changes came from uploading new data to the server.") : "";
358 final int answer = JOptionPane.showConfirmDialog(
359 parent, tr("There are unsaved changes. Discard the changes and continue?")+msg,
360 tr("Unsaved Changes"), JOptionPane.YES_NO_OPTION);
361 if (answer != JOptionPane.YES_OPTION)
362 return true;
363 }
364 }
365 return false;
366 }
367
368 private static void downloadFromParamString(final boolean rawGps, String s) {
369 if (s.startsWith("http:")) {
370 final Bounds b = DownloadAction.osmurl2bounds(s);
371 if (b == null)
372 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed url: \"{0}\"", s));
373 else {
374 DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
375 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
376 }
377 return;
378 }
379
380 if (s.startsWith("file:")) {
381 try {
382 main.menu.open.openFile(new File(new URI(s)));
383 } catch (URISyntaxException e) {
384 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file url: \"{0}\"", s));
385 }
386 return;
387 }
388
389 final StringTokenizer st = new StringTokenizer(s, ",");
390 if (st.countTokens() == 4) {
391 try {
392 DownloadTask task = main.menu.download.downloadTasks.get(rawGps ? 1 : 0);
393 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
394 return;
395 } catch (final NumberFormatException e) {
396 }
397 }
398
399 main.menu.open.openFile(new File(s));
400 }
401}
Note: See TracBrowser for help on using the repository browser.