Two more files documented.
[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.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                         // map backdrop object
134             var w:uint = map_area.width;
135             var h:uint = map_area.height;
136             var b:Sprite = new Sprite();
137             b.height=h; b.width=w;
138             b.graphics.beginFill(0xFFFFEA,100); 
139             b.graphics.drawRect(0,0,w,h); 
140             b.graphics.endFill();
141                         _root.addChild(b);
142
143                         // pass additional parameters to map
144                         var params:Object={}; var k:String;
145                         for (k in this.loaderInfo.parameters) {
146                                 params[k]=this.loaderInfo.parameters[k];
147                         }
148                         for (k in SharedObject.getLocal('user_state').data) {
149                                 params[k]=SharedObject.getLocal('user_state').data[k];
150                         }
151                         params['tileblocks']=[new RegExp("google","i")];        // hard-coded block on Google tiles
152
153                         // create map and Yahoo
154                         theMap=new Map(params);
155
156             // Auto-load vector backgrounds from config
157             // This could go spectacularly wrong if map.init completes before the event listener below is added
158             theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void { VectorBackgrounds.instance().init(theMap); });
159
160                         theMap.backdrop=b;
161                         yahoo=new Yahoo(w,h,theMap);
162                         yahoo.hide();
163                         _root.addChild(yahoo);
164                         _root.addChild(theMap);
165             theMap.updateSize(w,h);
166                         theMap.addEventListener(MapEvent.SCALE, scaleHandler);
167
168                         // add mask for map
169                         var s:Sprite=new Sprite();
170                         s.graphics.beginFill(0xFFFFFF,100);
171                         s.graphics.drawRect(0,0,w,h);
172                         s.graphics.endFill();
173                         _root.addChild(s);
174                         theMap.mask=s;
175
176                         // add attribution/logo sprite
177                         var overlay:Sprite=new Sprite();
178                         var attribution:TextField=new TextField();
179                         attribution.width=220; attribution.height=300;
180                         attribution.multiline=true;
181                         attribution.wordWrap=true;
182                         attribution.selectable=false;
183                         attribution.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, false);
184                         overlay.addChild(attribution);
185                         var terms:TextField=new TextField();
186                         terms.width=200; terms.height=15;
187                         terms.selectable=false;
188                         terms.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, true);
189                         overlay.addChild(terms);
190                         _root.addChild(overlay);
191
192                         // mouse-up handler attached to stage, so the user can release outside the map
193                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
194                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
195                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
196
197                         // initialise imagery and stylesheets
198                         Imagery.instance().init(theMap, overlay, yahoo);
199                         Stylesheets.instance().init(theMap);
200                         Imagery.instance().addEventListener(MapEvent.BUMP, bumpHandler);
201
202                         // keyboard event attached to stage
203                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
204
205                         // position toolbox
206                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
207                         toolbox.init(theController);
208                         toolbox.x=stage.stageWidth-toolbox.width-5;
209                         toolbox.y=stage.stageHeight-toolbox.height-5;
210
211                         // add debug field
212                         var t:TextField=new TextField();
213                         t.width=500; t.height=150; t.border=true;
214                         t.multiline=true;
215                         _root.addChild(t);
216                         Globals.vars.debug=t;
217             t.visible = loaderInfo.parameters["show_debug"] == 'true';
218                         Globals.vars.root=theMap;       // just for the addDebug function
219
220             theController = new EditController(theMap, tagViewer, toolbox);
221             theController.setActive();
222             
223             var conn:Connection = Connection.getConnectionInstance();
224             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
225             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
226             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
227             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
228             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
229             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
230                         conn.addEventListener(MapEvent.ERROR, onMapError);
231
232             // set the access token from saved cookie
233             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
234             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
235
236             // Load any requested GPX track
237             if (loaderInfo.parameters['gpx']) {
238                 var id:Number = loaderInfo.parameters['gpx'];
239                 if (conn.hasAccessToken()) { 
240                     loadTrace(id);
241                 } else {
242                     SaveManager.ensureAccess(function ():void { loadTrace(id); });
243                 }
244             }
245
246                         // Load arbitrary GPX from provided URL
247                         if (loaderInfo.parameters['gpx_url']) {
248                                 var vectorlayer:VectorLayer=new VectorLayer(name,theMap,"gpx.css");
249                                 vectorlayer.url=loaderInfo.parameters['gpx_url'];
250                                 var gpx:GpxImporter=new GpxImporter(vectorlayer, vectorlayer.paint, [vectorlayer.url], 
251                                                                     function(success:Boolean,message:String=null):void {
252                                         if (!success) return;
253                                         theMap.addVectorLayer(vectorlayer);
254                                         dispatchEvent(new Event("layers_changed"));
255                                                                     }, false);
256                         }
257
258                         // create GPS trackloader
259                         trackLoader=new TrackLoader(theMap,conn.apiBase);
260
261             // Force authentication on startup, if required
262             // force_auth == force => checks for access token, and displays OAuth panel if needed
263             var force_auth:String = loaderInfo.parameters["force_auth"];
264             if (!conn.hasAccessToken() && force_auth == 'force') {
265               SaveManager.ensureAccess(onAccessChecked);
266             }
267
268             // show help dialog on startup, if required
269             // show_help == always => on every startup
270             // show_help == once => show on first startup only
271             var show_help:String = loaderInfo.parameters["show_help"];
272
273             if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
274               new HelpDialog().init();
275             }
276
277             // Check if Tiger highlighting should be enabled from saved object
278             Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
279                 }
280                 
281                 public function onMapError(event:MapEvent):void {
282                         Alert.show(event.params.message, 'Error', mx.controls.Alert.OK);
283                 }
284
285         public function onResizeMap():void {
286             if ( theMap != null )
287                 theMap.updateSize(map_area.width, map_area.height);
288
289                         if (toolbox) {
290                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-5);
291                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-5);
292                         }
293         }
294                 private function bumpHandler(e:MapEvent):void {
295                         if (toolbox) {
296                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-10-e.params.y);
297                         }
298                 }
299
300         private function onDataStart(event:Event):void {
301                         switch (event.type) {
302                                 case Connection.LOAD_STARTED:   loadcount++; break;
303                                 case Connection.SAVE_STARTED:   savecount++; break;
304                         }
305                         updateDataWorking();
306         }
307         private function onDataComplete(event:Event):void {
308                         switch (event.type) {
309                                 case Connection.LOAD_COMPLETED: loadcount--; break;
310                                 case Connection.SAVE_COMPLETED: savecount--; break;
311                         }
312             updateDataWorking();
313         }
314                 private function updateDataWorking():void {
315                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
316                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
317                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
318                         else                            { dataWorking.text=""; }
319                         dataWorking.visible=(dataWorking.text!="");
320                 }
321         private function onDataDirty(event:Event):void {
322                         saveButton.enabled=true;
323             if (ExternalInterface.available) {
324               ExternalInterface.call("markChanged", false);
325             }
326                 }
327                 private function onDataClean(event:Event):void {
328                         saveButton.enabled=false;
329             if (ExternalInterface.available) {
330               ExternalInterface.call("markChanged", true);
331             }
332                 }
333                 
334
335
336                 private function scaleHandler(event:MapEvent):void {
337                         dispatchEvent(new Event("rescale"));
338                 }
339                 
340                 [Bindable(event="rescale")]
341                 private function getScale():String {
342                         return String(theMap.scale);
343                 }
344
345         private function dragEnterHandler(event:DragEvent):void {
346             // Get the drop target component from the event object.
347             var dropTarget:Canvas=event.currentTarget as Canvas;
348             // Accept the drag only if the user is dragging poi with tags
349             if (event.dragSource.hasFormat('tags')) 
350             {
351                 DragManager.acceptDragDrop(dropTarget);
352             }
353         }
354         
355         private function dragDropHandler(event:DragEvent):void {
356                         // Deselect the dragged icon
357                         if (event.dragSource.dataForFormat('container')) {
358                                 event.dragSource.dataForFormat('container').selectedItem=-1;
359                         }
360
361                         // Get the tags
362             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
363             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
364             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
365             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
366             
367             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
368             
369             var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
370             for each ( var tag:Object in tags ) {
371                 node.setTag(tag.k, tag.v, createAction.push);
372             }
373                         Connection.getConnectionInstance().registerPOI(node);
374                         MainUndoStack.getGlobalStack().addAction(createAction);
375             theController.setState(new SelectedPOINode(node));
376         }
377
378         /* Called when forcing an initial access token check. */
379         private function onAccessChecked():void {
380             // Floaty panel message "You now have access";
381         }
382
383         private function loadTrace(id:Number):void {
384             var conn:Connection = Connection.getConnectionInstance();
385             conn.addEventListener(Connection.TRACES_LOADED, function (e:Event):void {
386                 for each (var trace:Trace in conn.getTraces()) {
387                     if (trace.id == id) { trace.addToMap(); }
388                 }
389             });
390             conn.fetchUserTraces();
391         }
392
393         ]]></mx:Script>
394
395 </mx:Application>
396