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