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

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