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