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

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