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

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

fixed #2583 - patch by Michel Marti - fon't move objects when copying between layers

  • Property svn:eol-style set to native
File size: 17.6 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.Epsg4326;
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 map.mapView.removeLayer(layer);
170 if (layer instanceof OsmDataLayer)
171 ds = new DataSet();
172 if (map.mapView.getAllLayers().isEmpty())
173 setMapFrame(null);
174 }
175
176 public Main() {
177 this(null);
178 }
179
180 public Main(SplashScreen splash) {
181 main = this;
182// platform = determinePlatformHook();
183 platform.startupHook();
184 contentPane.add(panel, BorderLayout.CENTER);
185 panel.add(gettingStarted, BorderLayout.CENTER);
186
187 if(splash != null) splash.setStatus(tr("Creating main GUI"));
188 menu = new MainMenu();
189
190 undoRedo.listenerCommands.add(redoUndoListener);
191
192 // creating toolbar
193 contentPane.add(toolbar.control, BorderLayout.NORTH);
194
195 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
196 .put(Shortcut.registerShortcut("system:help", tr("Help"),
197 KeyEvent.VK_F1, Shortcut.GROUP_DIRECT).getKeyStroke(), "Help");
198 contentPane.getActionMap().put("Help", menu.help);
199
200 TaggingPresetPreference.initialize();
201 MapPaintPreference.initialize();
202
203 toolbar.refreshToolbarControl();
204
205 toolbar.control.updateUI();
206 contentPane.updateUI();
207 }
208
209 /**
210 * Add a new layer to the map. If no map exists, create one.
211 */
212 public final void addLayer(final Layer layer) {
213 if (map == null) {
214 final MapFrame mapFrame = new MapFrame();
215 setMapFrame(mapFrame);
216 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
217 mapFrame.setVisible(true);
218 mapFrame.setVisibleDialogs();
219 }
220 map.mapView.addLayer(layer);
221 }
222 /**
223 * @return The edit osm layer. If none exists, it will be created.
224 */
225 public final OsmDataLayer editLayer() {
226 if (map == null || map.mapView.editLayer == null)
227 menu.newAction.actionPerformed(null);
228 return map.mapView.editLayer;
229 }
230
231 /**
232 * Use this to register shortcuts to
233 */
234 public static final JPanel contentPane = new JPanel(new BorderLayout());
235
236 ///////////////////////////////////////////////////////////////////////////
237 // Implementation part
238 ///////////////////////////////////////////////////////////////////////////
239
240 public static JPanel panel = new JPanel(new BorderLayout());
241
242 protected static Rectangle bounds;
243
244 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
245 public void commandChanged(final int queueSize, final int redoSize) {
246 menu.undo.setEnabled(queueSize > 0);
247 menu.redo.setEnabled(redoSize > 0);
248 }
249 };
250 /**
251 * Should be called before the main constructor to setup some parameter stuff
252 * @param args The parsed argument list.
253 */
254 public static void preConstructorInit(Map<String, Collection<String>> args) {
255 try {
256 Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
257 } catch (final Exception e) {
258 e.printStackTrace();
259 JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using EPSG:4326"));
260 Main.proj = new Epsg4326();
261 }
262
263 try {
264 try {
265 String laf = Main.pref.get("laf");
266 if(laf != null && laf.length() > 0)
267 UIManager.setLookAndFeel(laf);
268 }
269 catch (final javax.swing.UnsupportedLookAndFeelException e) {
270 System.out.println("Look and Feel not supported: " + Main.pref.get("laf"));
271 }
272 toolbar = new ToolbarPreferences();
273 contentPane.updateUI();
274 panel.updateUI();
275 } catch (final Exception e) {
276 e.printStackTrace();
277 }
278 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
279 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
280 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
281 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
282
283 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
284 String geometry = Main.pref.get("gui.geometry");
285 if (args.containsKey("geometry")) {
286 geometry = args.get("geometry").iterator().next();
287 }
288 if (geometry.length() != 0) {
289 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
290 if (m.matches()) {
291 int w = Integer.valueOf(m.group(1));
292 int h = Integer.valueOf(m.group(2));
293 int x = 0, y = 0;
294 if (m.group(3) != null) {
295 x = Integer.valueOf(m.group(5));
296 y = Integer.valueOf(m.group(7));
297 if (m.group(4).equals("-"))
298 x = screenDimension.width - x - w;
299 if (m.group(6).equals("-"))
300 y = screenDimension.height - y - h;
301 }
302 bounds = new Rectangle(x,y,w,h);
303 if(!Main.pref.get("gui.geometry").equals(geometry)) {
304 // remember this geometry
305 Main.pref.put("gui.geometry", geometry);
306 }
307 } else {
308 System.out.println("Ignoring malformed geometry: "+geometry);
309 }
310 }
311 if (bounds == null)
312 bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
313
314 // preinitialize a wait dialog for all early downloads (e.g. via command line)
315 pleaseWaitDlg = new PleaseWaitDialog(null);
316 }
317
318 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
319 // initialize the pleaseWaitDialog with the application as parent to handle focus stuff
320 pleaseWaitDlg = new PleaseWaitDialog(parent);
321
322 if (args.containsKey("download"))
323 for (String s : args.get("download"))
324 downloadFromParamString(false, s);
325 if (args.containsKey("downloadgps"))
326 for (String s : args.get("downloadgps"))
327 downloadFromParamString(true, s);
328 if (args.containsKey("selection"))
329 for (String s : args.get("selection"))
330 SearchAction.search(s, SearchAction.SearchMode.add, false, false);
331 }
332
333 public static boolean breakBecauseUnsavedChanges() {
334 Shortcut.savePrefs();
335 if (map != null) {
336 boolean modified = false;
337 boolean uploadedModified = false;
338 for (final Layer l : map.mapView.getAllLayers()) {
339 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
340 modified = true;
341 uploadedModified = ((OsmDataLayer)l).uploadedModified;
342 break;
343 }
344 }
345 if (modified) {
346 final String msg = uploadedModified ? "\n"
347 +tr("Hint: Some changes came from uploading new data to the server.") : "";
348 int result = new ExtendedDialog(parent, tr("Unsaved Changes"),
349 new javax.swing.JLabel(tr("There are unsaved changes. Discard the changes and continue?")+msg),
350 new String[] {tr("Save and Exit"), tr("Discard and Exit"), tr("Cancel")},
351 new String[] {"save.png", "exit.png", "cancel.png"}).getValue();
352
353 // Save before exiting
354 if(result == 1) {
355 Boolean savefailed = false;
356 for (final Layer l : map.mapView.getAllLayers()) {
357 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
358 SaveAction save = new SaveAction(l);
359 if(!save.doSave())
360 savefailed = true;
361 }
362 }
363 return savefailed;
364 }
365 else if(result != 2) // Cancel exiting unless the 2nd button was clicked
366 return true;
367 }
368 }
369 return false;
370 }
371
372 private static void downloadFromParamString(final boolean rawGps, String s) {
373 if (s.startsWith("http:")) {
374 final Bounds b = OsmUrlToBounds.parse(s);
375 if (b == null)
376 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed URL: \"{0}\"", s));
377 else {
378 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
379 DownloadTask osmTask = new DownloadOsmTask();
380 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
381 }
382 return;
383 }
384
385 if (s.startsWith("file:")) {
386 try {
387 main.menu.openFile.openFile(new File(new URI(s)));
388 } catch (URISyntaxException e) {
389 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file URL: \"{0}\"", s));
390 }
391 return;
392 }
393
394 final StringTokenizer st = new StringTokenizer(s, ",");
395 if (st.countTokens() == 4) {
396 try {
397 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
398 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
399 return;
400 } catch (final NumberFormatException e) {
401 }
402 }
403
404 main.menu.openFile.openFile(new File(s));
405 }
406
407 protected static void determinePlatformHook() {
408 String os = System.getProperty("os.name");
409 if (os == null) {
410 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
411 platform = new PlatformHookUnixoid();
412 } else if (os.toLowerCase().startsWith("windows")) {
413 platform = new PlatformHookWindows();
414 } else if (os.equals("Linux") || os.equals("Solaris") ||
415 os.equals("SunOS") || os.equals("AIX") ||
416 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
417 platform = new PlatformHookUnixoid();
418 } else if (os.toLowerCase().startsWith("mac os x")) {
419 platform = new PlatformHookOsx();
420 } else {
421 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
422 platform = new PlatformHookUnixoid();
423 }
424 }
425
426 static public String getLanguageCodeU()
427 {
428 String languageCode = getLanguageCode();
429 if(languageCode.equals("en"))
430 return "";
431 return languageCode.substring(0,1).toUpperCase() + languageCode.substring(1) + ":";
432 }
433 static public String getLanguageCode()
434 {
435 String full = Locale.getDefault().toString();
436 if (full.equals("iw_IL"))
437 return "he";
438 /* list of non-single codes supported by josm */
439 else if (full.equals("en_GB"))
440 return full;
441 return Locale.getDefault().getLanguage();
442 }
443
444 static public void saveGuiGeometry() {
445 // save the current window geometry
446 String newGeometry = "";
447 try {
448 if (((JFrame)parent).getExtendedState() == JFrame.NORMAL) {
449 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
450 Rectangle bounds = parent.getBounds();
451 int width = (int)bounds.getWidth();
452 int height = (int)bounds.getHeight();
453 int x = (int)bounds.getX();
454 int y = (int)bounds.getY();
455 if (width > screenDimension.width)
456 width = screenDimension.width;
457 if (height > screenDimension.height)
458 width = screenDimension.height;
459 if (x < 0)
460 x = 0;
461 if (y < 0)
462 y = 0;
463 newGeometry = width + "x" + height + "+" + x + "+" + y;
464 }
465 }
466 catch (Exception e) {
467 System.out.println("Failed to save GUI geometry: " + e);
468 }
469 pref.put("gui.geometry", newGeometry);
470 }
471}
Note: See TracBrowser for help on using the repository browser.