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

Last change on this file since 4806 was 4774, checked in by bastiK, 12 years ago

fixed #7223 - Error when downloading list of nodes

  • Property svn:eol-style set to native
File size: 35.0 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.GridBagConstraints;
9import java.awt.GridBagLayout;
10import java.awt.Rectangle;
11import java.awt.Toolkit;
12import java.awt.event.ComponentEvent;
13import java.awt.event.ComponentListener;
14import java.awt.event.KeyEvent;
15import java.awt.event.WindowAdapter;
16import java.awt.event.WindowEvent;
17import java.io.File;
18import java.lang.ref.WeakReference;
19import java.net.URI;
20import java.net.URISyntaxException;
21import java.util.ArrayList;
22import java.util.Collection;
23import java.util.Iterator;
24import java.util.List;
25import java.util.Map;
26import java.util.StringTokenizer;
27import java.util.concurrent.ExecutorService;
28import java.util.concurrent.Future;
29import java.util.regex.Matcher;
30import java.util.regex.Pattern;
31
32import javax.swing.Action;
33import javax.swing.InputMap;
34import javax.swing.JComponent;
35import javax.swing.JFrame;
36import javax.swing.JLabel;
37import javax.swing.JOptionPane;
38import javax.swing.JPanel;
39import javax.swing.JTextArea;
40import javax.swing.KeyStroke;
41import javax.swing.UIManager;
42
43import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
44import org.openstreetmap.josm.actions.JosmAction;
45import org.openstreetmap.josm.actions.OpenFileAction;
46import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
47import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
48import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
49import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
50import org.openstreetmap.josm.actions.mapmode.MapMode;
51import org.openstreetmap.josm.actions.search.SearchAction;
52import org.openstreetmap.josm.data.Bounds;
53import org.openstreetmap.josm.data.Preferences;
54import org.openstreetmap.josm.data.UndoRedoHandler;
55import org.openstreetmap.josm.data.coor.CoordinateFormat;
56import org.openstreetmap.josm.data.coor.LatLon;
57import org.openstreetmap.josm.data.osm.DataSet;
58import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy;
59import org.openstreetmap.josm.data.projection.Projection;
60import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
61import org.openstreetmap.josm.data.validation.OsmValidator;
62import org.openstreetmap.josm.gui.GettingStarted;
63import org.openstreetmap.josm.gui.MainMenu;
64import org.openstreetmap.josm.gui.MapFrame;
65import org.openstreetmap.josm.gui.MapView;
66import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
67import org.openstreetmap.josm.gui.io.SaveLayersDialog;
68import org.openstreetmap.josm.gui.layer.Layer;
69import org.openstreetmap.josm.gui.layer.OsmDataLayer;
70import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
71import org.openstreetmap.josm.gui.preferences.ImageryPreference;
72import org.openstreetmap.josm.gui.preferences.MapPaintPreference;
73import org.openstreetmap.josm.gui.preferences.ProjectionPreference;
74import org.openstreetmap.josm.gui.preferences.TaggingPresetPreference;
75import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
76import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
77import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
78import org.openstreetmap.josm.io.OsmApi;
79import org.openstreetmap.josm.plugins.PluginHandler;
80import org.openstreetmap.josm.tools.CheckParameterUtil;
81import org.openstreetmap.josm.tools.I18n;
82import org.openstreetmap.josm.tools.ImageProvider;
83import org.openstreetmap.josm.tools.OpenBrowser;
84import org.openstreetmap.josm.tools.OsmUrlToBounds;
85import org.openstreetmap.josm.tools.PlatformHook;
86import org.openstreetmap.josm.tools.PlatformHookOsx;
87import org.openstreetmap.josm.tools.PlatformHookUnixoid;
88import org.openstreetmap.josm.tools.PlatformHookWindows;
89import org.openstreetmap.josm.tools.Shortcut;
90import org.openstreetmap.josm.tools.Utils;
91
92abstract public class Main {
93
94 /**
95 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
96 * it only shows the MOTD panel.
97 *
98 * @return true if JOSM currently displays a map view
99 */
100 static public boolean isDisplayingMapView() {
101 if (map == null) return false;
102 if (map.mapView == null) return false;
103 return true;
104 }
105 /**
106 * Global parent component for all dialogs and message boxes
107 */
108 public static Component parent;
109 /**
110 * Global application.
111 */
112 public static Main main;
113 /**
114 * The worker thread slave. This is for executing all long and intensive
115 * calculations. The executed runnables are guaranteed to be executed separately
116 * and sequential.
117 */
118 public final static ExecutorService worker = new ProgressMonitorExecutor();
119 /**
120 * Global application preferences
121 */
122 public static Preferences pref;
123
124 /**
125 * The global paste buffer.
126 */
127 public static PrimitiveDeepCopy pasteBuffer = new PrimitiveDeepCopy();
128 public static Layer pasteSource;
129
130 /**
131 * The MapFrame. Use setMapFrame to set or clear it.
132 */
133 public static MapFrame map;
134 /**
135 * True, when in applet mode
136 */
137 public static boolean applet = false;
138
139 /**
140 * The toolbar preference control to register new actions.
141 */
142 public static ToolbarPreferences toolbar;
143
144 public UndoRedoHandler undoRedo = new UndoRedoHandler();
145
146 public static PleaseWaitProgressMonitor currentProgressMonitor;
147
148 /**
149 * The main menu bar at top of screen.
150 */
151 public final MainMenu menu;
152
153 public final OsmValidator validator;
154 /**
155 * The MOTD Layer.
156 */
157 private GettingStarted gettingStarted = new GettingStarted();
158
159 /**
160 * Print a message if logging is on.
161 */
162 static public int log_level = 2;
163 static public void warn(String msg) {
164 if (log_level < 1)
165 return;
166 System.out.println(msg);
167 }
168 static public void info(String msg) {
169 if (log_level < 2)
170 return;
171 System.out.println(msg);
172 }
173 static public void debug(String msg) {
174 if (log_level < 3)
175 return;
176 System.out.println(msg);
177 }
178
179 /**
180 * Platform specific code goes in here.
181 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
182 * So if you need to hook into those early ones, split your class and send the one with the early hooks
183 * to the JOSM team for inclusion.
184 */
185 public static PlatformHook platform;
186
187 /**
188 * Wheather or not the java vm is openjdk
189 * We use this to work around openjdk bugs
190 */
191 public static boolean isOpenjdk;
192
193 /**
194 * Set or clear (if passed <code>null</code>) the map.
195 */
196 public final void setMapFrame(final MapFrame map) {
197 MapFrame old = Main.map;
198 panel.setVisible(false);
199 panel.removeAll();
200 if (map != null) {
201 map.fillPanel(panel);
202 } else {
203 old.destroy();
204 panel.add(gettingStarted, BorderLayout.CENTER);
205 }
206 panel.setVisible(true);
207 redoUndoListener.commandChanged(0,0);
208
209 Main.map = map;
210
211 PluginHandler.notifyMapFrameChanged(old, map);
212 if (map == null && currentProgressMonitor != null) {
213 currentProgressMonitor.showForegroundDialog();
214 }
215 }
216
217 /**
218 * Remove the specified layer from the map. If it is the last layer,
219 * remove the map as well.
220 */
221 public final void removeLayer(final Layer layer) {
222 if (map != null) {
223 map.mapView.removeLayer(layer);
224 if (map != null && map.mapView.getAllLayers().isEmpty()) {
225 setMapFrame(null);
226 }
227 }
228 }
229
230 private static InitStatusListener initListener = null;
231
232 public static interface InitStatusListener {
233
234 void updateStatus(String event);
235 }
236
237 public static void setInitStatusListener(InitStatusListener listener) {
238 initListener = listener;
239 }
240
241 public Main() {
242 main = this;
243 isOpenjdk = System.getProperty("java.vm.name").toUpperCase().indexOf("OPENJDK") != -1;
244
245 if (initListener != null) {
246 initListener.updateStatus(tr("Executing platform startup hook"));
247 }
248 platform.startupHook();
249
250 // We try to establish an API connection early, so that any API
251 // capabilities are already known to the editor instance. However
252 // if it goes wrong that's not critical at this stage.
253 if (initListener != null) {
254 initListener.updateStatus(tr("Initializing OSM API"));
255 }
256 try {
257 OsmApi.getOsmApi().initialize(null, true);
258 } catch (Exception x) {
259 // ignore any exception here.
260 }
261
262 if (initListener != null) {
263 initListener.updateStatus(tr("Building main menu"));
264 }
265 contentPanePrivate.add(panel, BorderLayout.CENTER);
266 panel.add(gettingStarted, BorderLayout.CENTER);
267 menu = new MainMenu();
268
269 undoRedo.listenerCommands.add(redoUndoListener);
270
271 // creating toolbar
272 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
273
274 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
275 KeyEvent.VK_F1, Shortcut.GROUP_DIRECT));
276
277 if (initListener != null) {
278 initListener.updateStatus(tr("Initializing presets"));
279 }
280 TaggingPresetPreference.initialize();
281
282 if (initListener != null) {
283 initListener.updateStatus(tr("Initializing map styles"));
284 }
285 MapPaintPreference.initialize();
286
287 if (initListener != null) {
288 initListener.updateStatus(tr("Loading imagery preferences"));
289 }
290 ImageryPreference.initialize();
291
292 if (initListener != null) {
293 initListener.updateStatus(tr("Initializing validator"));
294 }
295 validator = new OsmValidator();
296 MapView.addLayerChangeListener(validator);
297
298 // hooks for the jmapviewer component
299 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
300 @Override
301 public void openLink(String url) {
302 OpenBrowser.displayUrl(url);
303 }
304 });
305 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
306
307 if (initListener != null) {
308 initListener.updateStatus(tr("Updating user interface"));
309 }
310
311 toolbar.refreshToolbarControl();
312
313 toolbar.control.updateUI();
314 contentPanePrivate.updateUI();
315
316 }
317
318 /**
319 * Add a new layer to the map. If no map exists, create one.
320 */
321 public final void addLayer(final Layer layer) {
322 if (map == null) {
323 final MapFrame mapFrame = new MapFrame(contentPanePrivate);
324 setMapFrame(mapFrame);
325 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction(), layer);
326 mapFrame.setVisible(true);
327 mapFrame.initializeDialogsPane();
328 // bootstrapping problem: make sure the layer list dialog is going to
329 // listen to change events of the very first layer
330 //
331 layer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
332 }
333 map.mapView.addLayer(layer);
334 }
335
336 /**
337 * Replies true if there is an edit layer
338 *
339 * @return true if there is an edit layer
340 */
341 public boolean hasEditLayer() {
342 if (getEditLayer() == null) return false;
343 return true;
344 }
345
346 /**
347 * Replies the current edit layer
348 *
349 * @return the current edit layer. null, if no current edit layer exists
350 */
351 public OsmDataLayer getEditLayer() {
352 if (map == null) return null;
353 if (map.mapView == null) return null;
354 return map.mapView.getEditLayer();
355 }
356
357 /**
358 * Replies the current data set.
359 *
360 * @return the current data set. null, if no current data set exists
361 */
362 public DataSet getCurrentDataSet() {
363 if (!hasEditLayer()) return null;
364 return getEditLayer().data;
365 }
366
367 /**
368 * Returns the currently active layer
369 *
370 * @return the currently active layer. null, if currently no active layer exists
371 */
372 public Layer getActiveLayer() {
373 if (map == null) return null;
374 if (map.mapView == null) return null;
375 return map.mapView.getActiveLayer();
376 }
377
378 protected static JPanel contentPanePrivate = new JPanel(new BorderLayout());
379
380 /**
381 * @deprecated If you just need to register shortcut for action, use registerActionShortcut instead of accessing InputMap directly
382 */
383 @Deprecated
384 public static final JPanel contentPane = contentPanePrivate;
385
386 public static void registerActionShortcut(Action action, Shortcut shortcut) {
387 registerActionShortcut(action, shortcut.getKeyStroke());
388 }
389
390 public static void registerActionShortcut(Action action, KeyStroke keyStroke) {
391 if (keyStroke == null)
392 return;
393
394 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
395 Object existing = inputMap.get(keyStroke);
396 if (existing != null && !existing.equals(action)) {
397 System.out.println(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
398 }
399 inputMap.put(keyStroke, action);
400
401 contentPanePrivate.getActionMap().put(action, action);
402 }
403
404 public static void unregisterActionShortcut(Shortcut shortcut) {
405 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
406 }
407
408 public static void unregisterActionShortcut(JosmAction action) {
409 unregisterActionShortcut(action, action.getShortcut());
410 }
411
412 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
413 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
414 contentPanePrivate.getActionMap().remove(action);
415 }
416
417
418 ///////////////////////////////////////////////////////////////////////////
419 // Implementation part
420 ///////////////////////////////////////////////////////////////////////////
421
422 public static JPanel panel = new JPanel(new BorderLayout());
423
424 protected static Rectangle bounds;
425 protected static int windowState = JFrame.NORMAL;
426
427 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
428 public void commandChanged(final int queueSize, final int redoSize) {
429 menu.undo.setEnabled(queueSize > 0);
430 menu.redo.setEnabled(redoSize > 0);
431 }
432 };
433
434 /**
435 * Should be called before the main constructor to setup some parameter stuff
436 * @param args The parsed argument list.
437 */
438 public static void preConstructorInit(Map<String, Collection<String>> args) {
439 ProjectionPreference.setProjection();
440
441 try {
442 String defaultlaf = platform.getDefaultStyle();
443 String laf = Main.pref.get("laf", defaultlaf);
444 try {
445 UIManager.setLookAndFeel(laf);
446 }
447 catch (final java.lang.ClassNotFoundException e) {
448 System.out.println("Look and Feel not found: " + laf);
449 Main.pref.put("laf", defaultlaf);
450 }
451 catch (final javax.swing.UnsupportedLookAndFeelException e) {
452 System.out.println("Look and Feel not supported: " + laf);
453 Main.pref.put("laf", defaultlaf);
454 }
455 toolbar = new ToolbarPreferences();
456 contentPanePrivate.updateUI();
457 panel.updateUI();
458 } catch (final Exception e) {
459 e.printStackTrace();
460 }
461 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
462 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
463 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
464 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
465
466 I18n.translateJavaInternalMessages();
467
468 // init default coordinate format
469 //
470 try {
471 //CoordinateFormat format = CoordinateFormat.valueOf(Main.pref.get("coordinates"));
472 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
473 } catch (IllegalArgumentException iae) {
474 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
475 }
476
477 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
478 String geometry = null;
479 if (args.containsKey("geometry")) {
480 geometry = args.get("geometry").iterator().next();
481 } else {
482 geometry = Main.pref.get("gui.geometry");
483 }
484 if (geometry.length() != 0) {
485 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
486 if (m.matches()) {
487 int w = Integer.valueOf(m.group(1));
488 int h = Integer.valueOf(m.group(2));
489 int x = 0, y = 0;
490 if (m.group(3) != null) {
491 x = Integer.valueOf(m.group(5));
492 y = Integer.valueOf(m.group(7));
493 if (m.group(4).equals("-")) {
494 x = screenDimension.width - x - w;
495 }
496 if (m.group(6).equals("-")) {
497 y = screenDimension.height - y - h;
498 }
499 }
500 // copied from WindowsGeometry.applySafe()
501 if (x > Toolkit.getDefaultToolkit().getScreenSize().width - 10) {
502 x = 0;
503 }
504 if (y > Toolkit.getDefaultToolkit().getScreenSize().height - 10) {
505 y = 0;
506 }
507 bounds = new Rectangle(x,y,w,h);
508 if(!Main.pref.get("gui.geometry").equals(geometry)) {
509 // remember this geometry
510 Main.pref.put("gui.geometry", geometry);
511 }
512 } else {
513 System.out.println("Ignoring malformed geometry: "+geometry);
514 }
515 }
516 if (bounds == null) {
517 bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
518 }
519 }
520
521 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
522 if (args.containsKey("download")) {
523 List<File> fileList = new ArrayList<File>();
524 for (String s : args.get("download")) {
525 File f = null;
526 switch(paramType(s)) {
527 case httpUrl:
528 downloadFromParamHttp(false, s);
529 break;
530 case bounds:
531 downloadFromParamBounds(false, s);
532 break;
533 case fileUrl:
534 try {
535 f = new File(new URI(s));
536 } catch (URISyntaxException e) {
537 JOptionPane.showMessageDialog(
538 Main.parent,
539 tr("Ignoring malformed file URL: \"{0}\"", s),
540 tr("Warning"),
541 JOptionPane.WARNING_MESSAGE
542 );
543 }
544 if (f!=null) {
545 fileList.add(f);
546 }
547 break;
548 case fileName:
549 f = new File(s);
550 fileList.add(f);
551 break;
552 }
553 }
554 if(!fileList.isEmpty())
555 {
556 OpenFileAction.openFiles(fileList, true);
557 }
558 }
559 if (args.containsKey("downloadgps")) {
560 for (String s : args.get("downloadgps")) {
561 switch(paramType(s)) {
562 case httpUrl:
563 downloadFromParamHttp(true, s);
564 break;
565 case bounds:
566 downloadFromParamBounds(true, s);
567 break;
568 case fileUrl:
569 case fileName:
570 JOptionPane.showMessageDialog(
571 Main.parent,
572 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
573 tr("Warning"),
574 JOptionPane.WARNING_MESSAGE
575 );
576 }
577 }
578 }
579 if (args.containsKey("selection")) {
580 for (String s : args.get("selection")) {
581 SearchAction.search(s, SearchAction.SearchMode.add);
582 }
583 }
584 }
585
586 public static boolean saveUnsavedModifications() {
587 if (map == null) return true;
588 SaveLayersDialog dialog = new SaveLayersDialog(Main.parent);
589 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
590 for (OsmDataLayer l: Main.map.mapView.getLayersOfType(OsmDataLayer.class)) {
591 if (l.requiresSaveToFile() || l.requiresUploadToServer()) {
592 layersWithUnmodifiedChanges.add(l);
593 }
594 }
595 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
596 if (!layersWithUnmodifiedChanges.isEmpty()) {
597 dialog.getModel().populate(layersWithUnmodifiedChanges);
598 dialog.setVisible(true);
599 switch(dialog.getUserAction()) {
600 case CANCEL: return false;
601 case PROCEED: return true;
602 default: return false;
603 }
604 }
605
606 return true;
607 }
608
609 public static boolean exitJosm(boolean exit) {
610 if (Main.saveUnsavedModifications()) {
611 Main.saveGuiGeometry();
612 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
613 if (Main.isDisplayingMapView()) {
614 Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
615 for (Layer l: layers) {
616 Main.map.mapView.removeLayer(l);
617 }
618 }
619 if (exit) {
620 System.exit(0);
621 return true;
622 } else
623 return true;
624 } else
625 return false;
626 }
627
628 /**
629 * The type of a command line parameter, to be used in switch statements.
630 * @see paramType
631 */
632 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
633
634 /**
635 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
636 * @param s A parameter string
637 * @return The guessed parameter type
638 */
639 private DownloadParamType paramType(String s) {
640 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
641 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
642 final StringTokenizer st = new StringTokenizer(s, ",");
643 // we assume a string with exactly 3 commas is a bounds parameter
644 if (st.countTokens() == 4) return DownloadParamType.bounds;
645 // everything else must be a file name
646 return DownloadParamType.fileName;
647 }
648
649 /**
650 * Download area specified on the command line as OSM URL.
651 * @param rawGps Flag to download raw GPS tracks
652 * @param s The URL parameter
653 */
654 private static void downloadFromParamHttp(final boolean rawGps, String s) {
655 final Bounds b = OsmUrlToBounds.parse(s);
656 if (b == null) {
657 JOptionPane.showMessageDialog(
658 Main.parent,
659 tr("Ignoring malformed URL: \"{0}\"", s),
660 tr("Warning"),
661 JOptionPane.WARNING_MESSAGE
662 );
663 } else {
664 downloadFromParamBounds(rawGps, b);
665 }
666 }
667
668 /**
669 * Download area specified on the command line as bounds string.
670 * @param rawGps Flag to download raw GPS tracks
671 * @param s The bounds parameter
672 */
673 private static void downloadFromParamBounds(final boolean rawGps, String s) {
674 final StringTokenizer st = new StringTokenizer(s, ",");
675 if (st.countTokens() == 4) {
676 Bounds b = new Bounds(
677 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
678 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
679 );
680 downloadFromParamBounds(rawGps, b);
681 }
682 }
683
684 /**
685 * Download area specified as Bounds value.
686 * @param rawGps Flag to download raw GPS tracks
687 * @param b The bounds value
688 * @see downloadFromParamBounds(final boolean rawGps, String s)
689 * @see downloadFromParamHttp
690 */
691 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
692 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
693 // asynchronously launch the download task ...
694 Future<?> future = task.download(true, b, null);
695 // ... and the continuation when the download is finished (this will wait for the download to finish)
696 Main.worker.execute(new PostDownloadHandler(task, future));
697 }
698
699 public static void determinePlatformHook() {
700 String os = System.getProperty("os.name");
701 if (os == null) {
702 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
703 platform = new PlatformHookUnixoid();
704 } else if (os.toLowerCase().startsWith("windows")) {
705 platform = new PlatformHookWindows();
706 } else if (os.equals("Linux") || os.equals("Solaris") ||
707 os.equals("SunOS") || os.equals("AIX") ||
708 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
709 platform = new PlatformHookUnixoid();
710 } else if (os.toLowerCase().startsWith("mac os x")) {
711 platform = new PlatformHookOsx();
712 } else {
713 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
714 platform = new PlatformHookUnixoid();
715 }
716 }
717
718 static public void saveGuiGeometry() {
719 // save the current window geometry and the width of the toggle dialog area
720 String newGeometry = "";
721 String newToggleDlgWidth = null;
722 try {
723 Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
724 int width = (int)bounds.getWidth();
725 int height = (int)bounds.getHeight();
726 int x = (int)bounds.getX();
727 int y = (int)bounds.getY();
728 if (width > screenDimension.width) {
729 width = screenDimension.width;
730 }
731 if (height > screenDimension.height) {
732 width = screenDimension.height;
733 }
734 if (x < 0) {
735 x = 0;
736 }
737 if (y < 0) {
738 y = 0;
739 }
740 newGeometry = width + "x" + height + "+" + x + "+" + y;
741
742 if (map != null) {
743 newToggleDlgWidth = Integer.toString(map.getToggleDlgWidth());
744 if (newToggleDlgWidth.equals(Integer.toString(MapFrame.DEF_TOGGLE_DLG_WIDTH))) {
745 newToggleDlgWidth = "";
746 }
747 }
748 }
749 catch (Exception e) {
750 System.out.println("Failed to get GUI geometry: " + e);
751 e.printStackTrace();
752 }
753 boolean maximized = (windowState & JFrame.MAXIMIZED_BOTH) != 0;
754 // Main.debug("Main window: saving geometry \"" + newGeometry + "\" " + (maximized?"maximized":"normal"));
755 pref.put("gui.maximized", maximized);
756 pref.put("gui.geometry", newGeometry);
757 if (newToggleDlgWidth != null) {
758 pref.put("toggleDialogs.width", newToggleDlgWidth);
759 }
760 }
761 private static class WindowPositionSizeListener extends WindowAdapter implements
762 ComponentListener {
763
764 @Override
765 public void windowStateChanged(WindowEvent e) {
766 Main.windowState = e.getNewState();
767 // Main.debug("Main window state changed to " + Main.windowState);
768 }
769
770 public void componentHidden(ComponentEvent e) {
771 }
772
773 public void componentMoved(ComponentEvent e) {
774 handleComponentEvent(e);
775 }
776
777 public void componentResized(ComponentEvent e) {
778 handleComponentEvent(e);
779 }
780
781 public void componentShown(ComponentEvent e) {
782 }
783
784 private void handleComponentEvent(ComponentEvent e) {
785 Component c = e.getComponent();
786 if (c instanceof JFrame) {
787 if (Main.windowState == JFrame.NORMAL) {
788 Main.bounds = ((JFrame) c).getBounds();
789 // Main.debug("Main window: new geometry " + Main.bounds);
790 } else {
791 // Main.debug("Main window state is " + Main.windowState);
792 }
793 }
794 }
795
796 }
797 public static void addListener() {
798 parent.addComponentListener(new WindowPositionSizeListener());
799 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
800 }
801
802 public static void checkJava6() {
803 String version = System.getProperty("java.version");
804 if (version != null) {
805 if (version.startsWith("1.6") || version.startsWith("6") ||
806 version.startsWith("1.7") || version.startsWith("7"))
807 return;
808 if (version.startsWith("1.5") || version.startsWith("5")) {
809 JLabel ho = new JLabel("<html>"+
810 tr("<h2>JOSM requires Java version 6.</h2>"+
811 "Detected Java version: {0}.<br>"+
812 "You can <ul><li>update your Java (JRE) or</li>"+
813 "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
814 "More Info:", version)+"</html>");
815 JTextArea link = new JTextArea("http://josm.openstreetmap.de/wiki/Help/SystemRequirements");
816 link.setEditable(false);
817 link.setBackground(panel.getBackground());
818 JPanel panel = new JPanel(new GridBagLayout());
819 GridBagConstraints gbc = new GridBagConstraints();
820 gbc.gridwidth = GridBagConstraints.REMAINDER;
821 gbc.anchor = GridBagConstraints.WEST;
822 gbc.weightx = 1.0;
823 panel.add(ho, gbc);
824 panel.add(link, gbc);
825 final String EXIT = tr("Exit JOSM");
826 final String CONTINUE = tr("Continue, try anyway");
827 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
828 if (ret == 0) {
829 System.exit(0);
830 }
831 return;
832 }
833 }
834 System.err.println("Error: Could not recognize Java Version: "+version);
835 }
836
837 /* ----------------------------------------------------------------------------------------- */
838 /* projection handling - Main is a registry for a single, global projection instance */
839 /* */
840 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
841 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
842 /* ----------------------------------------------------------------------------------------- */
843 /**
844 * The projection method used.
845 * @deprecated use {@link #getProjection()} and {@link #setProjection(Projection)} instead.
846 * For the time being still publicly available, but avoid/migrate write access to it. Use
847 * {@link #setProjection(Projection)} in order to trigger a projection change event.
848 */
849 @Deprecated
850 public static Projection proj;
851
852 /**
853 * Replies the current projection.
854 *
855 * @return
856 */
857 public static Projection getProjection() {
858 return proj;
859 }
860
861 /**
862 * Sets the current projection
863 *
864 * @param p the projection
865 */
866 public static void setProjection(Projection p) {
867 CheckParameterUtil.ensureParameterNotNull(p);
868 Projection oldValue = proj;
869 proj = p;
870 fireProjectionChanged(oldValue, proj);
871 }
872
873 /*
874 * Keep WeakReferences to the listeners. This relieves clients from the burden of
875 * explicitly removing the listeners and allows us to transparently register every
876 * created dataset as projection change listener.
877 */
878 private static final ArrayList<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
879
880 private static void fireProjectionChanged(Projection oldValue, Projection newValue) {
881 if (newValue == null ^ oldValue == null
882 || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
883
884 synchronized(Main.class) {
885 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
886 while(it.hasNext()){
887 WeakReference<ProjectionChangeListener> wr = it.next();
888 ProjectionChangeListener listener = wr.get();
889 if (listener == null) {
890 it.remove();
891 continue;
892 }
893 listener.projectionChanged(oldValue, newValue);
894 }
895 }
896 if (newValue != null) {
897 Bounds b = (Main.map != null && Main.map.mapView != null) ? Main.map.mapView.getRealBounds() : null;
898 if (b != null){
899 Main.map.mapView.zoomTo(b);
900 }
901 }
902 /* TODO - remove layers with fixed projection */
903 }
904 }
905
906 /**
907 * Register a projection change listener
908 *
909 * @param listener the listener. Ignored if null.
910 */
911 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
912 if (listener == null) return;
913 synchronized (Main.class) {
914 for (WeakReference<ProjectionChangeListener> wr : listeners) {
915 // already registered ? => abort
916 if (wr.get() == listener) return;
917 }
918 listeners.add(new WeakReference<ProjectionChangeListener>(listener));
919 }
920 }
921
922 /**
923 * Removes a projection change listener
924 *
925 * @param listener the listener. Ignored if null.
926 */
927 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
928 if (listener == null) return;
929 synchronized(Main.class){
930 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
931 while(it.hasNext()){
932 WeakReference<ProjectionChangeListener> wr = it.next();
933 // remove the listener - and any other listener which god garbage
934 // collected in the meantime
935 if (wr.get() == null || wr.get() == listener) {
936 it.remove();
937 }
938 }
939 }
940 }
941}
Note: See TracBrowser for help on using the repository browser.