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

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

see #6964 - perform several initialization tasks in parallel in order to speedup startup

  • Property svn:eol-style set to native
File size: 33.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.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 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
250 List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
251
252 tasks.add(new Callable<Void>() {
253
254 @Override
255 public Void call() throws Exception {
256 // We try to establish an API connection early, so that any API
257 // capabilities are already known to the editor instance. However
258 // if it goes wrong that's not critical at this stage.
259 if (initListener != null) {
260 initListener.updateStatus(tr("Initializing OSM API"));
261 }
262 try {
263 OsmApi.getOsmApi().initialize(null, true);
264 } catch (Exception x) {
265 // ignore any exception here.
266 }
267 return null;
268 }
269 });
270
271 tasks.add(new Callable<Void>() {
272
273 @Override
274 public Void call() throws Exception {
275 if (initListener != null) {
276 initListener.updateStatus(tr("Building main menu"));
277 }
278 contentPanePrivate.add(panel, BorderLayout.CENTER);
279 panel.add(gettingStarted, BorderLayout.CENTER);
280 menu = new MainMenu();
281
282 undoRedo.addCommandQueueListener(redoUndoListener);
283
284 // creating toolbar
285 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
286
287 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
288 KeyEvent.VK_F1, Shortcut.DIRECT));
289
290 return null;
291 }
292 });
293
294 tasks.add(new Callable<Void>() {
295
296 @Override
297 public Void call() throws Exception {
298 if (initListener != null) {
299 initListener.updateStatus(tr("Initializing presets"));
300 }
301 TaggingPresetPreference.initialize();
302 return null;
303 }
304 });
305
306 tasks.add(new Callable<Void>() {
307
308 @Override
309 public Void call() throws Exception {
310 if (initListener != null) {
311 initListener.updateStatus(tr("Initializing map styles"));
312 }
313 MapPaintPreference.initialize();
314 return null;
315 }
316 });
317
318 tasks.add(new Callable<Void>() {
319
320 @Override
321 public Void call() throws Exception {
322 if (initListener != null) {
323 initListener.updateStatus(tr("Loading imagery preferences"));
324 }
325 ImageryPreference.initialize();
326 return null;
327 }
328 });
329
330 tasks.add(new Callable<Void>() {
331
332 @Override
333 public Void call() throws Exception {
334 if (initListener != null) {
335 initListener.updateStatus(tr("Initializing validator"));
336 }
337 validator = new OsmValidator();
338 MapView.addLayerChangeListener(validator);
339 return null;
340 }
341 });
342
343 try {
344 Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()).invokeAll(tasks);
345 } catch (InterruptedException ex) {
346 throw new RuntimeException(ex);
347 }
348
349 // hooks for the jmapviewer component
350 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
351 @Override
352 public void openLink(String url) {
353 OpenBrowser.displayUrl(url);
354 }
355 });
356 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
357
358 if (initListener != null) {
359 initListener.updateStatus(tr("Updating user interface"));
360 }
361
362 toolbar.refreshToolbarControl();
363
364 toolbar.control.updateUI();
365 contentPanePrivate.updateUI();
366
367 }
368
369 /**
370 * Add a new layer to the map. If no map exists, create one.
371 */
372 public final void addLayer(final Layer layer) {
373 if (map == null) {
374 final MapFrame mapFrame = new MapFrame(contentPanePrivate);
375 setMapFrame(mapFrame);
376 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction(), layer);
377 mapFrame.setVisible(true);
378 mapFrame.initializeDialogsPane();
379 // bootstrapping problem: make sure the layer list dialog is going to
380 // listen to change events of the very first layer
381 //
382 layer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
383 }
384 map.mapView.addLayer(layer);
385 }
386
387 /**
388 * Replies true if there is an edit layer
389 *
390 * @return true if there is an edit layer
391 */
392 public boolean hasEditLayer() {
393 if (getEditLayer() == null) return false;
394 return true;
395 }
396
397 /**
398 * Replies the current edit layer
399 *
400 * @return the current edit layer. null, if no current edit layer exists
401 */
402 public OsmDataLayer getEditLayer() {
403 if (map == null) return null;
404 if (map.mapView == null) return null;
405 return map.mapView.getEditLayer();
406 }
407
408 /**
409 * Replies the current data set.
410 *
411 * @return the current data set. null, if no current data set exists
412 */
413 public DataSet getCurrentDataSet() {
414 if (!hasEditLayer()) return null;
415 return getEditLayer().data;
416 }
417
418 /**
419 * Returns the currently active layer
420 *
421 * @return the currently active layer. null, if currently no active layer exists
422 */
423 public Layer getActiveLayer() {
424 if (map == null) return null;
425 if (map.mapView == null) return null;
426 return map.mapView.getActiveLayer();
427 }
428
429 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
430
431 public static void redirectToMainContentPane(JComponent source) {
432 RedirectInputMap.redirect(source, contentPanePrivate);
433 }
434
435 public static void registerActionShortcut(Action action, Shortcut shortcut) {
436 KeyStroke keyStroke = shortcut.getKeyStroke();
437 if (keyStroke == null)
438 return;
439
440 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
441 Object existing = inputMap.get(keyStroke);
442 if (existing != null && !existing.equals(action)) {
443 System.out.println(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
444 }
445 inputMap.put(keyStroke, action);
446
447 contentPanePrivate.getActionMap().put(action, action);
448 }
449
450 public static void unregisterActionShortcut(Shortcut shortcut) {
451 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
452 }
453
454 public static void unregisterActionShortcut(JosmAction action) {
455 unregisterActionShortcut(action, action.getShortcut());
456 }
457
458 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
459 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
460 contentPanePrivate.getActionMap().remove(action);
461 }
462
463 ///////////////////////////////////////////////////////////////////////////
464 // Implementation part
465 ///////////////////////////////////////////////////////////////////////////
466
467 public static final JPanel panel = new JPanel(new BorderLayout());
468
469 protected static WindowGeometry geometry;
470 protected static int windowState = JFrame.NORMAL;
471
472 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
473 public void commandChanged(final int queueSize, final int redoSize) {
474 menu.undo.setEnabled(queueSize > 0);
475 menu.redo.setEnabled(redoSize > 0);
476 }
477 };
478
479 /**
480 * Should be called before the main constructor to setup some parameter stuff
481 * @param args The parsed argument list.
482 */
483 public static void preConstructorInit(Map<String, Collection<String>> args) {
484 ProjectionPreference.setProjection();
485
486 try {
487 String defaultlaf = platform.getDefaultStyle();
488 String laf = Main.pref.get("laf", defaultlaf);
489 try {
490 UIManager.setLookAndFeel(laf);
491 }
492 catch (final java.lang.ClassNotFoundException e) {
493 System.out.println("Look and Feel not found: " + laf);
494 Main.pref.put("laf", defaultlaf);
495 }
496 catch (final javax.swing.UnsupportedLookAndFeelException e) {
497 System.out.println("Look and Feel not supported: " + laf);
498 Main.pref.put("laf", defaultlaf);
499 }
500 toolbar = new ToolbarPreferences();
501 contentPanePrivate.updateUI();
502 panel.updateUI();
503 } catch (final Exception e) {
504 e.printStackTrace();
505 }
506 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
507 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
508 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
509 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
510
511 I18n.translateJavaInternalMessages();
512
513 // init default coordinate format
514 //
515 try {
516 //CoordinateFormat format = CoordinateFormat.valueOf(Main.pref.get("coordinates"));
517 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
518 } catch (IllegalArgumentException iae) {
519 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
520 }
521
522 geometry = WindowGeometry.mainWindow("gui.geometry",
523 (args.containsKey("geometry") ? args.get("geometry").iterator().next() : null),
524 !args.containsKey("no-maximize"));
525 }
526
527 public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
528 if (args.containsKey("download")) {
529 List<File> fileList = new ArrayList<File>();
530 for (String s : args.get("download")) {
531 File f = null;
532 switch(paramType(s)) {
533 case httpUrl:
534 downloadFromParamHttp(false, s);
535 break;
536 case bounds:
537 downloadFromParamBounds(false, s);
538 break;
539 case fileUrl:
540 try {
541 f = new File(new URI(s));
542 } catch (URISyntaxException e) {
543 JOptionPane.showMessageDialog(
544 Main.parent,
545 tr("Ignoring malformed file URL: \"{0}\"", s),
546 tr("Warning"),
547 JOptionPane.WARNING_MESSAGE
548 );
549 }
550 if (f!=null) {
551 fileList.add(f);
552 }
553 break;
554 case fileName:
555 f = new File(s);
556 fileList.add(f);
557 break;
558 }
559 }
560 if(!fileList.isEmpty())
561 {
562 OpenFileAction.openFiles(fileList, true);
563 }
564 }
565 if (args.containsKey("downloadgps")) {
566 for (String s : args.get("downloadgps")) {
567 switch(paramType(s)) {
568 case httpUrl:
569 downloadFromParamHttp(true, s);
570 break;
571 case bounds:
572 downloadFromParamBounds(true, s);
573 break;
574 case fileUrl:
575 case fileName:
576 JOptionPane.showMessageDialog(
577 Main.parent,
578 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
579 tr("Warning"),
580 JOptionPane.WARNING_MESSAGE
581 );
582 }
583 }
584 }
585 if (args.containsKey("selection")) {
586 for (String s : args.get("selection")) {
587 SearchAction.search(s, SearchAction.SearchMode.add);
588 }
589 }
590 }
591
592 public static boolean saveUnsavedModifications() {
593 if (map == null) return true;
594 SaveLayersDialog dialog = new SaveLayersDialog(Main.parent);
595 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
596 for (OsmDataLayer l: Main.map.mapView.getLayersOfType(OsmDataLayer.class)) {
597 if ((l.requiresSaveToFile() || l.requiresUploadToServer()) && l.data.isModified()) {
598 layersWithUnmodifiedChanges.add(l);
599 }
600 }
601 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
602 if (!layersWithUnmodifiedChanges.isEmpty()) {
603 dialog.getModel().populate(layersWithUnmodifiedChanges);
604 dialog.setVisible(true);
605 switch(dialog.getUserAction()) {
606 case CANCEL: return false;
607 case PROCEED: return true;
608 default: return false;
609 }
610 }
611
612 return true;
613 }
614
615 public static boolean exitJosm(boolean exit) {
616 if (Main.saveUnsavedModifications()) {
617 geometry.remember("gui.geometry");
618 if (map != null) {
619 map.rememberToggleDialogWidth();
620 }
621 pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
622 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
623 if (Main.isDisplayingMapView()) {
624 Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
625 for (Layer l: layers) {
626 Main.map.mapView.removeLayer(l);
627 }
628 }
629 if (exit) {
630 System.exit(0);
631 return true;
632 } else
633 return true;
634 } else
635 return false;
636 }
637
638 /**
639 * The type of a command line parameter, to be used in switch statements.
640 * @see paramType
641 */
642 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
643
644 /**
645 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
646 * @param s A parameter string
647 * @return The guessed parameter type
648 */
649 private DownloadParamType paramType(String s) {
650 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
651 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
652 String coorPattern = "\\s*[0-9]+(\\.[0-9]+)?\\s*";
653 if(s.matches(coorPattern+"(,"+coorPattern+"){3}")) return DownloadParamType.bounds;
654 // everything else must be a file name
655 return DownloadParamType.fileName;
656 }
657
658 /**
659 * Download area specified on the command line as OSM URL.
660 * @param rawGps Flag to download raw GPS tracks
661 * @param s The URL parameter
662 */
663 private static void downloadFromParamHttp(final boolean rawGps, String s) {
664 final Bounds b = OsmUrlToBounds.parse(s);
665 if (b == null) {
666 JOptionPane.showMessageDialog(
667 Main.parent,
668 tr("Ignoring malformed URL: \"{0}\"", s),
669 tr("Warning"),
670 JOptionPane.WARNING_MESSAGE
671 );
672 } else {
673 downloadFromParamBounds(rawGps, b);
674 }
675 }
676
677 /**
678 * Download area specified on the command line as bounds string.
679 * @param rawGps Flag to download raw GPS tracks
680 * @param s The bounds parameter
681 */
682 private static void downloadFromParamBounds(final boolean rawGps, String s) {
683 final StringTokenizer st = new StringTokenizer(s, ",");
684 if (st.countTokens() == 4) {
685 Bounds b = new Bounds(
686 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
687 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
688 );
689 downloadFromParamBounds(rawGps, b);
690 }
691 }
692
693 /**
694 * Download area specified as Bounds value.
695 * @param rawGps Flag to download raw GPS tracks
696 * @param b The bounds value
697 * @see downloadFromParamBounds(final boolean rawGps, String s)
698 * @see downloadFromParamHttp
699 */
700 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
701 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
702 // asynchronously launch the download task ...
703 Future<?> future = task.download(true, b, null);
704 // ... and the continuation when the download is finished (this will wait for the download to finish)
705 Main.worker.execute(new PostDownloadHandler(task, future));
706 }
707
708 public static void determinePlatformHook() {
709 String os = System.getProperty("os.name");
710 if (os == null) {
711 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
712 platform = new PlatformHookUnixoid();
713 } else if (os.toLowerCase().startsWith("windows")) {
714 platform = new PlatformHookWindows();
715 } else if (os.equals("Linux") || os.equals("Solaris") ||
716 os.equals("SunOS") || os.equals("AIX") ||
717 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
718 platform = new PlatformHookUnixoid();
719 } else if (os.toLowerCase().startsWith("mac os x")) {
720 platform = new PlatformHookOsx();
721 } else {
722 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
723 platform = new PlatformHookUnixoid();
724 }
725 }
726
727 private static class WindowPositionSizeListener extends WindowAdapter implements
728 ComponentListener {
729 @Override
730 public void windowStateChanged(WindowEvent e) {
731 Main.windowState = e.getNewState();
732 }
733
734 @Override
735 public void componentHidden(ComponentEvent e) {
736 }
737
738 @Override
739 public void componentMoved(ComponentEvent e) {
740 handleComponentEvent(e);
741 }
742
743 @Override
744 public void componentResized(ComponentEvent e) {
745 handleComponentEvent(e);
746 }
747
748 @Override
749 public void componentShown(ComponentEvent e) {
750 }
751
752 private void handleComponentEvent(ComponentEvent e) {
753 Component c = e.getComponent();
754 if (c instanceof JFrame && c.isVisible() && Main.windowState == JFrame.NORMAL) {
755 Main.geometry = new WindowGeometry((JFrame) c);
756 }
757 }
758 }
759 public static void addListener() {
760 parent.addComponentListener(new WindowPositionSizeListener());
761 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
762 }
763
764 public static void checkJava6() {
765 String version = System.getProperty("java.version");
766 if (version != null) {
767 if (version.startsWith("1.6") || version.startsWith("6") ||
768 version.startsWith("1.7") || version.startsWith("7"))
769 return;
770 if (version.startsWith("1.5") || version.startsWith("5")) {
771 JLabel ho = new JLabel("<html>"+
772 tr("<h2>JOSM requires Java version 6.</h2>"+
773 "Detected Java version: {0}.<br>"+
774 "You can <ul><li>update your Java (JRE) or</li>"+
775 "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
776 "More Info:", version)+"</html>");
777 JTextArea link = new JTextArea("http://josm.openstreetmap.de/wiki/Help/SystemRequirements");
778 link.setEditable(false);
779 link.setBackground(panel.getBackground());
780 JPanel panel = new JPanel(new GridBagLayout());
781 GridBagConstraints gbc = new GridBagConstraints();
782 gbc.gridwidth = GridBagConstraints.REMAINDER;
783 gbc.anchor = GridBagConstraints.WEST;
784 gbc.weightx = 1.0;
785 panel.add(ho, gbc);
786 panel.add(link, gbc);
787 final String EXIT = tr("Exit JOSM");
788 final String CONTINUE = tr("Continue, try anyway");
789 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
790 if (ret == 0) {
791 System.exit(0);
792 }
793 return;
794 }
795 }
796 System.err.println("Error: Could not recognize Java Version: "+version);
797 }
798
799 /* ----------------------------------------------------------------------------------------- */
800 /* projection handling - Main is a registry for a single, global projection instance */
801 /* */
802 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
803 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
804 /* ----------------------------------------------------------------------------------------- */
805 /**
806 * The projection method used.
807 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
808 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
809 */
810 private static Projection proj;
811
812 /**
813 * Replies the current projection.
814 *
815 * @return
816 */
817 public static Projection getProjection() {
818 return proj;
819 }
820
821 /**
822 * Sets the current projection
823 *
824 * @param p the projection
825 */
826 public static void setProjection(Projection p) {
827 CheckParameterUtil.ensureParameterNotNull(p);
828 Projection oldValue = proj;
829 proj = p;
830 fireProjectionChanged(oldValue, proj);
831 }
832
833 /*
834 * Keep WeakReferences to the listeners. This relieves clients from the burden of
835 * explicitly removing the listeners and allows us to transparently register every
836 * created dataset as projection change listener.
837 */
838 private static final ArrayList<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
839
840 private static void fireProjectionChanged(Projection oldValue, Projection newValue) {
841 if (newValue == null ^ oldValue == null
842 || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
843
844 synchronized(Main.class) {
845 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
846 while(it.hasNext()){
847 WeakReference<ProjectionChangeListener> wr = it.next();
848 ProjectionChangeListener listener = wr.get();
849 if (listener == null) {
850 it.remove();
851 continue;
852 }
853 listener.projectionChanged(oldValue, newValue);
854 }
855 }
856 if (newValue != null) {
857 Bounds b = (Main.map != null && Main.map.mapView != null) ? Main.map.mapView.getRealBounds() : null;
858 if (b != null){
859 Main.map.mapView.zoomTo(b);
860 }
861 }
862 /* TODO - remove layers with fixed projection */
863 }
864 }
865
866 /**
867 * Register a projection change listener
868 *
869 * @param listener the listener. Ignored if null.
870 */
871 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
872 if (listener == null) return;
873 synchronized (Main.class) {
874 for (WeakReference<ProjectionChangeListener> wr : listeners) {
875 // already registered ? => abort
876 if (wr.get() == listener) return;
877 }
878 listeners.add(new WeakReference<ProjectionChangeListener>(listener));
879 }
880 }
881
882 /**
883 * Removes a projection change listener
884 *
885 * @param listener the listener. Ignored if null.
886 */
887 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
888 if (listener == null) return;
889 synchronized(Main.class){
890 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
891 while(it.hasNext()){
892 WeakReference<ProjectionChangeListener> wr = it.next();
893 // remove the listener - and any other listener which god garbage
894 // collected in the meantime
895 if (wr.get() == null || wr.get() == listener) {
896 it.remove();
897 }
898 }
899 }
900 }
901}
Note: See TracBrowser for help on using the repository browser.