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

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

fixed #3261: Use the "name:$CURRENT_LOCALE" name in the JOSM UI instead of "name" when it exists
new: new checkbox in LAF preferences for enabling/disabling localized names for primitives

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