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

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

reworked plugin handling a lot, more to come

  • Property svn:eol-style set to native
File size: 15.7 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.util.Collection;
15import java.util.Locale;
16import java.util.Map;
17import java.util.StringTokenizer;
18import java.util.concurrent.Executor;
19import java.util.concurrent.Executors;
20import java.util.regex.Matcher;
21import java.util.regex.Pattern;
22
23import javax.swing.JComponent;
24import javax.swing.JOptionPane;
25import javax.swing.JPanel;
26import javax.swing.UIManager;
27
28import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
29import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
30import org.openstreetmap.josm.actions.mapmode.MapMode;
31import org.openstreetmap.josm.actions.search.SearchAction;
32import org.openstreetmap.josm.data.Bounds;
33import org.openstreetmap.josm.data.Preferences;
34import org.openstreetmap.josm.data.UndoRedoHandler;
35import org.openstreetmap.josm.data.osm.DataSet;
36import org.openstreetmap.josm.data.projection.Epsg4326;
37import org.openstreetmap.josm.data.projection.Projection;
38import org.openstreetmap.josm.gui.GettingStarted;
39import org.openstreetmap.josm.gui.MainMenu;
40import org.openstreetmap.josm.gui.MapFrame;
41import org.openstreetmap.josm.gui.PleaseWaitDialog;
42import org.openstreetmap.josm.gui.SplashScreen;
43import org.openstreetmap.josm.gui.download.DownloadDialog.DownloadTask;
44import org.openstreetmap.josm.gui.layer.Layer;
45import org.openstreetmap.josm.gui.layer.OsmDataLayer;
46import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
47import org.openstreetmap.josm.gui.preferences.MapPaintPreference;
48import org.openstreetmap.josm.gui.preferences.TaggingPresetPreference;
49import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
50import org.openstreetmap.josm.plugins.PluginHandler;
51import org.openstreetmap.josm.tools.ImageProvider;
52import org.openstreetmap.josm.tools.OsmUrlToBounds;
53import org.openstreetmap.josm.tools.PlatformHook;
54import org.openstreetmap.josm.tools.PlatformHookUnixoid;
55import org.openstreetmap.josm.tools.PlatformHookWindows;
56import org.openstreetmap.josm.tools.PlatformHookOsx;
57import org.openstreetmap.josm.tools.Shortcut;
58
59abstract public class Main {
60 /**
61 * Global parent component for all dialogs and message boxes
62 */
63 public static Component parent;
64 /**
65 * Global application.
66 */
67 public static Main main;
68 /**
69 * The worker thread slave. This is for executing all long and intensive
70 * calculations. The executed runnables are guaranteed to be executed separately
71 * and sequential.
72 */
73 public final static Executor worker = Executors.newSingleThreadExecutor();
74 /**
75 * Global application preferences
76 */
77 public static Preferences pref = new Preferences();
78 /**
79 * The global dataset.
80 */
81 public static DataSet ds = new DataSet();
82 /**
83 * The global paste buffer.
84 */
85 public static DataSet pasteBuffer = new DataSet();
86 /**
87 * The projection method used.
88 */
89 public static Projection proj;
90 /**
91 * The MapFrame. Use setMapFrame to set or clear it.
92 */
93 public static MapFrame map;
94 /**
95 * The dialog that gets displayed during background task execution.
96 */
97 public static PleaseWaitDialog pleaseWaitDlg;
98
99 /**
100 * True, when in applet mode
101 */
102 public static boolean applet = false;
103
104 /**
105 * The toolbar preference control to register new actions.
106 */
107 public static ToolbarPreferences toolbar;
108
109
110 public UndoRedoHandler undoRedo = new UndoRedoHandler();
111
112 /**
113 * The main menu bar at top of screen.
114 */
115 public final MainMenu menu;
116
117 /**
118 * Print a debug message if debugging is on.
119 */
120 static public int debug_level = 1;
121 static public final void debug(String msg) {
122 if (debug_level <= 0)
123 return;
124 System.out.println(msg);
125 }
126
127 /**
128 * Platform specific code goes in here.
129 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
130 * So if you need to hook into those early ones, split your class and send the one with the early hooks
131 * to the JOSM team for inclusion.
132 */
133 public static PlatformHook platform;
134
135 /**
136 * Set or clear (if passed <code>null</code>) the map.
137 */
138 public final void setMapFrame(final MapFrame map) {
139 MapFrame old = Main.map;
140 Main.map = map;
141 panel.setVisible(false);
142 panel.removeAll();
143 if (map != null)
144 map.fillPanel(panel);
145 else {
146 old.destroy();
147 panel.add(new GettingStarted(), BorderLayout.CENTER);
148 }
149 panel.setVisible(true);
150 redoUndoListener.commandChanged(0,0);
151
152 PluginHandler.setMapFrame(old, map);
153 }
154
155 /**
156 * Remove the specified layer from the map. If it is the last layer,
157 * remove the map as well.
158 */
159 public final void removeLayer(final Layer layer) {
160 map.mapView.removeLayer(layer);
161 if (layer instanceof OsmDataLayer)
162 ds = new DataSet();
163 if (map.mapView.getAllLayers().isEmpty())
164 setMapFrame(null);
165 }
166
167 public Main() {
168 this(null);
169 }
170
171 public Main(SplashScreen splash) {
172 main = this;
173// platform = determinePlatformHook();
174 platform.startupHook();
175 contentPane.add(panel, BorderLayout.CENTER);
176 if(splash != null) splash.setStatus(tr("Download \"Message of the day\""));
177 panel.add(new GettingStarted(), BorderLayout.CENTER);
178
179 if(splash != null) splash.setStatus(tr("Creating main GUI"));
180 menu = new MainMenu();
181
182 undoRedo.listenerCommands.add(redoUndoListener);
183
184 // creating toolbar
185 contentPane.add(toolbar.control, BorderLayout.NORTH);
186
187 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
188 .put(Shortcut.registerShortcut("system:help", tr("Help"),
189 KeyEvent.VK_F1, Shortcut.GROUP_DIRECT).getKeyStroke(), "Help");
190 contentPane.getActionMap().put("Help", menu.help);
191
192 TaggingPresetPreference.initialize();
193 MapPaintPreference.initialize();
194
195 toolbar.refreshToolbarControl();
196
197 toolbar.control.updateUI();
198 contentPane.updateUI();
199 }
200
201 /**
202 * Add a new layer to the map. If no map exists, create one.
203 */
204 public final void addLayer(final Layer layer) {
205 if (map == null) {
206 final MapFrame mapFrame = new MapFrame();
207 setMapFrame(mapFrame);
208 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
209 mapFrame.setVisible(true);
210 mapFrame.setVisibleDialogs();
211 }
212 map.mapView.addLayer(layer);
213 }
214 /**
215 * @return The edit osm layer. If none exists, it will be created.
216 */
217 public final OsmDataLayer editLayer() {
218 if (map == null || map.mapView.editLayer == null)
219 menu.newAction.actionPerformed(null);
220 return map.mapView.editLayer;
221 }
222
223 /**
224 * Use this to register shortcuts to
225 */
226 public static final JPanel contentPane = new JPanel(new BorderLayout());
227
228 ///////////////////////////////////////////////////////////////////////////
229 // Implementation part
230 ///////////////////////////////////////////////////////////////////////////
231
232 public static JPanel panel = new JPanel(new BorderLayout());
233
234 protected static Rectangle bounds;
235
236 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
237 public void commandChanged(final int queueSize, final int redoSize) {
238 menu.undo.setEnabled(queueSize > 0);
239 menu.redo.setEnabled(redoSize > 0);
240 }
241 };
242 /**
243 * Should be called before the main constructor to setup some parameter stuff
244 * @param args The parsed argument list.
245 */
246 public static void preConstructorInit(Map<String, Collection<String>> args) {
247 try {
248 Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
249 } catch (final Exception e) {
250 e.printStackTrace();
251 JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using EPSG:4326"));
252 Main.proj = new Epsg4326();
253 }
254
255 try {
256 try {
257 String laf = Main.pref.get("laf");
258 if(laf != null && laf.length() > 0)
259 UIManager.setLookAndFeel(laf);
260 }
261 catch (final javax.swing.UnsupportedLookAndFeelException e) {
262 System.out.println("Look and Feel not supported: " + Main.pref.get("laf"));
263 }
264 toolbar = new ToolbarPreferences();
265 contentPane.updateUI();
266 panel.updateUI();
267 } catch (final Exception e) {
268 e.printStackTrace();
269 }
270 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
271 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
272 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
273 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
274
275 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
276 String geometry = Main.pref.get("gui.geometry");
277 if (args.containsKey("geometry")) {
278 geometry = args.get("geometry").iterator().next();
279 }
280 if (geometry.length() != 0) {
281 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
282 if (m.matches()) {
283 int w = Integer.valueOf(m.group(1));
284 int h = Integer.valueOf(m.group(2));
285 int x = 0, y = 0;
286 if (m.group(3) != null) {
287 x = Integer.valueOf(m.group(5));
288 y = Integer.valueOf(m.group(7));
289 if (m.group(4).equals("-"))
290 x = screenDimension.width - x - w;
291 if (m.group(6).equals("-"))
292 y = screenDimension.height - y - h;
293 }
294 bounds = new Rectangle(x,y,w,h);
295 if(!Main.pref.get("gui.geometry").equals(geometry)) {
296 // remember this geometry
297 Main.pref.put("gui.geometry", geometry);
298 }
299 } else
300 System.out.println("Ignoring malformed geometry: "+geometry);
301 }
302 if (bounds == null)
303 bounds = !args.containsKey("no-fullscreen") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
304
305 // preinitialize a wait dialog for all early downloads (e.g. via command line)
306 pleaseWaitDlg = new PleaseWaitDialog(null);
307 }
308
309 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
310 // initialize the pleaseWaitDialog with the application as parent to handle focus stuff
311 pleaseWaitDlg = new PleaseWaitDialog(parent);
312
313 if (args.containsKey("download"))
314 for (String s : args.get("download"))
315 downloadFromParamString(false, s);
316 if (args.containsKey("downloadgps"))
317 for (String s : args.get("downloadgps"))
318 downloadFromParamString(true, s);
319 if (args.containsKey("selection"))
320 for (String s : args.get("selection"))
321 SearchAction.search(s, SearchAction.SearchMode.add, false, false);
322 }
323
324 public static boolean breakBecauseUnsavedChanges() {
325 Shortcut.savePrefs();
326 if (map != null) {
327 boolean modified = false;
328 boolean uploadedModified = false;
329 for (final Layer l : map.mapView.getAllLayers()) {
330 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
331 modified = true;
332 uploadedModified = ((OsmDataLayer)l).uploadedModified;
333 break;
334 }
335 }
336 if (modified) {
337 final String msg = uploadedModified ? "\n"+tr("Hint: Some changes came from uploading new data to the server.") : "";
338 final int answer = JOptionPane.showConfirmDialog(
339 parent, tr("There are unsaved changes. Discard the changes and continue?")+msg,
340 tr("Unsaved Changes"), JOptionPane.YES_NO_OPTION);
341 if (answer != JOptionPane.YES_OPTION)
342 return true;
343 }
344 }
345 return false;
346 }
347
348 private static void downloadFromParamString(final boolean rawGps, String s) {
349 if (s.startsWith("http:")) {
350 final Bounds b = OsmUrlToBounds.parse(s);
351 if (b == null)
352 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed URL: \"{0}\"", s));
353 else {
354 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
355 DownloadTask osmTask = new DownloadOsmTask();
356 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
357 }
358 return;
359 }
360
361 if (s.startsWith("file:")) {
362 try {
363 main.menu.openFile.openFile(new File(new URI(s)));
364 } catch (URISyntaxException e) {
365 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file URL: \"{0}\"", s));
366 }
367 return;
368 }
369
370 final StringTokenizer st = new StringTokenizer(s, ",");
371 if (st.countTokens() == 4) {
372 try {
373 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
374 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
375 return;
376 } catch (final NumberFormatException e) {
377 }
378 }
379
380 main.menu.openFile.openFile(new File(s));
381 }
382
383 protected static void determinePlatformHook() {
384 String os = System.getProperty("os.name");
385 if (os == null) {
386 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
387 platform = new PlatformHookUnixoid();
388 } else if (os.toLowerCase().startsWith("windows")) {
389 platform = new PlatformHookWindows();
390 } else if (os.equals("Linux") || os.equals("Solaris") ||
391 os.equals("SunOS") || os.equals("AIX") ||
392 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
393 platform = new PlatformHookUnixoid();
394 } else if (os.toLowerCase().startsWith("mac os x")) {
395 platform = new PlatformHookOsx();
396 } else {
397 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
398 platform = new PlatformHookUnixoid();
399 }
400 }
401
402 static public String getLanguageCodeU()
403 {
404 String languageCode = Locale.getDefault().getLanguage();
405 return languageCode.substring(0,1).toUpperCase() + languageCode.substring(1) + ":";
406 }
407 static public String getLanguageCode()
408 {
409 return Locale.getDefault().getLanguage() + ":";
410 }
411
412 static public void saveGuiGeometry() {
413 // if the gui.geometry preference is already set,
414 // save the current window geometry
415 String curGeometryPref = pref.get("gui.geometry");
416 if(curGeometryPref.length() != 0) {
417 Rectangle bounds = parent.getBounds();
418 pref.put("gui.geometry",
419 (int)bounds.getWidth() +
420 "x" + (int)bounds.getHeight() +
421 "+" + (int)bounds.getX() +
422 "+" + (int)bounds.getY());
423 }
424 }
425}
Note: See TracBrowser for help on using the repository browser.