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

Last change on this file since 5177 was 5177, checked in by simon04, 12 years ago

see #6964 - validator initialization requires tagging presets to be initialized

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