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

Last change on this file since 1058 was 1058, checked in by mfloryan, 15 years ago

Changed infrastructure of JOSM translations. lang-* plugins are now
obsolete. Translations are integrated into core via lang-translation.jar
in /lib directory. Ant scripts are updated automated build may require
an update. Source translation files are still kept in JOSM SVN repo.

  • Property svn:eol-style set to native
File size: 16.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.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) {
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", "lang-de","lang-en_GB","lang-fr","lang-it","lang-pl","lang-ro","lang-ru"};
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
238 if (plugins.isEmpty())
239 return;
240
241 SortedMap<Integer, Collection<PluginInformation>> p = new TreeMap<Integer, Collection<PluginInformation>>();
242 for (String pluginName : plugins) {
243 PluginInformation info = PluginInformation.findPlugin(pluginName);
244 if (info != null) {
245 if (info.early != early)
246 continue;
247 if (!p.containsKey(info.stage))
248 p.put(info.stage, new LinkedList<PluginInformation>());
249 p.get(info.stage).add(info);
250 } else {
251 if (early)
252 System.out.println("Plugin not found: "+pluginName); // do not translate
253 else
254 JOptionPane.showMessageDialog(Main.parent, tr("Plugin not found: {0}.", pluginName));
255 }
256 }
257
258 // iterate all plugins and collect all libraries of all plugins:
259 List<URL> allPluginLibraries = new ArrayList<URL>();
260 for (Collection<PluginInformation> c : p.values())
261 for (PluginInformation info : c)
262 allPluginLibraries.addAll(info.libraries);
263 // create a classloader for all plugins:
264 URL[] jarUrls = new URL[allPluginLibraries.size()];
265 jarUrls = allPluginLibraries.toArray(jarUrls);
266 URLClassLoader pluginClassLoader = new URLClassLoader(jarUrls, Main.class.getClassLoader());
267 ImageProvider.sources.add(0, pluginClassLoader);
268
269 for (Collection<PluginInformation> c : p.values()) {
270 for (PluginInformation info : c) {
271 try {
272 Class<?> klass = info.loadClass(pluginClassLoader);
273 if (klass != null) {
274 System.out.println("loading "+info.name);
275 Main.plugins.add(info.load(klass));
276 }
277 } catch (Throwable e) {
278 e.printStackTrace();
279 boolean remove = true;
280 if (early)
281 System.out.println("Could not load plugin: "+info.name+" - deleted from preferences"); // do not translate
282 else {
283 int answer = JOptionPane.showConfirmDialog(Main.parent,
284 tr("Could not load plugin {0}. Delete from preferences?", info.name,
285 JOptionPane.YES_NO_OPTION));
286 if (answer != JOptionPane.OK_OPTION) {
287 remove = false;
288 }
289 }
290 if (remove) {
291 plugins.remove(info.name);
292 String plist = null;
293 for (String pn : plugins) {
294 if (plist==null) plist=""; else plist=plist+",";
295 plist=plist+pn;
296 }
297 Main.pref.put("plugins", plist);
298 }
299 }
300 }
301 }
302 }
303
304 /**
305 * Add a new layer to the map. If no map exists, create one.
306 */
307 public final void addLayer(final Layer layer) {
308 if (map == null) {
309 final MapFrame mapFrame = new MapFrame();
310 setMapFrame(mapFrame);
311 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
312 mapFrame.setVisible(true);
313 mapFrame.setVisibleDialogs();
314 }
315 map.mapView.addLayer(layer);
316 }
317 /**
318 * @return The edit osm layer. If none exists, it will be created.
319 */
320 public final OsmDataLayer editLayer() {
321 if (map == null || map.mapView.editLayer == null)
322 menu.newAction.actionPerformed(null);
323 return map.mapView.editLayer;
324 }
325
326
327
328
329 /**
330 * Use this to register shortcuts to
331 */
332 public static final JPanel contentPane = new JPanel(new BorderLayout());
333
334
335 ////////////////////////////////////////////////////////////////////////////////////////
336 // Implementation part
337 ////////////////////////////////////////////////////////////////////////////////////////
338
339 public static JPanel panel = new JPanel(new BorderLayout());
340
341 protected static Rectangle bounds;
342
343 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
344 public void commandChanged(final int queueSize, final int redoSize) {
345 menu.undo.setEnabled(queueSize > 0);
346 menu.redo.setEnabled(redoSize > 0);
347 }
348 };
349 /**
350 * Should be called before the main constructor to setup some parameter stuff
351 * @param args The parsed argument list.
352 */
353 public static void preConstructorInit(Map<String, Collection<String>> args) {
354 try {
355 Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
356 } catch (final Exception e) {
357 e.printStackTrace();
358 JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using EPSG:4263."));
359 Main.proj = new Epsg4326();
360 }
361
362 try {
363 UIManager.setLookAndFeel(Main.pref.get("laf"));
364 toolbar = new ToolbarPreferences();
365 contentPane.updateUI();
366 panel.updateUI();
367 } catch (final Exception e) {
368 e.printStackTrace();
369 }
370 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
371 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
372 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
373 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
374
375 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
376 if (args.containsKey("geometry")) {
377 String geometry = args.get("geometry").iterator().next();
378 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
379 if (m.matches()) {
380 int w = Integer.valueOf(m.group(1));
381 int h = Integer.valueOf(m.group(2));
382 int x = 0, y = 0;
383 if (m.group(3) != null) {
384 x = Integer.valueOf(m.group(5));
385 y = Integer.valueOf(m.group(7));
386 if (m.group(4).equals("-"))
387 x = screenDimension.width - x - w;
388 if (m.group(6).equals("-"))
389 y = screenDimension.height - y - h;
390 }
391 bounds = new Rectangle(x,y,w,h);
392 } else
393 System.out.println("Ignoring malformed geometry: "+geometry);
394 }
395 if (bounds == null)
396 bounds = !args.containsKey("no-fullscreen") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
397
398 // preinitialize a wait dialog for all early downloads (e.g. via command line)
399 pleaseWaitDlg = new PleaseWaitDialog(null);
400 }
401
402 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
403 // initialize the pleaseWaitDialog with the application as parent to handle focus stuff
404 pleaseWaitDlg = new PleaseWaitDialog(parent);
405
406 if (args.containsKey("download"))
407 for (String s : args.get("download"))
408 downloadFromParamString(false, s);
409 if (args.containsKey("downloadgps"))
410 for (String s : args.get("downloadgps"))
411 downloadFromParamString(true, s);
412 if (args.containsKey("selection"))
413 for (String s : args.get("selection"))
414 SearchAction.search(s, SearchAction.SearchMode.add, false);
415 }
416
417 public static boolean breakBecauseUnsavedChanges() {
418 ShortCut.savePrefs();
419 if (map != null) {
420 boolean modified = false;
421 boolean uploadedModified = false;
422 for (final Layer l : map.mapView.getAllLayers()) {
423 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
424 modified = true;
425 uploadedModified = ((OsmDataLayer)l).uploadedModified;
426 break;
427 }
428 }
429 if (modified) {
430 final String msg = uploadedModified ? "\n"+tr("Hint: Some changes came from uploading new data to the server.") : "";
431 final int answer = JOptionPane.showConfirmDialog(
432 parent, tr("There are unsaved changes. Discard the changes and continue?")+msg,
433 tr("Unsaved Changes"), JOptionPane.YES_NO_OPTION);
434 if (answer != JOptionPane.YES_OPTION)
435 return true;
436 }
437 }
438 return false;
439 }
440
441 private static void downloadFromParamString(final boolean rawGps, String s) {
442 if (s.startsWith("http:")) {
443 final Bounds b = BoundingBoxSelection.osmurl2bounds(s);
444 if (b == null)
445 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed url: \"{0}\"", s));
446 else {
447 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
448 DownloadTask osmTask = new DownloadOsmTask();
449 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
450 }
451 return;
452 }
453
454 if (s.startsWith("file:")) {
455 try {
456 main.menu.open.openFile(new File(new URI(s)));
457 } catch (URISyntaxException e) {
458 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file url: \"{0}\"", s));
459 }
460 return;
461 }
462
463 final StringTokenizer st = new StringTokenizer(s, ",");
464 if (st.countTokens() == 4) {
465 try {
466 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
467 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
468 return;
469 } catch (final NumberFormatException e) {
470 }
471 }
472
473 main.menu.open.openFile(new File(s));
474 }
475
476 protected static void determinePlatformHook() {
477 String os = System.getProperty("os.name");
478 if (os == null) {
479 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
480 platform = new PlatformHookUnixoid();
481 } else if (os.toLowerCase().startsWith("windows")) {
482 platform = new PlatformHookWindows();
483 } else if (os.equals("Linux") || os.equals("Solaris") || os.equals("SunOS") || os.equals("AIX") || os.equals("FreeBSD")) {
484 platform = new PlatformHookUnixoid();
485 } else if (os.toLowerCase().startsWith("mac os x")) {
486 platform = new PlatformHookOsx();
487 } else {
488 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
489 platform = new PlatformHookUnixoid();
490 }
491 }
492
493}
Note: See TracBrowser for help on using the repository browser.