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

Last change on this file since 1047 was 1047, checked in by cbrill, 16 years ago

[Cleanup] Remove unused imports and unused variables, part 2

This cleanup does not include static imports for translation

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