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