source: josm/branch/0.5/src/org/openstreetmap/josm/Main.java@ 342

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