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

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

version check was reversed

  • 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, remove the map as well.
184 */
185 public final void removeLayer(final Layer layer) {
186 map.mapView.removeLayer(layer);
187 if (layer instanceof OsmDataLayer)
188 ds = new DataSet();
189 if (map.mapView.getAllLayers().isEmpty())
190 setMapFrame(null);
191 }
192
193 public Main() {
194 main = this;
195// platform = determinePlatformHook();
196 platform.startupHook();
197 contentPane.add(panel, BorderLayout.CENTER);
198 panel.add(new GettingStarted(), BorderLayout.CENTER);
199 menu = new MainMenu();
200
201 undoRedo.listenerCommands.add(redoUndoListener);
202
203 // creating toolbar
204 contentPane.add(toolbar.control, BorderLayout.NORTH);
205
206 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ShortCut.registerShortCut("system:help", tr("Help"), KeyEvent.VK_F1, ShortCut.GROUP_DIRECT).getKeyStroke(), "Help");
207 contentPane.getActionMap().put("Help", menu.help);
208
209 TaggingPresetPreference.initialize();
210 MapPaintPreference.initialize();
211
212 toolbar.refreshToolbarControl();
213
214 toolbar.control.updateUI();
215 contentPane.updateUI();
216 }
217
218 /**
219 * Load all plugins specified in preferences. If the parameter is <code>true</code>, all
220 * early plugins are loaded (before constructor).
221 */
222 public static void loadPlugins(boolean early) {
223 List<String> plugins = new LinkedList<String>();
224 Collection<String> cp = Main.pref.getCollection("plugins", null);
225 if (cp != null)
226 plugins.addAll(cp);
227 if (System.getProperty("josm.plugins") != null)
228 plugins.addAll(Arrays.asList(System.getProperty("josm.plugins").split(",")));
229
230 String [] oldplugins = new String[] {"mappaint", "unglueplugin", "lang-de","lang-en_GB","lang-fr","lang-it","lang-pl","lang-ro","lang-ru"};
231 for(String p : oldplugins)
232 {
233 if(plugins.contains(p))
234 {
235 plugins.remove(p);
236 Main.pref.removeFromCollection("plugins", p);
237 System.out.println(tr("Warning - loading of {0} plugin was requested. This plugin is no longer required.", p));
238 }
239 }
240
241 if (plugins.isEmpty())
242 return;
243
244 SortedMap<Integer, Collection<PluginInformation>> p = new TreeMap<Integer, Collection<PluginInformation>>();
245 for (String pluginName : plugins) {
246 PluginInformation info = PluginInformation.findPlugin(pluginName);
247 if (info != null) {
248 if (info.early != early)
249 continue;
250 if (info.mainversion != null && info.mainversion.compareTo(AboutAction.version) > 0)
251 {
252 JOptionPane.showMessageDialog(Main.parent, tr("Plugin requires JOSM update: {0}.", pluginName));
253 continue;
254 }
255 if (!p.containsKey(info.stage))
256 p.put(info.stage, new LinkedList<PluginInformation>());
257 p.get(info.stage).add(info);
258 } else {
259 if (early)
260 System.out.println("Plugin not found: "+pluginName); // do not translate
261 else
262 JOptionPane.showMessageDialog(Main.parent, tr("Plugin not found: {0}.", pluginName));
263 }
264 }
265
266 if(!early)
267 {
268 long tim = System.currentTimeMillis();
269 long last = Main.pref.getLong("pluginmanager.lastupdate", 0);
270 Integer maxTime = Main.pref.getInteger("pluginmanager.warntime", 30*24*60*60);
271 if(last <= 0)
272 {
273 Main.pref.put("pluginmanager.lastupdate",Long.toString(tim));
274 }
275 else if(tim - last >= maxTime*1000*24*60*60)
276 {
277 long d = (tim - last)/(24*60*60*1000);
278 JOptionPane.showMessageDialog(Main.parent, tr("Last plugin update more than {0} days ago.", d));
279 }
280 }
281
282 // iterate all plugins and collect all libraries of all plugins:
283 List<URL> allPluginLibraries = new ArrayList<URL>();
284 for (Collection<PluginInformation> c : p.values())
285 for (PluginInformation info : c)
286 allPluginLibraries.addAll(info.libraries);
287 // create a classloader for all plugins:
288 URL[] jarUrls = new URL[allPluginLibraries.size()];
289 jarUrls = allPluginLibraries.toArray(jarUrls);
290 URLClassLoader pluginClassLoader = new URLClassLoader(jarUrls, Main.class.getClassLoader());
291 ImageProvider.sources.add(0, pluginClassLoader);
292
293 for (Collection<PluginInformation> c : p.values()) {
294 for (PluginInformation info : c) {
295 try {
296 Class<?> klass = info.loadClass(pluginClassLoader);
297 if (klass != null) {
298 System.out.println("loading "+info.name);
299 Main.plugins.add(info.load(klass));
300 }
301 } catch (Throwable e) {
302 e.printStackTrace();
303 boolean remove = true;
304 if (early)
305 System.out.println("Could not load plugin: "+info.name+" - deleted from preferences"); // do not translate
306 else {
307 int answer = JOptionPane.showConfirmDialog(Main.parent,
308 tr("Could not load plugin {0}. Delete from preferences?", info.name,
309 JOptionPane.YES_NO_OPTION));
310 if (answer != JOptionPane.OK_OPTION) {
311 remove = false;
312 }
313 }
314 if (remove) {
315 plugins.remove(info.name);
316 String plist = null;
317 for (String pn : plugins) {
318 if (plist==null) plist=""; else plist=plist+",";
319 plist=plist+pn;
320 }
321 Main.pref.put("plugins", plist);
322 }
323 }
324 }
325 }
326 }
327
328 /**
329 * Add a new layer to the map. If no map exists, create one.
330 */
331 public final void addLayer(final Layer layer) {
332 if (map == null) {
333 final MapFrame mapFrame = new MapFrame();
334 setMapFrame(mapFrame);
335 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
336 mapFrame.setVisible(true);
337 mapFrame.setVisibleDialogs();
338 }
339 map.mapView.addLayer(layer);
340 }
341 /**
342 * @return The edit osm layer. If none exists, it will be created.
343 */
344 public final OsmDataLayer editLayer() {
345 if (map == null || map.mapView.editLayer == null)
346 menu.newAction.actionPerformed(null);
347 return map.mapView.editLayer;
348 }
349
350
351
352
353 /**
354 * Use this to register shortcuts to
355 */
356 public static final JPanel contentPane = new JPanel(new BorderLayout());
357
358
359 ////////////////////////////////////////////////////////////////////////////////////////
360 // Implementation part
361 ////////////////////////////////////////////////////////////////////////////////////////
362
363 public static JPanel panel = new JPanel(new BorderLayout());
364
365 protected static Rectangle bounds;
366
367 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
368 public void commandChanged(final int queueSize, final int redoSize) {
369 menu.undo.setEnabled(queueSize > 0);
370 menu.redo.setEnabled(redoSize > 0);
371 }
372 };
373 /**
374 * Should be called before the main constructor to setup some parameter stuff
375 * @param args The parsed argument list.
376 */
377 public static void preConstructorInit(Map<String, Collection<String>> args) {
378 try {
379 Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
380 } catch (final Exception e) {
381 e.printStackTrace();
382 JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using EPSG:4263."));
383 Main.proj = new Epsg4326();
384 }
385
386 try {
387 UIManager.setLookAndFeel(Main.pref.get("laf"));
388 toolbar = new ToolbarPreferences();
389 contentPane.updateUI();
390 panel.updateUI();
391 } catch (final Exception e) {
392 e.printStackTrace();
393 }
394 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
395 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
396 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
397 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
398
399 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
400 if (args.containsKey("geometry")) {
401 String geometry = args.get("geometry").iterator().next();
402 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
403 if (m.matches()) {
404 int w = Integer.valueOf(m.group(1));
405 int h = Integer.valueOf(m.group(2));
406 int x = 0, y = 0;
407 if (m.group(3) != null) {
408 x = Integer.valueOf(m.group(5));
409 y = Integer.valueOf(m.group(7));
410 if (m.group(4).equals("-"))
411 x = screenDimension.width - x - w;
412 if (m.group(6).equals("-"))
413 y = screenDimension.height - y - h;
414 }
415 bounds = new Rectangle(x,y,w,h);
416 } else
417 System.out.println("Ignoring malformed geometry: "+geometry);
418 }
419 if (bounds == null)
420 bounds = !args.containsKey("no-fullscreen") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
421
422 // preinitialize a wait dialog for all early downloads (e.g. via command line)
423 pleaseWaitDlg = new PleaseWaitDialog(null);
424 }
425
426 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
427 // initialize the pleaseWaitDialog with the application as parent to handle focus stuff
428 pleaseWaitDlg = new PleaseWaitDialog(parent);
429
430 if (args.containsKey("download"))
431 for (String s : args.get("download"))
432 downloadFromParamString(false, s);
433 if (args.containsKey("downloadgps"))
434 for (String s : args.get("downloadgps"))
435 downloadFromParamString(true, s);
436 if (args.containsKey("selection"))
437 for (String s : args.get("selection"))
438 SearchAction.search(s, SearchAction.SearchMode.add, false);
439 }
440
441 public static boolean breakBecauseUnsavedChanges() {
442 ShortCut.savePrefs();
443 if (map != null) {
444 boolean modified = false;
445 boolean uploadedModified = false;
446 for (final Layer l : map.mapView.getAllLayers()) {
447 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
448 modified = true;
449 uploadedModified = ((OsmDataLayer)l).uploadedModified;
450 break;
451 }
452 }
453 if (modified) {
454 final String msg = uploadedModified ? "\n"+tr("Hint: Some changes came from uploading new data to the server.") : "";
455 final int answer = JOptionPane.showConfirmDialog(
456 parent, tr("There are unsaved changes. Discard the changes and continue?")+msg,
457 tr("Unsaved Changes"), JOptionPane.YES_NO_OPTION);
458 if (answer != JOptionPane.YES_OPTION)
459 return true;
460 }
461 }
462 return false;
463 }
464
465 private static void downloadFromParamString(final boolean rawGps, String s) {
466 if (s.startsWith("http:")) {
467 final Bounds b = BoundingBoxSelection.osmurl2bounds(s);
468 if (b == null)
469 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed url: \"{0}\"", s));
470 else {
471 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
472 DownloadTask osmTask = new DownloadOsmTask();
473 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
474 }
475 return;
476 }
477
478 if (s.startsWith("file:")) {
479 try {
480 main.menu.open.openFile(new File(new URI(s)));
481 } catch (URISyntaxException e) {
482 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file url: \"{0}\"", s));
483 }
484 return;
485 }
486
487 final StringTokenizer st = new StringTokenizer(s, ",");
488 if (st.countTokens() == 4) {
489 try {
490 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
491 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
492 return;
493 } catch (final NumberFormatException e) {
494 }
495 }
496
497 main.menu.open.openFile(new File(s));
498 }
499
500 protected static void determinePlatformHook() {
501 String os = System.getProperty("os.name");
502 if (os == null) {
503 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
504 platform = new PlatformHookUnixoid();
505 } else if (os.toLowerCase().startsWith("windows")) {
506 platform = new PlatformHookWindows();
507 } else if (os.equals("Linux") || os.equals("Solaris") || os.equals("SunOS") || os.equals("AIX") || os.equals("FreeBSD")) {
508 platform = new PlatformHookUnixoid();
509 } else if (os.toLowerCase().startsWith("mac os x")) {
510 platform = new PlatformHookOsx();
511 } else {
512 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
513 platform = new PlatformHookUnixoid();
514 }
515 }
516
517}
Note: See TracBrowser for help on using the repository browser.