]> git.openstreetmap.org Git - potlatch2.git/blob - net/systemeD/potlatch2/collections/Imagery.as
Load imagery catalogue through FileBank
[potlatch2.git] / net / systemeD / potlatch2 / collections / Imagery.as
1 package net.systemeD.potlatch2.collections {
2
3         import flash.events.*;
4         import flash.display.*;
5         import flash.net.*;
6         import flash.text.TextField;
7         import net.systemeD.halcyon.FileBank;
8         import net.systemeD.halcyon.Map;
9         import net.systemeD.halcyon.MapEvent;
10         import net.systemeD.potlatch2.FunctionKeyManager;
11         import net.systemeD.potlatch2.Yahoo;
12         import mx.collections.ArrayCollection;
13
14         /*
15                 There's lots of further tidying we can do:
16                 - remove all the horrid Yahoo stuff
17                 - remove the backreferences to _map and send events instead
18                 but this will do for now and help remove the clutter from potlatch2.mxml.
19         */
20
21         public class Imagery extends EventDispatcher {
22
23         private static const GLOBAL_INSTANCE:Imagery = new Imagery();
24         public static function instance():Imagery { return GLOBAL_INSTANCE; }
25
26                 public var collection:Array=[];
27                 private var _selected:Object={};
28
29                 private var _map:Map;
30                 private var _overlay:Sprite;
31                 private var _yahoo:Yahoo;
32
33                 /* Load catalogue file */
34
35                 public function init(map:Map, overlay:Sprite, yahoo:Yahoo):void {
36                         _map = map;
37                         _overlay = overlay;
38                         _yahoo = yahoo;
39
40                         // load imagery file
41             FileBank.getInstance().addFromFile("imagery.xml", onImageryLoad);
42
43                         // create map listeners
44                         map.addEventListener(MapEvent.MOVE, moveHandler);
45                         map.addEventListener(MapEvent.RESIZE, resizeHandler);
46                 }
47
48                 private function onImageryLoad(fileBank:FileBank, filename:String):void {
49                         var xml:XML = new XML(fileBank.getAsString(filename));
50                         var saved:Object = {};
51                         var bg:Object;
52                         if (SharedObject.getLocal("user_state").data['background_url']!=undefined) {
53                                 saved={ name: SharedObject.getLocal("user_state").data['background_name'],
54                                                 url:  SharedObject.getLocal("user_state").data['background_url' ] };
55                         }
56
57                         var isSet:Boolean=false;
58             var backgroundSet:Boolean = false;
59
60                         // Read all values from XML file
61                         collection=new Array({ name: "None", url: "" });
62                         for each(var set:XML in xml.set) {
63                                 var obj:Object={};
64                                 var a:XML;
65                                 for each (a in set.@*) { obj[a.name().localName]=a.toString(); }
66                                 for each (a in set.* ) { obj[a.name()          ]=a.toString(); }
67                 collection.push(obj);
68                                 if ((saved.url  && obj.url ==saved.url) ||
69                                     (saved.name && obj.name==saved.name && obj.name!='Custom')) { isSet=true; }
70                         }
71
72                         // Add user's previous preference (from SharedObject) if we didn't find it in the XML file
73             if (!isSet && saved.name && saved.url && saved.url!='') {
74                 collection.push(saved);
75                 isSet=true;
76             }
77
78                         // Automatically select the user's previous preference
79                         var defaultBackground:Object=null;
80                         for each (bg in collection) {
81                                 if (bg.name==saved.name || bg.url==saved.url) {
82                                         setBackground(bg);
83                     backgroundSet = true;
84                                 } else if (bg.default) {
85                                         defaultBackground=bg;
86                                 }
87                         }
88
89             // Otherwise, set whatever's specified as default
90             if (!backgroundSet && defaultBackground) {
91                 setBackground(defaultBackground);
92             }
93
94                         // Get any attribution and logo details
95                         collection.forEach(function(bg:Object, index:int, array:Array):void {
96                                 if (bg.logo) {
97                                         // load the logo
98                                         var loader:Loader = new Loader();
99                                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void { onLogoLoad(e,bg); });
100                                         loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
101                                         loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
102                                         loader.load(new URLRequest(bg.logo));
103                                 }
104                                 if (bg.attribution_url) {
105                                         // load the attribution
106                                 var urlloader:URLLoader = new URLLoader();
107                                         urlloader.addEventListener(Event.COMPLETE, function(e:Event):void { onAttributionLoad(e,bg); });
108                                         urlloader.addEventListener(IOErrorEvent.IO_ERROR, onError);
109                                         urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
110                                 urlloader.load(new URLRequest(bg.attribution_url));
111                                 }
112                         });
113
114                         // Tell the function key manager that we'd like to receive function key calls
115                         FunctionKeyManager.instance().registerListener('Background imagery',
116                                 function(o:String):void { setBackground(findBackgroundWithName(o)); });
117                         dispatchEvent(new Event("collection_changed"));
118                 }
119                 
120                 private function onError(e:Event):void {
121                         // placeholder error routine so exception isn't thrown
122                 }
123                 
124                 public function onLogoLoad(e:Event, bg:Object):void {
125                         bg.logoData  = Bitmap(LoaderInfo(e.target).content).bitmapData;
126                         bg.logoWidth = e.target.loader.width;
127                         bg.logoHeight= e.target.loader.height;
128                         setLogo();
129                 }
130                 
131                 public function onAttributionLoad(e:Event,bg: Object):void {
132                         // if we ever need to cope with non-Microsoft attribution, then this should look at bg.scheme
133             default xml namespace = Namespace("http://schemas.microsoft.com/search/local/ws/rest/v1");
134             var xml:XML = new XML(e.target.data);
135                         var attribution:Object = {};
136             for each (var ImageryProvider:XML in xml..ImageryProvider) {
137                 var areas:Array=[];
138                 for each (var CoverageArea:XML in ImageryProvider.CoverageArea) {
139                     areas.push([CoverageArea.ZoomMin,
140                                 CoverageArea.ZoomMax,
141                                 CoverageArea.BoundingBox.SouthLatitude,
142                                 CoverageArea.BoundingBox.WestLongitude,
143                                 CoverageArea.BoundingBox.NorthLatitude,
144                                 CoverageArea.BoundingBox.EastLongitude]);
145                 }
146                 attribution[ImageryProvider.Attribution]=areas;
147             }
148                         default xml namespace = new Namespace("");
149                         bg.attribution=attribution;
150                         setAttribution();
151                 }
152
153                 public function setBackground(bg:Object):void {
154                         // set background
155                         _selected=bg;
156                         if (bg.url=='yahoo') { dispatchEvent(new CollectionEvent(CollectionEvent.SELECT, {url:''})); _yahoo.show(); }
157                                         else { dispatchEvent(new CollectionEvent(CollectionEvent.SELECT, bg      )); _yahoo.hide(); }
158                         // update attribution and logo
159                         _overlay.visible=bg.attribution || bg.logo || bg.terms_url;
160                         setLogo(); setAttribution(); setTerms();
161                         // save as SharedObject for next time
162                         var obj:SharedObject = SharedObject.getLocal("user_state");
163                         obj.setProperty('background_url' ,String(bg.url));
164                         obj.setProperty('background_name',String(bg.name));
165                         obj.flush();
166                 }
167                 
168                 public function get selected():Object { return _selected; }
169                 
170                 private function findBackgroundWithName(name:String):Object {
171                         for each (var bg:Object in collection) {
172                                 if (bg.name==name) { return bg; }
173                         }
174                         return { url:'' };
175                 }
176
177                 private function moveHandler(event:MapEvent):void {
178                         setAttribution();
179                         dispatchEvent(new Event("collection_changed"));
180                 }
181                 private function setAttribution():void {
182                         var tf:TextField=TextField(_overlay.getChildAt(0));
183                         tf.text='';
184                         if (!_selected.attribution) return;
185                         var attr:Array=[];
186                         for (var provider:String in _selected.attribution) {
187                                 for each (var bounds:Array in _selected.attribution[provider]) {
188                                         if (_map.scale>=bounds[0] && _map.scale<=bounds[1] &&
189                                           ((_map.edge_l>bounds[3] && _map.edge_l<bounds[5]) ||
190                                            (_map.edge_r>bounds[3] && _map.edge_r<bounds[5]) ||
191                                    (_map.edge_l<bounds[3] && _map.edge_r>bounds[5])) &&
192                                           ((_map.edge_b>bounds[2] && _map.edge_b<bounds[4]) ||
193                                            (_map.edge_t>bounds[2] && _map.edge_t<bounds[4]) ||
194                                            (_map.edge_b<bounds[2] && _map.edge_t>bounds[4]))) {
195                                                 attr.push(provider);
196                                         }
197                                 }
198                         }
199                         if (attr.length==0) return;
200                         tf.text="Background "+attr.join(", ");
201                         positionAttribution();
202                         dispatchEvent(new MapEvent(MapEvent.BUMP, { y: tf.textHeight }));       // don't let the toolbox obscure it
203                 }
204                 private function positionAttribution():void {
205                         var tf:TextField=TextField(_overlay.getChildAt(0));
206                         tf.x=_map.mapwidth  - 5 - tf.textWidth;
207                         tf.y=_map.mapheight - 5 - tf.textHeight;
208                 }
209
210                 private function setLogo():void {
211                         while (_overlay.numChildren>2) { _overlay.removeChildAt(2); }
212                         if (!_selected.logoData) return;
213                         var logo:Sprite=new Sprite();
214                         logo.addChild(new Bitmap(_selected.logoData));
215                         if (_selected.logo_url) { logo.buttonMode=true; logo.addEventListener(MouseEvent.CLICK, launchLogoLink, false, 0, true); }
216                         _overlay.addChild(logo);
217                         positionLogo();
218                 }
219                 private function positionLogo():void {
220                         _overlay.getChildAt(2).x=5;
221                         _overlay.getChildAt(2).y=_map.mapheight - 5 - _selected.logoHeight - (_selected.terms_url ? 10 : 0);
222                 }
223                 private function launchLogoLink(e:Event):void {
224                         if (!_selected.logo_url) return;
225                         navigateToURL(new URLRequest(_selected.logo_url), '_blank');
226                 }
227                 private function setTerms():void {
228                         var terms:TextField=TextField(_overlay.getChildAt(1));
229                         if (!_selected.terms_url) { terms.text=''; return; }
230                         terms.text="Background terms of use";
231                         positionTerms();
232                         terms.addEventListener(MouseEvent.CLICK, launchTermsLink, false, 0, true);
233                 }
234                 private function positionTerms():void {
235                         _overlay.getChildAt(1).x=5;
236                         _overlay.getChildAt(1).y=_map.mapheight - 15;
237                 }
238                 private function launchTermsLink(e:Event):void {
239                         if (!_selected.terms_url) return;
240                         navigateToURL(new URLRequest(_selected.terms_url), '_blank');
241                 }
242
243                 private function resizeHandler(event:MapEvent):void {
244                         if (_selected.logoData) positionLogo();
245                         if (_selected.terms_url) positionTerms();
246                         if (_selected.attribution) positionAttribution();
247                 }
248
249                 [Bindable(event="collection_changed")]
250                 public function getAvailableImagery():ArrayCollection {
251                         var available:Array=[];
252                         for each (var bg:Object in collection) {
253                                 if (bg.minlon) {
254                                         // if there's a bbox, check the current viewport intersects it
255                                         if (((_map.edge_l>bg.minlon && _map.edge_l<bg.maxlon) ||
256                                              (_map.edge_r>bg.minlon && _map.edge_r<bg.maxlon) ||
257                                              (_map.edge_l<bg.minlon && _map.edge_r>bg.maxlon)) &&
258                                             ((_map.edge_b>bg.minlat && _map.edge_b<bg.maxlat) ||
259                                              (_map.edge_t>bg.minlat && _map.edge_t<bg.maxlat) ||
260                                              (_map.edge_b<bg.minlat && _map.edge_t>bg.maxlat))) {
261                                                 available.push(bg);
262                                         }
263                                 } else {
264                                         // if there's no bbox (i.e. global set), include it anyway
265                                         available.push(bg);
266                                 }
267                         }
268                         return new ArrayCollection(available);
269                 }
270
271         }
272         
273 }