Add opencyclemap and mapquest tiles as optional background layers
[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" styleName="appBarButton"
29             creationComplete="bgButton.popUp = new BackgroundSelector();"/>
30         <mx:PopUpButton id="styleButton" label="Map Style" openAlways="true" styleName="appBarButton"
31             creationComplete="styleButton.popUp = new StyleSelector();"/>
32                 <mx:PopUpMenuButton id="gpsButton" styleName="appBarButton"
33                     itemClick="if (event.index==0) { trackLoader.load(); } else { new MyGpxDialog().init(); }">
34                         <mx:dataProvider>
35                                 <mx:Array>
36                                         <mx:Object label="GPS data" />
37                                         <mx:Object label="My tracks" />
38                                 </mx:Array>
39                         </mx:dataProvider>
40                 </mx:PopUpMenuButton>
41         <mx:Spacer width="100%"/>
42         <mx:Button label="Undo" click="MainUndoStack.getGlobalStack().undo();" styleName="appBarButton"
43             enabled="{MainUndoStack.getGlobalStack().canUndo()}"/>
44         <mx:Button label="Redo" click="MainUndoStack.getGlobalStack().redo();" styleName="appBarButton"
45             enabled="{MainUndoStack.getGlobalStack().canRedo()}"/>
46         <mx:Spacer width="100%"/>
47         <mx:Button label="Help" click="new HelpDialog().init();" styleName="appBarButton" />
48         <mx:Button label="Options" click="new OptionsDialog().init();" styleName="appBarButton" /> 
49         <mx:Button label="Save" icon="@Embed('embedded/upload.svg')" disabledIcon="@Embed('embedded/upload_disabled.svg')" styleName="appBarButton"
50                         click="SaveManager.saveChanges();" id="saveButton" enabled="false"/>
51     </mx:ApplicationControlBar>
52     
53     <mx:HDividedBox width="100%" height="100%">
54
55           <!-- Tag viewer -->
56           <potlatch2:TagViewer width="25%" height="100%" id="tagViewer"/>
57
58       <mx:Canvas width="75%" height="100%">
59         <mx:Canvas id="map_area" resize="onResizeMap()"
60             top="0" left="0" width="100%" height="100%" dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);">
61         </mx:Canvas>
62         <mx:Image source="@Embed('embedded/zoomIn.svg')" right="3" top="3" click="theMap.zoomIn();"
63             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom in - currently z'+getScale()}" />
64         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
65             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom out - currently z'+getScale()}" />
66         <mx:TextArea id="dataWorking" text="" right="20" top="3" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="18"
67             enabled="false" borderThickness="0"
68             showEffect="{wipeIn}" hideEffect="{wipeOut}"/>
69
70     </mx:Canvas>
71
72     </mx:HDividedBox>
73
74         <mx:Script><![CDATA[
75                 import net.systemeD.halcyon.*;
76                 import net.systemeD.halcyon.connection.*;
77                 import net.systemeD.potlatch2.*;
78                 import net.systemeD.potlatch2.save.SaveManager;
79                 import net.systemeD.potlatch2.collections.*;
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.events.CloseEvent;
95         import mx.managers.DragManager;
96         import mx.core.DragSource;
97         import mx.controls.Alert;
98
99         public var theMap:Map;
100         public var theController:EditController;
101                 public var yahoo:Yahoo;
102                 public var trackLoader:TrackLoader;
103                 public var toolbox:Toolbox;
104         public var bugLoader:BugLoader;
105         public var bikeShopLoader:BikeShopLoader;
106
107                 private var savecount:uint=0;
108                 private var loadcount:uint=0;
109
110         include "version.as";
111
112                 private function initApp():void {
113
114                         Globals.vars.map_area = map_area;
115                         Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
116                         var _root:IChildList = map_area.rawChildren;            // convenient local shorthand
117                         Globals.vars.nocache = loaderInfo.parameters['nocache'] == 'true';
118
119                         // populate sharedObject with loaderInfo parameters if supplied
120                         var obj:SharedObject = SharedObject.getLocal("user_state");
121                         var objChanged:Boolean = false;
122                         if (loaderInfo.parameters['tileurl']) {
123                                 obj.setProperty('background_url',loaderInfo.parameters['tileurl']); 
124                                 obj.setProperty('background_name','Custom'); 
125                                 objChanged=true;
126                         }
127                         if (loaderInfo.parameters['style']) { 
128                                 obj.setProperty('stylesheet_url',loaderInfo.parameters['style']);
129                                 obj.setProperty('stylesheet_name','Custom');
130                                 objChanged=true; 
131                         }
132                         if (objChanged) { obj.flush(); }
133
134                         // map backdrop object
135             var w:uint = map_area.width;
136             var h:uint = map_area.height;
137             var b:Sprite = new Sprite();
138             b.height=h; b.width=w;
139             b.graphics.beginFill(0xFFFFEA,100); 
140             b.graphics.drawRect(0,0,w,h); 
141             b.graphics.endFill();
142                         _root.addChild(b);
143
144                         // pass additional parameters to map
145                         var params:Object={}; var k:String;
146                         for (k in this.loaderInfo.parameters) {
147                                 params[k]=this.loaderInfo.parameters[k];
148                         }
149                         for (k in SharedObject.getLocal('user_state').data) {
150                                 params[k]=SharedObject.getLocal('user_state').data[k];
151                         }
152                         params['tileblocks']=[new RegExp("google","i")];        // hard-coded block on Google tiles
153
154                         // create map and Yahoo
155                         theMap=new Map(params);
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             theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void { VectorBackgrounds.instance().init(theMap); });
160
161                         theMap.backdrop=b;
162                         yahoo=new Yahoo(w,h,theMap);
163                         yahoo.hide();
164                         _root.addChild(yahoo);
165                         _root.addChild(theMap);
166             theMap.updateSize(w,h);
167                         theMap.addEventListener(MapEvent.SCALE, scaleHandler);
168
169                         // add mask for map
170                         var s:Sprite=new Sprite();
171                         s.graphics.beginFill(0xFFFFFF,100);
172                         s.graphics.drawRect(0,0,w,h);
173                         s.graphics.endFill();
174                         _root.addChild(s);
175                         theMap.mask=s;
176
177                         // add attribution/logo sprite
178                         var overlay:Sprite=new Sprite();
179                         var attribution:TextField=new TextField();
180                         attribution.width=220; attribution.height=300;
181                         attribution.multiline=true;
182                         attribution.wordWrap=true;
183                         attribution.selectable=false;
184                         attribution.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, false);
185                         overlay.addChild(attribution);
186                         var terms:TextField=new TextField();
187                         terms.width=200; terms.height=15;
188                         terms.selectable=false;
189                         terms.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, true);
190                         overlay.addChild(terms);
191                         _root.addChild(overlay);
192
193                         // mouse-up handler attached to stage, so the user can release outside the map
194                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
195                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
196                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
197
198                         // initialise imagery and stylesheets
199                         Imagery.instance().init(theMap, overlay, yahoo);
200                         Stylesheets.instance().init(theMap);
201                         Imagery.instance().addEventListener(MapEvent.BUMP, bumpHandler);
202
203                         // keyboard event attached to stage
204                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
205
206                         // position toolbox
207                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
208                         toolbox.init(theController);
209                         toolbox.x=stage.stageWidth-toolbox.width-5;
210                         toolbox.y=stage.stageHeight-toolbox.height-5;
211
212                         // add debug field
213                         var t:TextField=new TextField();
214                         t.width=500; t.height=150; t.border=true;
215                         t.multiline=true;
216                         _root.addChild(t);
217                         Globals.vars.debug=t;
218             t.visible = loaderInfo.parameters["show_debug"] == 'true';
219                         Globals.vars.root=theMap;       // just for the addDebug function
220
221             theController = new EditController(theMap, tagViewer, toolbox);
222             theController.setActive();
223             
224             var conn:Connection = Connection.getConnectionInstance();
225             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
226             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
227             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
228             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
229             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
230             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
231                         conn.addEventListener(MapEvent.ERROR, onMapError);
232                         conn.addEventListener(MapEvent.ATTENTION, onAttention);
233
234             // set the access token from saved cookie
235             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
236             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
237
238             // Load any requested GPX track
239             if (loaderInfo.parameters['gpx']) {
240                 var id:Number = loaderInfo.parameters['gpx'];
241                 if (conn.hasAccessToken()) { 
242                     loadTrace(id);
243                 } else {
244                     SaveManager.ensureAccess(function ():void { loadTrace(id); });
245                 }
246             }
247
248                         // Load arbitrary GPX from provided URL
249                         if (loaderInfo.parameters['gpx_url']) {
250                                 var vectorlayer:VectorLayer=new VectorLayer(name,theMap,"gpx.css");
251                                 vectorlayer.url=loaderInfo.parameters['gpx_url'];
252                                 var gpx:GpxImporter=new GpxImporter(vectorlayer, vectorlayer.paint, [vectorlayer.url], 
253                                                                     function(success:Boolean,message:String=null):void {
254                                         if (!success) return;
255                                         theMap.addVectorLayer(vectorlayer);
256                                         dispatchEvent(new Event("layers_changed"));
257                                                                     }, false);
258                         }
259
260                         // create GPS trackloader
261                         trackLoader=new TrackLoader(theMap,conn.apiBase);
262
263             // Force authentication on startup, if required
264             // force_auth == force => checks for access token, and displays OAuth panel if needed
265             var force_auth:String = loaderInfo.parameters["force_auth"];
266             if (!conn.hasAccessToken() && force_auth == 'force') {
267               SaveManager.ensureAccess(onAccessChecked);
268             }
269
270             // show help dialog on startup, if required
271             // show_help == always => on every startup
272             // show_help == once => show on first startup only
273             var show_help:String = loaderInfo.parameters["show_help"];
274
275             if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
276               new HelpDialog().init();
277             }
278
279             // Check if Tiger highlighting should be enabled from saved object
280             Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
281                 }
282                 
283                 public function onMapError(mapEvent:MapEvent):void {
284                         var buttons:uint=0;
285                         if (mapEvent.params.no) { trace("no is set"); }
286                         if (mapEvent.params.yes             ) buttons|=mx.controls.Alert.YES;
287                         if (mapEvent.params.no              ) buttons|=mx.controls.Alert.NO;
288                         if (mapEvent.params.cancel          ) buttons|=mx.controls.Alert.CANCEL;
289                         if (mapEvent.params.ok || buttons==0) buttons|=mx.controls.Alert.OK;
290                         trace("showing alert with "+buttons);
291                         Alert.show(mapEvent.params.message, 'Error', buttons, null, function(closeEvent:CloseEvent):void { 
292                                 switch (closeEvent.detail) {
293                                         case mx.controls.Alert.CANCEL:  mapEvent.params.cancel(); break;
294                                         case mx.controls.Alert.YES:             mapEvent.params.yes(); break;
295                                         case mx.controls.Alert.NO:              mapEvent.params.no(); break;
296                                         default:                                                if (mapEvent.params.ok) mapEvent.params.ok();
297                                 }
298                         });
299                 }
300
301                 /* Highlight an entity in response to an 'attention' event */
302
303                 public function onAttention(mapEvent:MapEvent):void {
304                         var entity:Entity=mapEvent.params.entity;
305                         if (entity is Relation) {
306                                 // If it's a relation, just bring up the editor panel
307                                 var panel:RelationEditorPanel = RelationEditorPanel(
308                                         PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
309                                 panel.setRelation(entity as Relation);
310                                 PopUpManager.centerPopUp(panel);
311                                 return;
312                         }
313
314                         var lat:Number, lon:Number;
315                         var panTo:Boolean=true;
316                         if (entity is Way) {
317                                 // If it's a way, find if it's on-screen
318                                 for (var i:uint=0; i<Way(entity).length; i++) {
319                                         var node:Node=Way(entity).getNode(i)
320                                         if (node.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
321                                         lat=node.lat; lon=node.lon;
322                                 }
323                         } else if (entity is Node) {
324                                 // If it's a node, check if it's on-screen
325                                 if (entity.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
326                                 lat=Node(entity).lat; lon=Node(entity).lon;
327                         }
328                         // Pan if required, and select the object
329                         if (panTo) { theMap.moveMapFromLatLon(lat,lon); }
330                         theController.setState(theController.findStateForSelection([entity]));
331                 }
332
333         public function onResizeMap():void {
334             if ( theMap != null )
335                 theMap.updateSize(map_area.width, map_area.height);
336
337                         if (toolbox) {
338                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-5);
339                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-5);
340                         }
341         }
342                 private function bumpHandler(e:MapEvent):void {
343                         if (toolbox) {
344                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-10-e.params.y);
345                         }
346                 }
347
348         private function onDataStart(event:Event):void {
349                         switch (event.type) {
350                                 case Connection.LOAD_STARTED:   loadcount++; break;
351                                 case Connection.SAVE_STARTED:   savecount++; break;
352                         }
353                         updateDataWorking();
354         }
355         private function onDataComplete(event:Event):void {
356                         switch (event.type) {
357                                 case Connection.LOAD_COMPLETED: loadcount--; break;
358                                 case Connection.SAVE_COMPLETED: savecount--; break;
359                         }
360             updateDataWorking();
361         }
362                 private function updateDataWorking():void {
363                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
364                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
365                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
366                         else                            { dataWorking.text=""; }
367                         dataWorking.visible=(dataWorking.text!="");
368                 }
369         private function onDataDirty(event:Event):void {
370                         saveButton.enabled=true;
371             if (ExternalInterface.available) {
372               ExternalInterface.call("markChanged", false);
373             }
374                 }
375                 private function onDataClean(event:Event):void {
376                         saveButton.enabled=false;
377             if (ExternalInterface.available) {
378               ExternalInterface.call("markChanged", true);
379             }
380                 }
381                 
382
383
384                 private function scaleHandler(event:MapEvent):void {
385                         dispatchEvent(new Event("rescale"));
386                 }
387                 
388                 [Bindable(event="rescale")]
389                 private function getScale():String {
390                         return String(theMap.scale);
391                 }
392
393         private function dragEnterHandler(event:DragEvent):void {
394             // Get the drop target component from the event object.
395             var dropTarget:Canvas=event.currentTarget as Canvas;
396             // Accept the drag only if the user is dragging poi with tags
397             if (event.dragSource.hasFormat('tags')) 
398             {
399                 DragManager.acceptDragDrop(dropTarget);
400             }
401         }
402         
403         private function dragDropHandler(event:DragEvent):void {
404                         // Deselect the dragged icon
405                         if (event.dragSource.dataForFormat('container')) {
406                                 event.dragSource.dataForFormat('container').selectedItem=-1;
407                         }
408
409                         // Get the tags
410             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
411             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
412             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
413             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
414             
415             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
416             
417             var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
418             for each ( var tag:Object in tags ) {
419                 node.setTag(tag.k, tag.v, createAction.push);
420             }
421                         Connection.getConnectionInstance().registerPOI(node);
422                         MainUndoStack.getGlobalStack().addAction(createAction);
423             theController.setState(new SelectedPOINode(node));
424         }
425
426         /* Called when forcing an initial access token check. */
427         private function onAccessChecked():void {
428             // Floaty panel message "You now have access";
429         }
430
431         private function loadTrace(id:Number):void {
432             var conn:Connection = Connection.getConnectionInstance();
433             conn.addEventListener(Connection.TRACES_LOADED, function (e:Event):void {
434                 for each (var trace:Trace in conn.getTraces()) {
435                     if (trace.id == id) { trace.addToMap(); }
436                 }
437             });
438             conn.fetchUserTraces();
439         }
440
441         ]]></mx:Script>
442
443 </mx:Application>
444