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

Last change on this file since 1750 was 1750, checked in by Gubaer, 15 years ago

new: replaced global conflict list by conflict list per layer, similar to datasets

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