permit XML file nesting in map_features.xml
[potlatch2.git] / potlatch2.mxml
1 <?xml version="1.0" encoding="utf-8"?>
2 <mx:Application 
3         xmlns:mx="http://www.adobe.com/2006/mxml" 
4         xmlns:halcyon="net.systemeD.halcyon.*"
5         xmlns:potlatch2="net.systemeD.potlatch2.*"
6         layout="vertical"
7         horizontalScrollPolicy="off"
8         verticalScrollPolicy="off"
9         horizontalAlign="center" 
10         addedToStage="initApp()">
11         
12         <mx:Style source="styles/Application.css"/>
13
14     <mx:Glow id="glowImage" duration="100" 
15         alphaFrom="0.3" alphaTo="1.0" 
16         blurXFrom="0.0" blurXTo="5.0" 
17         blurYFrom="0.0" blurYTo="5.0" 
18         color="0xFF8000"/>
19     <mx:Glow id="unglowImage" duration="100" 
20         alphaFrom="1.0" alphaTo="0.3" 
21         blurXFrom="5.0" blurXTo="0.0" 
22         blurYFrom="5.0" blurYTo="0.0" 
23         color="0xFF8000"/>
24     <mx:WipeLeft id="wipeOut" duration="250"/>
25     <mx:WipeRight id="wipeIn" duration="250"/>
26
27     <mx:ApplicationControlBar dock="true">
28         <mx:PopUpButton id="bgButton" label="Background" openAlways="true" styleName="appBarButton"
29             creationComplete="bgButton.popUp = new BackgroundSelector();"/>
30         <mx:PopUpButton id="styleButton" label="Map Style" openAlways="true" styleName="appBarButton"
31             creationComplete="styleButton.popUp = new StyleSelector();"/>
32                 <mx:PopUpMenuButton id="gpsButton" styleName="appBarButton"
33                     itemClick="if (event.index==0) { trackLoader.load(); } else { new MyGpxDialog().init(); }">
34                         <mx:dataProvider>
35                                 <mx:Array>
36                                         <mx:Object label="GPS data" />
37                                         <mx:Object label="My tracks" />
38                                 </mx:Array>
39                         </mx:dataProvider>
40                 </mx:PopUpMenuButton>
41         <mx:Spacer width="100%"/>
42         <mx:Button label="Undo" click="MainUndoStack.getGlobalStack().undo();" styleName="appBarButton"
43             enabled="{MainUndoStack.getGlobalStack().canUndo()}"
44             toolTip="{MainUndoStack.getGlobalStack().getUndoDescription() ? 'Undo '+MainUndoStack.getGlobalStack().getUndoDescription() : 'Undo last action'}" />
45         <mx:Button label="Redo" click="MainUndoStack.getGlobalStack().redo();" styleName="appBarButton"
46             enabled="{MainUndoStack.getGlobalStack().canRedo()}"/>
47         <mx:Spacer width="100%"/>
48         <mx:Button label="Help" click="new HelpDialog().init();" styleName="appBarButton" />
49         <mx:Button label="Options" click="new OptionsDialog().init();" styleName="appBarButton" /> 
50         <mx:Button label="Save" icon="@Embed('embedded/upload.svg')" disabledIcon="@Embed('embedded/upload_disabled.svg')" styleName="appBarButton"
51                         click="SaveManager.saveChanges();" id="saveButton" enabled="false"/>
52     </mx:ApplicationControlBar>
53     
54     <mx:HDividedBox width="100%" height="100%">
55
56           <!-- Tag viewer -->
57           <potlatch2:TagViewer width="25%" height="100%" id="tagViewer"/>
58
59       <mx:Canvas width="75%" height="100%">
60         <mx:Canvas id="map_area" resize="onResizeMap()"
61             top="0" left="0" width="100%" height="100%" dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);">
62         </mx:Canvas>
63         <mx:Image source="@Embed('embedded/zoomIn.svg')" right="3" top="3" click="theMap.zoomIn();"
64             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom in - currently z'+getScale()}" />
65         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
66             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom out - currently z'+getScale()}" />
67         <mx:TextArea id="dataWorking" text="" right="20" top="3" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="18"
68             enabled="false" borderThickness="0"
69             showEffect="{wipeIn}" hideEffect="{wipeOut}"/>
70
71     </mx:Canvas>
72
73     </mx:HDividedBox>
74
75         <mx:Script><![CDATA[
76                 import net.systemeD.halcyon.*;
77                 import net.systemeD.halcyon.connection.*;
78                 import net.systemeD.potlatch2.*;
79                 import net.systemeD.potlatch2.save.SaveManager;
80                 import net.systemeD.potlatch2.collections.*;
81                 import net.systemeD.potlatch2.controller.*;
82                 import net.systemeD.potlatch2.help.*;
83                 import net.systemeD.potlatch2.options.*;
84                 import net.systemeD.potlatch2.utils.*;
85         import net.systemeD.potlatch2.mygpx.*;
86                 import mx.managers.PopUpManager;
87                 import flash.system.Security;
88                 import flash.net.*;
89                 import flash.events.MouseEvent;
90                 import flash.display.Sprite;
91                 import mx.core.IChildList;
92         import mx.containers.Canvas;
93                 import mx.core.Application;
94         import mx.events.DragEvent;
95         import mx.events.CloseEvent;
96         import mx.managers.DragManager;
97         import mx.core.DragSource;
98         import mx.controls.Alert;
99
100         public var theMap:Map;
101         public var theController:EditController;
102                 public var yahoo:Yahoo;
103                 public var trackLoader:TrackLoader;
104                 public var toolbox:Toolbox;
105         public var bugLoader:BugLoader;
106         public var bikeShopLoader:BikeShopLoader;
107
108                 private var savecount:uint=0;
109                 private var loadcount:uint=0;
110
111         include "version.as";
112
113                 private function initApp():void {
114
115                         Globals.vars.map_area = map_area;
116                         Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
117                         var _root:IChildList = map_area.rawChildren;            // convenient local shorthand
118                         Globals.vars.nocache = loaderInfo.parameters['nocache'] == 'true';
119
120                         // populate sharedObject with loaderInfo parameters if supplied
121                         var obj:SharedObject = SharedObject.getLocal("user_state");
122                         var objChanged:Boolean = false;
123                         if (loaderInfo.parameters['tileurl']) {
124                                 obj.setProperty('background_url',loaderInfo.parameters['tileurl']); 
125                                 obj.setProperty('background_name','Custom'); 
126                                 objChanged=true;
127                         }
128                         if (loaderInfo.parameters['style']) { 
129                                 obj.setProperty('stylesheet_url',loaderInfo.parameters['style']);
130                                 obj.setProperty('stylesheet_name','Custom');
131                                 objChanged=true; 
132                         }
133                         if (objChanged) { obj.flush(); }
134
135                         // map backdrop object
136             var w:uint = map_area.width;
137             var h:uint = map_area.height;
138             var b:Sprite = new Sprite();
139             b.height=h; b.width=w;
140             b.graphics.beginFill(0xFFFFEA,100); 
141             b.graphics.drawRect(0,0,w,h); 
142             b.graphics.endFill();
143                         _root.addChild(b);
144
145                         // pass additional parameters to map
146                         var params:Object={}; var k:String;
147                         for (k in this.loaderInfo.parameters) {
148                                 params[k]=this.loaderInfo.parameters[k];
149                         }
150                         for (k in SharedObject.getLocal('user_state').data) {
151                                 params[k]=SharedObject.getLocal('user_state').data[k];
152                         }
153                         params['tileblocks']=[new RegExp("google","i")];        // hard-coded block on Google tiles
154
155                         // create map and Yahoo
156                         theMap=new Map(params);
157
158             // Auto-load vector backgrounds from config
159             // This could go spectacularly wrong if map.init completes before the event listener below is added
160             theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void { VectorBackgrounds.instance().init(theMap); });
161
162                         theMap.backdrop=b;
163                         yahoo=new Yahoo(w,h,theMap);
164                         yahoo.hide();
165                         _root.addChild(yahoo);
166                         _root.addChild(theMap);
167             theMap.updateSize(w,h);
168                         theMap.addEventListener(MapEvent.SCALE, scaleHandler);
169
170                         // add mask for map
171                         var s:Sprite=new Sprite();
172                         s.graphics.beginFill(0xFFFFFF,100);
173                         s.graphics.drawRect(0,0,w,h);
174                         s.graphics.endFill();
175                         _root.addChild(s);
176                         theMap.mask=s;
177
178                         // add attribution/logo sprite
179                         var overlay:Sprite=new Sprite();
180                         var attribution:TextField=new TextField();
181                         attribution.width=220; attribution.height=300;
182                         attribution.multiline=true;
183                         attribution.wordWrap=true;
184                         attribution.selectable=false;
185                         attribution.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, false);
186                         overlay.addChild(attribution);
187                         var terms:TextField=new TextField();
188                         terms.width=200; terms.height=15;
189                         terms.selectable=false;
190                         terms.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, true);
191                         overlay.addChild(terms);
192                         _root.addChild(overlay);
193
194                         // mouse-up handler attached to stage, so the user can release outside the map
195                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
196                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
197                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
198
199                         // initialise imagery and stylesheets
200                         Imagery.instance().init(theMap, overlay, yahoo);
201                         Stylesheets.instance().init(theMap);
202                         Imagery.instance().addEventListener(MapEvent.BUMP, bumpHandler);
203
204                         // keyboard event attached to stage
205                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
206
207                         // position toolbox
208                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
209                         toolbox.init(theController);
210                         toolbox.x=stage.stageWidth-toolbox.width-5;
211                         toolbox.y=stage.stageHeight-toolbox.height-5;
212
213                         // add debug field
214                         var t:TextField=new TextField();
215                         t.width=500; t.height=150; t.border=true;
216                         t.multiline=true;
217                         _root.addChild(t);
218                         Globals.vars.debug=t;
219             t.visible = loaderInfo.parameters["show_debug"] == 'true';
220                         Globals.vars.root=theMap;       // just for the addDebug function
221
222             theController = new EditController(theMap, tagViewer, toolbox);
223             theController.setActive();
224             
225             var conn:Connection = Connection.getConnectionInstance();
226             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
227             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
228             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
229             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
230             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
231             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
232                         conn.addEventListener(MapEvent.ERROR, onMapError);
233                         conn.addEventListener(MapEvent.ATTENTION, onAttention);
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,"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;
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(mapEvent:MapEvent):void {
305                         var entity:Entity=mapEvent.params.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         public function onResizeMap():void {
335             if ( theMap != null )
336                 theMap.updateSize(map_area.width, map_area.height);
337
338                         if (toolbox) {
339                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-5);
340                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-5);
341                         }
342         }
343                 private function bumpHandler(e:MapEvent):void {
344                         if (toolbox) {
345                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-10-e.params.y);
346                         }
347                 }
348
349         private function onDataStart(event:Event):void {
350                         switch (event.type) {
351                                 case Connection.LOAD_STARTED:   loadcount++; break;
352                                 case Connection.SAVE_STARTED:   savecount++; break;
353                         }
354                         updateDataWorking();
355         }
356         private function onDataComplete(event:Event):void {
357                         switch (event.type) {
358                                 case Connection.LOAD_COMPLETED: loadcount--; break;
359                                 case Connection.SAVE_COMPLETED: savecount--; break;
360                         }
361             updateDataWorking();
362         }
363                 private function updateDataWorking():void {
364                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
365                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
366                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
367                         else                            { dataWorking.text=""; }
368                         dataWorking.visible=(dataWorking.text!="");
369                 }
370         private function onDataDirty(event:Event):void {
371                         saveButton.enabled=true;
372             if (ExternalInterface.available) {
373               ExternalInterface.call("markChanged", false);
374             }
375                 }
376                 private function onDataClean(event:Event):void {
377                         saveButton.enabled=false;
378             if (ExternalInterface.available) {
379               ExternalInterface.call("markChanged", true);
380             }
381                 }
382                 
383
384
385                 private function scaleHandler(event:MapEvent):void {
386                         dispatchEvent(new Event("rescale"));
387                 }
388                 
389                 [Bindable(event="rescale")]
390                 private function getScale():String {
391                         return String(theMap.scale);
392                 }
393
394         private function dragEnterHandler(event:DragEvent):void {
395             // Get the drop target component from the event object.
396             var dropTarget:Canvas=event.currentTarget as Canvas;
397             // Accept the drag only if the user is dragging poi with tags
398             if (event.dragSource.hasFormat('tags')) 
399             {
400                 DragManager.acceptDragDrop(dropTarget);
401             }
402         }
403         
404         private function dragDropHandler(event:DragEvent):void {
405                         // Deselect the dragged icon
406                         if (event.dragSource.dataForFormat('container')) {
407                                 event.dragSource.dataForFormat('container').selectedItem=-1;
408                         }
409
410                         // Get the tags
411             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
412             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
413             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
414             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
415             
416             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
417             
418             var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
419             for each ( var tag:Object in tags ) {
420                 node.setTag(tag.k, tag.v, createAction.push);
421             }
422                         Connection.getConnectionInstance().registerPOI(node);
423                         MainUndoStack.getGlobalStack().addAction(createAction);
424             theController.setState(new SelectedPOINode(node));
425         }
426
427         /* Called when forcing an initial access token check. */
428         private function onAccessChecked():void {
429             // Floaty panel message "You now have access";
430         }
431
432         private function loadTrace(id:Number):void {
433             var conn:Connection = Connection.getConnectionInstance();
434             conn.addEventListener(Connection.TRACES_LOADED, function (e:Event):void {
435                 for each (var trace:Trace in conn.getTraces()) {
436                     if (trace.id == id) { trace.addToMap(); }
437                 }
438             });
439             conn.fetchUserTraces();
440         }
441
442         ]]></mx:Script>
443
444 </mx:Application>
445