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

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

fixed #2286 - rename fullscreen to maximize - patch by avar

  • Property svn:eol-style set to native
File size: 17.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.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 /**
90 * The projection method used.
91 */
92 public static Projection proj;
93 /**
94 * The MapFrame. Use setMapFrame to set or clear it.
95 */
96 public static MapFrame map;
97 /**
98 * The dialog that gets displayed during background task execution.
99 */
100 public static PleaseWaitDialog pleaseWaitDlg;
101
102 /**
103 * True, when in applet mode
104 */
105 public static boolean applet = false;
106
107 /**
108 * The toolbar preference control to register new actions.
109 */
110 public static ToolbarPreferences toolbar;
111
112
113 public UndoRedoHandler undoRedo = new UndoRedoHandler();
114
115 /**
116 * The main menu bar at top of screen.
117 */
118 public final MainMenu menu;
119
120 /**
121 * The MOTD Layer.
122 */
123 private GettingStarted gettingStarted=new GettingStarted();
124
125 /**
126 * Print a debug message if debugging is on.
127 */
128 static public int debug_level = 1;
129 static public final void debug(String msg) {
130 if (debug_level <= 0)
131 return;
132 System.out.println(msg);
133 }
134
135 /**
136 * Platform specific code goes in here.
137 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
138 * So if you need to hook into those early ones, split your class and send the one with the early hooks
139 * to the JOSM team for inclusion.
140 */
141 public static PlatformHook platform;
142
143 /**
144 * Set or clear (if passed <code>null</code>) the map.
145 */
146 public final void setMapFrame(final MapFrame map) {
147 MapFrame old = Main.map;
148 Main.map = map;
149 panel.setVisible(false);
150 panel.removeAll();
151 if (map != null)
152 map.fillPanel(panel);
153 else {
154 old.destroy();
155 panel.add(gettingStarted, BorderLayout.CENTER);
156 }
157 panel.setVisible(true);
158 redoUndoListener.commandChanged(0,0);
159
160 PluginHandler.setMapFrame(old, map);
161 }
162
163 /**
164 * Remove the specified layer from the map. If it is the last layer,
165 * remove the map as well.
166 */
167 public final void removeLayer(final Layer layer) {
168 map.mapView.removeLayer(layer);
169 if (layer instanceof OsmDataLayer)
170 ds = new DataSet();
171 if (map.mapView.getAllLayers().isEmpty())
172 setMapFrame(null);
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) splash.setStatus(tr("Creating main GUI"));
187 menu = new MainMenu();
188
189 undoRedo.listenerCommands.add(redoUndoListener);
190
191 // creating toolbar
192 contentPane.add(toolbar.control, BorderLayout.NORTH);
193
194 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
195 .put(Shortcut.registerShortcut("system:help", tr("Help"),
196 KeyEvent.VK_F1, Shortcut.GROUP_DIRECT).getKeyStroke(), "Help");
197 contentPane.getActionMap().put("Help", menu.help);
198
199 TaggingPresetPreference.initialize();
200 MapPaintPreference.initialize();
201
202 toolbar.refreshToolbarControl();
203
204 toolbar.control.updateUI();
205 contentPane.updateUI();
206 }
207
208 /**
209 * Add a new layer to the map. If no map exists, create one.
210 */
211 public final void addLayer(final Layer layer) {
212 if (map == null) {
213 final MapFrame mapFrame = new MapFrame();
214 setMapFrame(mapFrame);
215 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
216 mapFrame.setVisible(true);
217 mapFrame.setVisibleDialogs();
218 }
219 map.mapView.addLayer(layer);
220 }
221 /**
222 * @return The edit osm layer. If none exists, it will be created.
223 */
224 public final OsmDataLayer editLayer() {
225 if (map == null || map.mapView.editLayer == null)
226 menu.newAction.actionPerformed(null);
227 return map.mapView.editLayer;
228 }
229
230 /**
231 * Use this to register shortcuts to
232 */
233 public static final JPanel contentPane = new JPanel(new BorderLayout());
234
235 ///////////////////////////////////////////////////////////////////////////
236 // Implementation part
237 ///////////////////////////////////////////////////////////////////////////
238
239 public static JPanel panel = new JPanel(new BorderLayout());
240
241 protected static Rectangle bounds;
242
243 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
244 public void commandChanged(final int queueSize, final int redoSize) {
245 menu.undo.setEnabled(queueSize > 0);
246 menu.redo.setEnabled(redoSize > 0);
247 }
248 };
249 /**
250 * Should be called before the main constructor to setup some parameter stuff
251 * @param args The parsed argument list.
252 */
253 public static void preConstructorInit(Map<String, Collection<String>> args) {
254 try {
255 Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
256 } catch (final Exception e) {
257 e.printStackTrace();
258 JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using EPSG:4326"));
259 Main.proj = new Epsg4326();
260 }
261
262 try {
263 try {
264 String laf = Main.pref.get("laf");
265 if(laf != null && laf.length() > 0)
266 UIManager.setLookAndFeel(laf);
267 }
268 catch (final javax.swing.UnsupportedLookAndFeelException e) {
269 System.out.println("Look and Feel not supported: " + Main.pref.get("laf"));
270 }
271 toolbar = new ToolbarPreferences();
272 contentPane.updateUI();
273 panel.updateUI();
274 } catch (final Exception e) {
275 e.printStackTrace();
276 }
277 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
278 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
279 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
280 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
281
282 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
283 String geometry = Main.pref.get("gui.geometry");
284 if (args.containsKey("geometry")) {
285 geometry = args.get("geometry").iterator().next();
286 }
287 if (geometry.length() != 0) {
288 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
289 if (m.matches()) {
290 int w = Integer.valueOf(m.group(1));
291 int h = Integer.valueOf(m.group(2));
292 int x = 0, y = 0;
293 if (m.group(3) != null) {
294 x = Integer.valueOf(m.group(5));
295 y = Integer.valueOf(m.group(7));
296 if (m.group(4).equals("-"))
297 x = screenDimension.width - x - w;
298 if (m.group(6).equals("-"))
299 y = screenDimension.height - y - h;
300 }
301 bounds = new Rectangle(x,y,w,h);
302 if(!Main.pref.get("gui.geometry").equals(geometry)) {
303 // remember this geometry
304 Main.pref.put("gui.geometry", geometry);
305 }
306 } else
307 System.out.println("Ignoring malformed geometry: "+geometry);
308 }
309 if (bounds == null)
310 bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
311
312 // preinitialize a wait dialog for all early downloads (e.g. via command line)
313 pleaseWaitDlg = new PleaseWaitDialog(null);
314 }
315
316 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
317 // initialize the pleaseWaitDialog with the application as parent to handle focus stuff
318 pleaseWaitDlg = new PleaseWaitDialog(parent);
319
320 if (args.containsKey("download"))
321 for (String s : args.get("download"))
322 downloadFromParamString(false, s);
323 if (args.containsKey("downloadgps"))
324 for (String s : args.get("downloadgps"))
325 downloadFromParamString(true, s);
326 if (args.containsKey("selection"))
327 for (String s : args.get("selection"))
328 SearchAction.search(s, SearchAction.SearchMode.add, false, false);
329 }
330
331 public static boolean breakBecauseUnsavedChanges() {
332 Shortcut.savePrefs();
333 if (map != null) {
334 boolean modified = false;
335 boolean uploadedModified = false;
336 for (final Layer l : map.mapView.getAllLayers()) {
337 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
338 modified = true;
339 uploadedModified = ((OsmDataLayer)l).uploadedModified;
340 break;
341 }
342 }
343 if (modified) {
344 final String msg = uploadedModified ? "\n"
345 +tr("Hint: Some changes came from uploading new data to the server.") : "";
346 int result = new ExtendedDialog(parent, tr("Unsaved Changes"),
347 new javax.swing.JLabel(tr("There are unsaved changes. Discard the changes and continue?")+msg),
348 new String[] {tr("Save and Exit"), tr("Discard and Exit"), tr("Cancel")},
349 new String[] {"save.png", "exit.png", "cancel.png"}).getValue();
350
351 // Save before exiting
352 if(result == 1) {
353 Boolean savefailed = false;
354 for (final Layer l : map.mapView.getAllLayers()) {
355 if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
356 SaveAction save = new SaveAction(l);
357 if(!save.doSave())
358 savefailed = true;
359 }
360 }
361 return savefailed;
362 }
363 else if(result != 2) // Cancel exiting unless the 2nd button was clicked
364 return true;
365 }
366 }
367 return false;
368 }
369
370 private static void downloadFromParamString(final boolean rawGps, String s) {
371 if (s.startsWith("http:")) {
372 final Bounds b = OsmUrlToBounds.parse(s);
373 if (b == null)
374 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed URL: \"{0}\"", s));
375 else {
376 //DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
377 DownloadTask osmTask = new DownloadOsmTask();
378 osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
379 }
380 return;
381 }
382
383 if (s.startsWith("file:")) {
384 try {
385 main.menu.openFile.openFile(new File(new URI(s)));
386 } catch (URISyntaxException e) {
387 JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file URL: \"{0}\"", s));
388 }
389 return;
390 }
391
392 final StringTokenizer st = new StringTokenizer(s, ",");
393 if (st.countTokens() == 4) {
394 try {
395 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
396 task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
397 return;
398 } catch (final NumberFormatException e) {
399 }
400 }
401
402 main.menu.openFile.openFile(new File(s));
403 }
404
405 protected static void determinePlatformHook() {
406 String os = System.getProperty("os.name");
407 if (os == null) {
408 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
409 platform = new PlatformHookUnixoid();
410 } else if (os.toLowerCase().startsWith("windows")) {
411 platform = new PlatformHookWindows();
412 } else if (os.equals("Linux") || os.equals("Solaris") ||
413 os.equals("SunOS") || os.equals("AIX") ||
414 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
415 platform = new PlatformHookUnixoid();
416 } else if (os.toLowerCase().startsWith("mac os x")) {
417 platform = new PlatformHookOsx();
418 } else {
419 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
420 platform = new PlatformHookUnixoid();
421 }
422 }
423
424 static public String getLanguageCodeU()
425 {
426 String languageCode = Locale.getDefault().getLanguage();
427 return languageCode.substring(0,1).toUpperCase() + languageCode.substring(1) + ":";
428 }
429 static public String getLanguageCode()
430 {
431 return Locale.getDefault().getLanguage();
432 }
433
434 static public void saveGuiGeometry() {
435 // save the current window geometry
436 String newGeometry = "";
437 try {
438 if(((JFrame)parent).getExtendedState() == JFrame.NORMAL) {
439 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
440 Rectangle bounds = parent.getBounds();
441 int width = (int)bounds.getWidth();
442 int height = (int)bounds.getHeight();
443 int x = (int)bounds.getX();
444 int y = (int)bounds.getY();
445 if(width > screenDimension.width)
446 width = screenDimension.width;
447 if(height > screenDimension.height)
448 width = screenDimension.height;
449 if(x < 0)
450 x = 0;
451 if(y < 0)
452 y = 0;
453 newGeometry = width + "x" + height + "+" + x + "+" + y;
454 }
455 }
456 catch (Exception e) {
457 System.out.println("Failed to save GUI geometry: " + e);
458 }
459 pref.put("gui.geometry", newGeometry);
460 }
461}
Note: See TracBrowser for help on using the repository browser.