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

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

close bug #1786

  • Property svn:eol-style set to native
File size: 17.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.UIManager;
34
35import org.openstreetmap.josm.actions.AboutAction;
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.MapPaintPreference;
56import org.openstreetmap.josm.gui.preferences.TaggingPresetPreference;
57import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
58import org.openstreetmap.josm.plugins.PluginInformation;
59import org.openstreetmap.josm.plugins.PluginProxy;
60import org.openstreetmap.josm.tools.ImageProvider;
61import org.openstreetmap.josm.tools.PlatformHook;
62import org.openstreetmap.josm.tools.PlatformHookUnixoid;
63import org.openstreetmap.josm.tools.PlatformHookWindows;
64import org.openstreetmap.josm.tools.PlatformHookOsx;
65import org.openstreetmap.josm.tools.Shortcut;
66
67abstract public class Main {
68 /**
69 * Global parent component for all dialogs and message boxes
70 */
71 public static Component parent;
72 /**
73 * Global application.
74 */
75 public static Main main;
76 /**
77 * The worker thread slave. This is for executing all long and intensive
78 * calculations. The executed runnables are guaranteed to be executed separately
79 * and sequential.
80 */
81 public final static Executor worker = Executors.newSingleThreadExecutor();
82 /**
83 * Global application preferences
84 */
85 public static Preferences pref = new Preferences();
86 /**
87 * The global dataset.
88 */
89 public static DataSet ds = new DataSet();
90 /**
91 * The global paste buffer.
92 */
93 public static DataSet pasteBuffer = new DataSet();
94 /**
95 * The projection method used.
96 */
97 public static Projection proj;
98 /**
99 * The MapFrame. Use setMapFrame to set or clear it.
100 */
101 public static MapFrame map;
102 /**
103 * All installed and loaded plugins (resp. their main classes)
104 */
105 public final static Collection<PluginProxy> plugins = new LinkedList<PluginProxy>();
106 /**
107 * The dialog that gets displayed during background task execution.
108 */
109 public static PleaseWaitDialog pleaseWaitDlg;
110
111 /**
112 * True, when in applet mode
113 */
114 public static boolean applet = false;
115
116 /**
117 * The toolbar preference control to register new actions.
118 */
119 public static ToolbarPreferences toolbar;
120
121
122 public UndoRedoHandler undoRedo = new UndoRedoHandler();
123
124 /**
125 * The main menu bar at top of screen.
126 */
127 public final MainMenu menu;
128
129 /**
130 * Print a debug message if debugging is on.
131 */
132 static public int debug_level = 1;
133 static public final void debug(String msg) {
134 if (debug_level <= 0)
135 return;
136 System.out.println(msg);
137 }
138
139 /**
140 * Platform specific code goes in here.
141 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
142 * So if you need to hook into those early ones, split your class and send the one with the early hooks
143 * to the JOSM team for inclusion.
144 */
145 public static PlatformHook platform;
146
147 /**
148 * Set or clear (if passed <code>null</code>) the map.
149 */
150 public final void setMapFrame(final MapFrame map) {
151 MapFrame old = Main.map;
152 Main.map = map;
153 panel.setVisible(false);
154 panel.removeAll();
155 if (map != null)
156 map.fillPanel(panel);
157 else {
158 old.destroy();
159 panel.add(new GettingStarted(), BorderLayout.CENTER);
160 }
161 panel.setVisible(true);
162 redoUndoListener.commandChanged(0,0);
163
164 for (PluginProxy plugin : plugins)
165 plugin.mapFrameInitialized(old, map);
166 }
167
168 /**
169 * Set the layer menu (changed when active layer changes).
170 */
171 public final void setLayerMenu(Component[] entries) {
172 //if (entries == null || entries.length == 0)
173 //menu.layerMenu.setVisible(false);
174 //else {
175 //menu.layerMenu.removeAll();
176 //for (Component c : entries)
177 //menu.layerMenu.add(c);
178 //menu.layerMenu.setVisible(true);
179 //}
180 }
181
182 /**
183 * Remove the specified layer from the map. If it is the last layer,
184 * remove the map as well.
185 */
186 public final void removeLayer(final Layer layer) {
187 map.mapView.removeLayer(layer);
188 if (layer instanceof OsmDataLayer)
189 ds = new DataSet();
190 if (map.mapView.getAllLayers().isEmpty())
191 setMapFrame(null);
192 }
193
194 public Main() {
195 main = this;
196// platform = determinePlatformHook();
197 platform.startupHook();
198 contentPane.add(panel, BorderLayout.CENTER);
199 panel.add(new GettingStarted(), BorderLayout.CENTER);
200 menu = new MainMenu();
201
202 undoRedo.listenerCommands.add(redoUndoListener);
203
204 // creating toolbar
205 contentPane.add(toolbar.control, BorderLayout.NORTH);
206
207 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(Shortcut.registerShortcut("system:help", tr("Help"), KeyEvent.VK_F1, Shortcut.GROUP_DIRECT).getKeyStroke(), "Help");
208 contentPane.getActionMap().put("Help", menu.help);
209
210 TaggingPresetPreference.initialize();
211 MapPaintPreference.initialize();
212
213 toolbar.refreshToolbarControl();
214
215 toolbar.control.updateUI();
216 contentPane.updateUI();
217 }
218
219 /**
220 * Load all plugins specified in preferences. If the parameter is
221 * <code>true</code>, all early plugins are loaded (before constructor).
222 */
223 public static void loadPlugins(boolean early) {
224 List<String> plugins = new LinkedList<String>();
225 Collection<String> cp = Main.pref.getCollection("plugins", null);
226 if (cp != null)
227 plugins.addAll(cp);
228 if (System.getProperty("josm.plugins") != null)
229 plugins.addAll(Arrays.asList(System.getProperty("josm.plugins").split(",")));
230
231 String [] oldplugins = new String[] {"mappaint", "unglueplugin", "lang-de","lang-en_GB","lang-fr","lang-it","lang-pl","lang-ro","lang-ru"};
232 for (String p : oldplugins) {
233 if (plugins.contains(p)) {
234 plugins.remove(p);
235 Main.pref.removeFromCollection("plugins", p);
236 System.out.println(tr("Warning - loading of {0} plugin was requested. This plugin is no longer required.", p));
237 }
238 }
239
240 if (plugins.isEmpty())
241 return;
242
243 SortedMap<Integer, Collection<PluginInformation>> p = new TreeMap<Integer, Collection<PluginInformation>>();
244 for (String pluginName : plugins) {
245 PluginInformation info = PluginInformation.findPlugin(pluginName);
246 if (info != null) {
247 if (info.early != early)
248 continue;
249 if (info.mainversion != null && info.mainversion.compareTo(AboutAction.version) > 0) {
250 JOptionPane.showMessageDialog(Main.parent, tr("Plugin requires JOSM update: {0}.", pluginName));
251 continue;
252 }
253 if (!p.containsKey(info.stage))
254 p.put(info.stage, new LinkedList<PluginInformation>());
255 p.get(info.stage).add(info);
256 } else {
257 if (early)
258 System.out.println("Plugin not found: "+pluginName); // do not translate
259 else
260 JOptionPane.showMessageDialog(Main.parent, tr("Plugin not found: {0}.", pluginName));
261 }
262 }
263
264 if (!early) {
265 long tim = System.currentTimeMillis();
266 long last = Main.pref.getLong("pluginmanager.lastupdate", 0);
267 Integer maxTime = Main.pref.getInteger("pluginmanager.warntime", 30);
268 if (last <= 0) {
269 Main.pref.put("pluginmanager.lastupdate",Long.toString(tim));
270 } else if (tim - last >= maxTime*1000l*24*60*60) {
271 long d = (tim - last)/(24*60*60*1000l);
272 JOptionPane.showMessageDialog(Main.parent,
273 tr("Last plugin update more than {0} days ago.", d));
274 }
275 }
276
277 // iterate all plugins and collect all libraries of all plugins:
278 List<URL> allPluginLibraries = new ArrayList<URL>();
279 for (Collection<PluginInformation> c : p.values())
280 for (PluginInformation info : c)
281 allPluginLibraries.addAll(info.libraries);
282 // create a classloader for all plugins:
283 URL[] jarUrls = new URL[allPluginLibraries.size()];
284 jarUrls = allPluginLibraries.toArray(jarUrls);
285 URLClassLoader pluginClassLoader = new URLClassLoader(jarUrls, Main.class.getClassLoader());
286 ImageProvider.sources.add(0, pluginClassLoader);
287
288 for (Collection<PluginInformation> c : p.values()) {
289 for (PluginInformation info : c) {
290 try {
291 Class<?> klass = info.loadClass(pluginClassLoader);
292 if (klass != null) {
293 System.out.println("loading "+info.name);
294 Main.plugins.add(info.load(klass));
295 }
296 } catch (Throwable e) {
297 e.printStackTrace();
298 boolean remove = true;
299 if (early)
300 System.out.println("Could not load plugin: "+info.name+" - deleted from preferences"); // do not translate
301 else {
302 int answer = JOptionPane.showConfirmDialog(Main.parent,
303 tr("Could not load plugin {0}. Delete from preferences?", info.name,
304 JOptionPane.YES_NO_OPTION));
305 if (answer != JOptionPane.OK_OPTION) {
306 remove = false;
307 }
308 }
309 if (remove) {
310 plugins.remove(info.name);
311 String plist = null;
312 for (String pn : plugins) {
313 if (plist==null) plist=""; else plist=plist+",";
314 plist=plist+pn;
315 }
316 Main.pref.put("plugins", plist);
317 }
318 }
319 }
320 }
321 }
322
323 /**
324 * Add a new layer to the map. If no map exists, create one.
325 */
326 public final void addLayer(final Layer layer) {
327 if (map == null) {
328 final MapFrame mapFrame = new MapFrame();
329 setMapFrame(mapFrame);
330 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
331 mapFrame.setVisible(true);
332 mapFrame.setVisibleDialogs();
333 }
334 map.mapView.addLayer(layer);
335 }
336 /**
337 * @return The edit osm layer. If none exists, it will be created.
338 */
339 public final OsmDataLayer editLayer() {
340 if (map == null || map.mapView.editLayer == null)
341 menu.newAction.actionPerformed(null);
342 return map.mapView.editLayer;
343 }
344
345 /**
346 * Use this to register shortcuts to
347 */
348 public static final JPanel contentPane = new JPanel(new BorderLayout());
349
350
351 ///////////////////////////////////////////////////////////////////////////
352 // Implementation part
353 ///////////////////////////////////////////////////////////////////////////
354
355 public static JPanel panel = new JPanel(new BorderLayout());
356
357 protected static Rectangle bounds;
358
359 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
360 public void commandChanged(final int queueSize, final int redoSize) {
361 menu.undo.setEnabled(queueSize > 0);
362 menu.redo.setEnabled(redoSize > 0);
363 }
364 };
365 /**
366 * Should be called before the main constructor to setup some parameter stuff
367 * @param args The parsed argument list.
368 */
369 public static void preConstructorInit(Map<String, Collection<String>> args) {
370 try {
371 Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
372 } catch (final Exception e) {
373 e.printStackTrace();
374 JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using EPSG:4263."));
375 Main.proj = new Epsg4326();
376 }
377
378 try {
379 UIManager.setLookAndFeel(Main.pref.get("laf"));
380 toolbar = new ToolbarPreferences();
381 contentPane.updateUI();
382 panel.updateUI();
383 } catch (final Exception e) {
384 e.printStackTrace();
385 }
386 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
387 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
388 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
389 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
390
391 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
392 if (args.containsKey("geometry")) {
393 String geometry = args.get("geometry").iterator().next();
394 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
395 if (m.matches()) {
396 int w = Integer.valueOf(m.group(1));
397 int h = Integer.valueOf(m.group(2));
398 int x = 0, y = 0;
399 if (m.group(3) != null) {
400 x = Integer.valueOf(m.group(5));
401 y = Integer.valueOf(m.group(7));
402 if (m.group(4).equals("-"))
403 x = screenDimension.width - x - w;
404 if (m.group(6).equals("-"))
405 y = screenDimension.height - y - h;
406 }
407 bounds = new Rectangle(x,y,w,h);
408 } else
409 System.out.println("Ignoring malformed geometry: "+geometry);
410 }
411 if (bounds == null)
412 bounds = !args.containsKey("no-fullscreen") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
413
414 // preinitialize a wait dialog for all early downloads (e.g. via command line)
415 pleaseWaitDlg = new PleaseWaitDialog(null);
416 }
417
418 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
419 // initialize the pleaseWaitDialog with the application as parent to handle focus stuff
420 pleaseWaitDlg = new PleaseWaitDialog(parent);
421
422 if (args.containsKey("download"))
423 for (String s : args.get("download"))
424 downloadFromParamString(false, s);
425 if (args.containsKey("downloadgps"))
426 for (String s : args.get("downloadgps"))
427 downloadFromParamString(true, s);
428 if (args.containsKey("selection"))
429 for (String s : args.get("selection"))
430 SearchAction.search(s, SearchAction.SearchMode.add, false);
431 }
432
433 public static boolean breakBecauseUnsavedChanges() {
434 Shortcut.savePrefs();
435 if (map != null) {
436 boolean modified = false;
437 boolean uploadedModified = false;
438 for (final Layer l : map.mapView.getAllLayers()) {
439 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
440 modified = true;
441 uploadedModified = ((OsmDataLayer)l).uploadedModified;
442 break;
443 }
444 }
445 if (modified) {
446 final String msg = uploadedModified ? "\n"+tr("Hint: Some changes came from uploading new data to the server.") : "";
447 final int answer = JOptionPane.showConfirmDialog(
448 parent, tr("There are unsaved changes. Discard the changes and continue?")+msg,
449 tr("Unsaved Changes"), JOptionPane.YES_NO_OPTION);
450 if (answer != JOptionPane.YES_OPTION)
451 return true;
452 }
453 }
454 return false;
455 }
456
457 private static void downloadFromParamString(final boolean rawGps, String s) {
458 if (s.startsWith("http:")) {
459 final Bounds b = BoundingBoxSelection.osmurl2bounds(s);
460 if (b == null)
461 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed url: \"{0}\"", s));
462 else {
463 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
464 DownloadTask osmTask = new DownloadOsmTask();
465 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
466 }
467 return;
468 }
469
470 if (s.startsWith("file:")) {
471 try {
472 main.menu.open.openFile(new File(new URI(s)));
473 } catch (URISyntaxException e) {
474 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file url: \"{0}\"", s));
475 }
476 return;
477 }
478
479 final StringTokenizer st = new StringTokenizer(s, ",");
480 if (st.countTokens() == 4) {
481 try {
482 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
483 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
484 return;
485 } catch (final NumberFormatException e) {
486 }
487 }
488
489 main.menu.open.openFile(new File(s));
490 }
491
492 protected static void determinePlatformHook() {
493 String os = System.getProperty("os.name");
494 if (os == null) {
495 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
496 platform = new PlatformHookUnixoid();
497 } else if (os.toLowerCase().startsWith("windows")) {
498 platform = new PlatformHookWindows();
499 } else if (os.equals("Linux") || os.equals("Solaris") ||
500 os.equals("SunOS") || os.equals("AIX") ||
501 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
502 platform = new PlatformHookUnixoid();
503 } else if (os.toLowerCase().startsWith("mac os x")) {
504 platform = new PlatformHookOsx();
505 } else {
506 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
507 platform = new PlatformHookUnixoid();
508 }
509 }
510
511}
Note: See TracBrowser for help on using the repository browser.