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