AutoVectorBackground - load VectorBackground layers from a config file
[potlatch2.git] / potlatch2.mxml
1 <?xml version="1.0" encoding="utf-8"?>
2 <mx:Application 
3         xmlns:mx="http://www.adobe.com/2006/mxml" 
4         xmlns:halcyon="net.systemeD.halcyon.*"
5         xmlns:potlatch2="net.systemeD.potlatch2.*"
6         layout="vertical"
7         horizontalScrollPolicy="off"
8         verticalScrollPolicy="off"
9         horizontalAlign="center" 
10         addedToStage="initApp()">
11         
12         <mx:Style source="styles/Application.css"/>
13
14     <mx:Glow id="glowImage" duration="100" 
15         alphaFrom="0.3" alphaTo="1.0" 
16         blurXFrom="0.0" blurXTo="5.0" 
17         blurYFrom="0.0" blurYTo="5.0" 
18         color="0xFF8000"/>
19     <mx:Glow id="unglowImage" duration="100" 
20         alphaFrom="1.0" alphaTo="0.3" 
21         blurXFrom="5.0" blurXTo="0.0" 
22         blurYFrom="5.0" blurYTo="0.0" 
23         color="0xFF8000"/>
24     <mx:WipeLeft id="wipeOut" duration="250"/>
25     <mx:WipeRight id="wipeIn" duration="250"/>
26
27     <mx:ApplicationControlBar dock="true">
28         <mx:PopUpButton id="bgButton" label="Background" openAlways="true"
29             creationComplete="bgButton.popUp = new BackgroundSelector();"/>
30         <mx:PopUpButton id="styleButton" label="Map Style" openAlways="true"
31             creationComplete="styleButton.popUp = new StyleSelector();"/>
32                 <mx:PopUpMenuButton id="gpsButton" itemClick="if (event.index==0) { trackLoader.load(); } else { new MyGpxDialog().init(); }">
33                         <mx:dataProvider>
34                                 <mx:Array>
35                                         <mx:Object label="GPS data" />
36                                         <mx:Object label="My tracks" />
37                                 </mx:Array>
38                         </mx:dataProvider>
39                 </mx:PopUpMenuButton>
40         <mx:Button id="bugsButton" label="Bugs" click="bugLoader.load();" visible="false"/>
41         <mx:Button id="bikeButton" label="Bike Shops" click="bikeShopLoader.load();" visible="false" />
42         <mx:Spacer width="100%"/>
43         <mx:Button label="Undo" click="MainUndoStack.getGlobalStack().undo();"
44             enabled="{MainUndoStack.getGlobalStack().canUndo()}"/>
45         <mx:Button label="Redo" click="MainUndoStack.getGlobalStack().redo();"
46             enabled="{MainUndoStack.getGlobalStack().canRedo()}"/>
47         <mx:Spacer width="100%"/>
48         <mx:Button label="Help" click="new HelpDialog().init();" />
49         <mx:Button label="Options" click="new OptionsDialog().init();" /> 
50         <mx:Button label="Save" icon="@Embed('embedded/save.svg')" click="SaveManager.saveChanges();" id="saveButton" 
51                         enabled="false"/>
52     </mx:ApplicationControlBar>
53     
54     <mx:HDividedBox width="100%" height="100%">
55
56           <!-- Tag viewer -->
57           <potlatch2:TagViewer width="25%" height="100%" id="tagViewer"/>
58
59       <mx:Canvas width="75%" height="100%">
60         <mx:Canvas id="map_area" resize="onResizeMap()"
61             top="0" left="0" width="100%" height="100%" dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);">
62         </mx:Canvas>
63         <mx:Image source="@Embed('embedded/zoomIn.svg')" right="3" top="3" click="theMap.zoomIn();"
64             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom in - currently z'+getScale()}" />
65         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
66             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom out - currently z'+getScale()}" />
67         <mx:TextArea id="dataWorking" text="" right="20" top="3" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="18"
68             enabled="false" borderThickness="0"
69             showEffect="{wipeIn}" hideEffect="{wipeOut}"/>
70
71     </mx:Canvas>
72
73     </mx:HDividedBox>
74
75         <mx:Script><![CDATA[
76                 import net.systemeD.halcyon.*;
77                 import net.systemeD.halcyon.connection.*;
78                 import net.systemeD.potlatch2.*;
79                 import net.systemeD.potlatch2.save.SaveManager;
80                 import net.systemeD.potlatch2.controller.*;
81                 import net.systemeD.potlatch2.help.*;
82                 import net.systemeD.potlatch2.options.*;
83                 import net.systemeD.potlatch2.utils.*;
84         import net.systemeD.potlatch2.mygpx.*;
85                 import mx.managers.PopUpManager;
86                 import flash.system.Security;
87                 import flash.net.*;
88                 import flash.events.MouseEvent;
89                 import flash.display.Sprite;
90                 import mx.core.IChildList;
91         import mx.containers.Canvas;
92                 import mx.core.Application;
93         import mx.events.DragEvent;
94         import mx.managers.DragManager;
95         import mx.core.DragSource;
96         import mx.controls.Alert;
97
98         public var theMap:Map;
99         public var theController:EditController;
100                 public var yahoo:Yahoo;
101                 public var trackLoader:TrackLoader;
102                 public var toolbox:Toolbox;
103         public var bugLoader:BugLoader;
104         public var bikeShopLoader:BikeShopLoader;
105
106                 private var savecount:uint=0;
107                 private var loadcount:uint=0;
108
109         include "version.as";
110
111                 private function initApp():void {
112
113                         Globals.vars.map_area = map_area;
114                         Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
115                         var _root:IChildList = map_area.rawChildren;            // convenient local shorthand
116                         Globals.vars.nocache = loaderInfo.parameters['nocache'] == 'true';
117
118                         // populate sharedObject with loaderInfo parameters if supplied
119                         var obj:SharedObject = SharedObject.getLocal("user_state");
120                         var objChanged:Boolean = false;
121                         if (loaderInfo.parameters['tileurl']) {
122                                 obj.setProperty('background_url',loaderInfo.parameters['tileurl']); 
123                                 obj.setProperty('background_name','Custom'); 
124                                 objChanged=true;
125                         }
126                         if (loaderInfo.parameters['style']) { 
127                                 obj.setProperty('stylesheet_url',loaderInfo.parameters['style']);
128                                 obj.setProperty('stylesheet_name','Custom');
129                                 objChanged=true; 
130                         }
131                         if (objChanged) { obj.flush(); }
132
133                         // load imagery and style XML
134                 var request:DebugURLRequest = new DebugURLRequest("imagery.xml");
135                 var loader:URLLoader = new URLLoader();
136                 loader.addEventListener(Event.COMPLETE, onImageryLoad);
137                 loader.load(request.request);
138
139                         var request2:DebugURLRequest = new DebugURLRequest("stylesheets.xml");
140                         var loader2:URLLoader = new URLLoader();
141                 loader2.addEventListener(Event.COMPLETE, onStylesheetsLoad);
142                 loader2.load(request2.request);
143
144                         // map backdrop object
145             var w:uint = map_area.width;
146             var h:uint = map_area.height;
147             var b:Sprite = new Sprite();
148             b.height=h; b.width=w;
149             b.graphics.beginFill(0xFFFFEA,100); 
150             b.graphics.drawRect(0,0,w,h); 
151             b.graphics.endFill();
152                         _root.addChild(b);
153
154                         // create map and Yahoo
155                         theMap=new Map(this.loaderInfo.parameters);
156
157             // Auto-load vector backgrounds from config
158             // This could go spectacularly wrong if map.init completes before the event listener below is added
159             var vectorloader:AutoVectorBackground = new AutoVectorBackground(theMap);
160             theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void {vectorloader.load();});
161
162                         theMap.backdrop=b;
163                         yahoo=new Yahoo(w,h,theMap);
164                         yahoo.hide();
165                         _root.addChild(yahoo);
166                         _root.addChild(theMap);
167             theMap.updateSize(w,h);
168                         theMap.addEventListener(MapEvent.SCALE, scaleHandler);
169
170                         // add mask for map
171                         var s:Sprite=new Sprite();
172                         s.graphics.beginFill(0xFFFFFF,100);
173                         s.graphics.drawRect(0,0,w,h);
174                         s.graphics.endFill();
175                         _root.addChild(s);
176                         theMap.mask=s;
177
178                         // mouse-up handler attached to stage, so the user can release outside the map
179                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
180                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
181                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
182
183                         // keyboard event attached to stage
184                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
185
186                         // position toolbox
187                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
188                         toolbox.init(theController);
189                         toolbox.x=stage.stageWidth-toolbox.width-15;
190                         toolbox.y=stage.stageHeight-toolbox.height-15;
191
192                         // add debug field
193                         var t:TextField=new TextField();
194                         t.width=500; t.height=150; t.border=true;
195                         t.multiline=true;
196                         _root.addChild(t);
197                         Globals.vars.debug=t;
198             t.visible = loaderInfo.parameters["show_debug"] == 'true';
199                         Globals.vars.root=theMap;       // just for the addDebug function
200
201             theController = new EditController(theMap, tagViewer, toolbox);
202             theController.setActive();
203             
204             var conn:Connection = Connection.getConnectionInstance();
205             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
206             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
207             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
208             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
209             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
210             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
211                         conn.addEventListener(MapEvent.ERROR, onMapError);
212
213             // set the access token from saved cookie
214             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
215             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
216
217                         // create GPS trackloader
218                         trackLoader=new TrackLoader(theMap,conn.apiBase);
219
220             // create Bug loader
221             if (loaderInfo.parameters["bugs_url"] && loaderInfo.parameters["bugs_apikey"]) {
222               bugsButton.visible = true;
223               bugLoader = new BugLoader(theMap, loaderInfo.parameters["bugs_url"], loaderInfo.parameters["bugs_apikey"]);
224             }
225
226             // create Bike Shop loader
227             bikeShopLoader = new BikeShopLoader(theMap, 'http://shaunmcdonald.dev.openstreetmap.org/bike-shop-locator/');
228
229             // Force authentication on startup, if required
230             // force_auth == force => checks for access token, and displays OAuth panel if needed
231             var force_auth:String = loaderInfo.parameters["force_auth"];
232             if (!conn.hasAccessToken() && force_auth == 'force') {
233               SaveManager.ensureAccess(onAccessChecked);
234             }
235
236             // show help dialog on startup, if required
237             // show_help == always => on every startup
238             // show_help == once => show on first startup only
239             var show_help:String = loaderInfo.parameters["show_help"];
240
241             if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
242               new HelpDialog().init();
243             }
244
245             // Check if Tiger highlighting should be enabled from saved object
246             Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
247                 }
248                 
249                 public function onMapError(event:MapEvent):void {
250                         Alert.show(event.params.message, 'Error', mx.controls.Alert.OK);
251                 }
252
253         public function onResizeMap():void {
254             if ( theMap != null )
255                 theMap.updateSize(map_area.width, map_area.height);
256
257                         if (toolbox) {
258                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-15);
259                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-15);
260                         }
261         }
262
263         private function onDataStart(event:Event):void {
264                         switch (event.type) {
265                                 case Connection.LOAD_STARTED:   loadcount++; break;
266                                 case Connection.SAVE_STARTED:   savecount++; break;
267                         }
268                         updateDataWorking();
269         }
270         private function onDataComplete(event:Event):void {
271                         switch (event.type) {
272                                 case Connection.LOAD_COMPLETED: loadcount--; break;
273                                 case Connection.SAVE_COMPLETED: savecount--; break;
274                         }
275             updateDataWorking();
276         }
277                 private function updateDataWorking():void {
278                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
279                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
280                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
281                         else                            { dataWorking.text=""; }
282                         dataWorking.visible=(dataWorking.text!="");
283                 }
284         private function onDataDirty(event:Event):void {
285                         saveButton.enabled=true;
286             if (ExternalInterface.available) {
287               ExternalInterface.call("markChanged", false);
288             }
289                 }
290                 private function onDataClean(event:Event):void {
291                         saveButton.enabled=false;
292             if (ExternalInterface.available) {
293               ExternalInterface.call("markChanged", true);
294             }
295                 }
296                 
297         private function onImageryLoad(event:Event):void {
298                         var xml:XML = new XML(URLLoader(event.target).data);
299                         var saved:Object;
300                         if (SharedObject.getLocal("user_state").data['background_url']) {
301                                 saved={ name: SharedObject.getLocal("user_state").data['background_name'],
302                                                 url:  SharedObject.getLocal("user_state").data['background_url' ] };
303                         } else {
304                                 saved={ url: ''};
305                         }
306
307                         var isSet:Boolean=false;
308             var backgroundSet:Boolean = false;
309
310             theController.imagery=new Array(
311                                 { name: "None", url: "" },
312                                 { name: "Yahoo", url: "yahoo", sourcetag: "Yahoo" } );
313                         for each(var set:XML in xml.set) {
314                                 var obj:Object={};
315                                 var a:XML;
316                                 for each (a in set.@*) { obj[a.name().localName]=a.toString(); }
317                                 for each (a in set.* ) { obj[a.name()          ]=a.toString(); }
318                 theController.imagery.push(obj);
319                                 if ((obj.url ==saved.url) ||
320                                     (obj.name==saved.name && obj.name!='Custom')) { isSet=true; }
321                         }
322
323             if (!isSet && saved.name && saved.url && saved.url!='' && saved.url!='yahoo') {
324                 theController.imagery.push(saved);
325                 isSet=true;
326             }
327
328                         for each (var bg:Object in theController.imagery) {
329                                 if (bg.name==saved.name || bg.url==saved.url) {
330                                         setBackground(bg);
331                     backgroundSet = true;
332                                 }
333                         }
334
335             // For most contributors it's useful to set the background to yahoo by default, I reckon, but lets make it a config
336             if (!backgroundSet && loaderInfo.parameters['yahoo_default'] == 'true') {
337                 setBackground(theController.imagery[1]);
338             }
339                 }
340                 
341                 public function setBackground(bg:Object):void {
342                         if (bg.url=='yahoo') { theMap.setBackground(''); yahoo.show(); }
343                                         else { theMap.setBackground(bg); yahoo.hide(); }
344                         theController.imagerySelected=bg;
345                         var obj:SharedObject = SharedObject.getLocal("user_state");
346                         obj.setProperty('background_url' ,String(bg.url));
347                         obj.setProperty('background_name',String(bg.name));
348                         obj.flush();
349                 }
350
351                 public function getAvailableImagery():Array {
352                         var available:Array=[];
353                         for each (var bg:Object in theController.imagery) {
354                                 if (bg.minlon) {
355                                         // if there's a bbox, check the current viewport intersects it
356                                         if (((theMap.edge_l>bg.minlon && theMap.edge_l<bg.maxlon) ||
357                                              (theMap.edge_r>bg.minlon && theMap.edge_r<bg.maxlon) ||
358                                              (theMap.edge_l<bg.minlon && theMap.edge_r>bg.maxlon)) &&
359                                             ((theMap.edge_b>bg.minlat && theMap.edge_b<bg.maxlat) ||
360                                              (theMap.edge_t>bg.minlat && theMap.edge_t<bg.maxlat) ||
361                                              (theMap.edge_b<bg.minlat && theMap.edge_t>bg.maxlat))) {
362                                                 available.push(bg);
363                                         }
364                                 } else {
365                                         // if there's no bbox (i.e. global set), include it anyway
366                                         available.push(bg);
367                                 }
368                         }
369                         return available;
370                 }
371
372                 private function onStylesheetsLoad(event:Event):void {
373                         var xml:XML = new XML(URLLoader(event.target).data);
374                         var saved_url:String = SharedObject.getLocal("user_state").data['stylesheet_url'];
375                         var saved_name:String= SharedObject.getLocal("user_state").data['stylesheet_name'];
376                         var isInMenu:Boolean=false, isSet:Boolean=false;
377
378             // first, build the menu from the stylesheet list.
379             // Also ensure the saved_url is in the menu (might be either saved from before, or supplied via loaderInfo)
380             theController.stylesheets=new Array();
381                         for each(var set:XML in xml.stylesheet) {
382                                 var obj:Object={};
383                                 for (var a:String in set.children()) {
384                                         obj[set.child(a).name()]=set.child(a);
385                                 }
386                 theController.stylesheets.push(obj);
387                                 if (obj.url==saved_url || (obj.name==saved_name && obj.name!='Custom')) { isInMenu=true; }
388                         }
389                         if (saved_url && !isInMenu) { theController.stylesheets.push({ name:saved_name, url:saved_url }); }
390
391             // pick a stylesheet to be set. It should be the saved one, if it is in the menu
392             // or alternatively the first one on the menu,
393             // or finally try 'potlatch.css'
394                         for each (var ss:Object in theController.stylesheets) {
395                                 if (ss.name==saved_nameĀ || ss.url==saved_url) {
396                                         setStylesheet(ss.name, ss.url);
397                     isSet = true;
398                     break;
399                                 }
400                         }
401             if (!isSet) {
402               if(theController.stylesheets.length > 0) {
403                 var s:Object = theController.stylesheets[0];
404                 setStylesheet(s.name, s.url);
405               } else {
406                 //hit and hope. FIXME should this be an error state?
407                 theController.stylesheets.push({ name:'Potlatch', url:'potlatch.css'});
408                 setStylesheet('Potlatch','potlatch.css');
409               }
410             }
411                 }
412
413                 public function setStylesheet(name:String,url:String):void {
414                         theMap.setStyle(url);
415                         var obj:SharedObject = SharedObject.getLocal("user_state");
416                         obj.setProperty("stylesheet_url",url);
417                         obj.setProperty("stylesheet_name",name);
418                         obj.flush();
419                 }
420
421                 private function scaleHandler(event:MapEvent):void {
422                         dispatchEvent(new Event("rescale"));
423                 }
424                 
425                 [Bindable(event="rescale")]
426                 private function getScale():String {
427                         return String(theMap.scale);
428                 }
429
430         private function dragEnterHandler(event:DragEvent):void {
431             // Get the drop target component from the event object.
432             var dropTarget:Canvas=event.currentTarget as Canvas;
433             // Accept the drag only if the user is dragging poi with tags
434             if (event.dragSource.hasFormat('tags')) 
435             {
436                 DragManager.acceptDragDrop(dropTarget);
437             }
438         }
439         
440         private function dragDropHandler(event:DragEvent):void {
441                         // Deselect the dragged icon
442                         if (event.dragSource.dataForFormat('container')) {
443                                 event.dragSource.dataForFormat('container').selectedItem=-1;
444                         }
445
446                         // Get the tags
447             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
448             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
449             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
450             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
451             
452             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
453             
454             var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
455             for each ( var tag:Object in tags ) {
456                 node.setTag(tag.k, tag.v, createAction.push);
457             }
458                         Connection.getConnectionInstance().registerPOI(node);
459                         MainUndoStack.getGlobalStack().addAction(createAction);
460             theController.setState(new SelectedPOINode(node));
461         }
462
463         /* Called when forcing an initial access token check. */
464         private function onAccessChecked():void {
465             // Floaty panel message "You now have access";
466         }
467
468         ]]></mx:Script>
469
470 </mx:Application>
471