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