floating alerts
[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 mask for map
173                         var s:Sprite=new Sprite();
174                         s.graphics.beginFill(0xFFFFFF,100);
175                         s.graphics.drawRect(0,0,w,h);
176                         s.graphics.endFill();
177                         _root.addChild(s);
178                         theMap.mask=s;
179
180                         // add attribution/logo sprite
181                         var overlay:Sprite=new Sprite();
182                         var attribution:TextField=new TextField();
183                         attribution.width=220; attribution.height=300;
184                         attribution.multiline=true;
185                         attribution.wordWrap=true;
186                         attribution.selectable=false;
187                         attribution.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, false);
188                         overlay.addChild(attribution);
189                         var terms:TextField=new TextField();
190                         terms.width=200; terms.height=15;
191                         terms.selectable=false;
192                         terms.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, true);
193                         overlay.addChild(terms);
194                         _root.addChild(overlay);
195
196                         // mouse-up handler attached to stage, so the user can release outside the map
197                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
198                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
199                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
200
201                         // initialise imagery and stylesheets
202                         Imagery.instance().init(theMap, overlay, yahoo);
203                         Stylesheets.instance().init(theMap);
204                         Imagery.instance().addEventListener(MapEvent.BUMP, bumpHandler);
205
206                         // keyboard event attached to stage
207                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
208
209                         // position toolbox
210                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
211                         toolbox.init(theController);
212                         toolbox.x=stage.stageWidth-toolbox.width-5;
213                         toolbox.y=stage.stageHeight-toolbox.height-5;
214
215                         // add debug field
216                         var t:TextField=new TextField();
217                         t.width=500; t.height=150; t.border=true;
218                         t.multiline=true;
219                         _root.addChild(t);
220                         Globals.vars.debug=t;
221             t.visible = loaderInfo.parameters["show_debug"] == 'true';
222                         Globals.vars.root=theMap;       // just for the addDebug function
223
224             theController = new EditController(theMap, tagViewer, toolbox);
225             theController.setActive();
226             
227             var conn:Connection = Connection.getConnectionInstance();
228             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
229             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
230             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
231             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
232             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
233             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
234                         conn.addEventListener(MapEvent.ERROR, onMapError);
235                         conn.addEventListener(AttentionEvent.ATTENTION, onAttention);
236                         conn.addEventListener(AttentionEvent.ALERT, onAlert);
237
238             // set the access token from saved cookie
239             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
240             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
241
242             // Load any requested GPX track
243             if (loaderInfo.parameters['gpx']) {
244                 var id:Number = loaderInfo.parameters['gpx'];
245                 if (conn.hasAccessToken()) { 
246                     loadTrace(id);
247                 } else {
248                     SaveManager.ensureAccess(function ():void { loadTrace(id); });
249                 }
250             }
251
252                         // Load arbitrary GPX from provided URL
253                         if (loaderInfo.parameters['gpx_url']) {
254                                 var vectorlayer:VectorLayer=new VectorLayer(name,theMap,"gpx.css");
255                                 vectorlayer.url=loaderInfo.parameters['gpx_url'];
256                                 var gpx:GpxImporter=new GpxImporter(vectorlayer, vectorlayer.paint, [vectorlayer.url], 
257                                                                     function(success:Boolean,message:String=null):void {
258                                         if (!success) return;
259                                         theMap.addVectorLayer(vectorlayer);
260                                         dispatchEvent(new Event("layers_changed"));
261                                                                     }, false);
262                         }
263
264                         // create GPS trackloader
265                         trackLoader=new TrackLoader(theMap,conn.apiBase);
266
267             // Force authentication on startup, if required
268             // force_auth == force => checks for access token, and displays OAuth panel if needed
269             var force_auth:String = loaderInfo.parameters["force_auth"];
270             if (!conn.hasAccessToken() && force_auth == 'force') {
271               SaveManager.ensureAccess(onAccessChecked);
272             }
273
274             // show help dialog on startup, if required
275             // show_help == always => on every startup
276             // show_help == once => show on first startup only
277             var show_help:String = loaderInfo.parameters["show_help"];
278
279             if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
280               new HelpDialog().init();
281             }
282
283             // Check if Tiger highlighting should be enabled from saved object
284             Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
285                 }
286                 
287                 public function onMapError(mapEvent:MapEvent):void {
288                         var buttons:uint=0;
289                         if (mapEvent.params.no) { trace("no is set"); }
290                         if (mapEvent.params.yes             ) buttons|=mx.controls.Alert.YES;
291                         if (mapEvent.params.no              ) buttons|=mx.controls.Alert.NO;
292                         if (mapEvent.params.cancel          ) buttons|=mx.controls.Alert.CANCEL;
293                         if (mapEvent.params.ok || buttons==0) buttons|=mx.controls.Alert.OK;
294                         trace("showing alert with "+buttons);
295                         Alert.show(mapEvent.params.message, 'Error', buttons, null, function(closeEvent:CloseEvent):void { 
296                                 switch (closeEvent.detail) {
297                                         case mx.controls.Alert.CANCEL:  mapEvent.params.cancel(); break;
298                                         case mx.controls.Alert.YES:             mapEvent.params.yes(); break;
299                                         case mx.controls.Alert.NO:              mapEvent.params.no(); break;
300                                         default:                                                if (mapEvent.params.ok) mapEvent.params.ok();
301                                 }
302                         });
303                 }
304
305                 /** Highlight an entity in response to an 'attention' event */
306
307                 public function onAttention(event:AttentionEvent):void {
308                         var entity:Entity=event.entity;
309                         if (entity is Relation) {
310                                 // If it's a relation, just bring up the editor panel
311                                 var panel:RelationEditorPanel = RelationEditorPanel(
312                                         PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
313                                 panel.setRelation(entity as Relation);
314                                 PopUpManager.centerPopUp(panel);
315                                 return;
316                         }
317
318                         var lat:Number, lon:Number;
319                         var panTo:Boolean=true;
320                         if (entity is Way) {
321                                 // If it's a way, find if it's on-screen
322                                 for (var i:uint=0; i<Way(entity).length; i++) {
323                                         var node:Node=Way(entity).getNode(i)
324                                         if (node.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
325                                         lat=node.lat; lon=node.lon;
326                                 }
327                         } else if (entity is Node) {
328                                 // If it's a node, check if it's on-screen
329                                 if (entity.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
330                                 lat=Node(entity).lat; lon=Node(entity).lon;
331                         }
332                         // Pan if required, and select the object
333                         if (panTo) { theMap.moveMapFromLatLon(lat,lon); }
334                         theController.setState(theController.findStateForSelection([entity]));
335                 }
336
337                 /** Display floating warning in response to an 'alert' event */
338
339                 public function onAlert(event:AttentionEvent):void {
340                         var alert:FloatingAlert=new FloatingAlert(event.message);
341                         stage.addChild(alert);
342                 }
343
344         public function onResizeMap():void {
345             if ( theMap != null )
346                 theMap.updateSize(map_area.width, map_area.height);
347
348                         if (toolbox) {
349                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-5);
350                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-5);
351                         }
352         }
353                 private function bumpHandler(e:MapEvent):void {
354                         if (toolbox) {
355                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-10-e.params.y);
356                         }
357                 }
358
359         private function onDataStart(event:Event):void {
360                         switch (event.type) {
361                                 case Connection.LOAD_STARTED:   loadcount++; break;
362                                 case Connection.SAVE_STARTED:   savecount++; break;
363                         }
364                         updateDataWorking();
365         }
366         private function onDataComplete(event:Event):void {
367                         switch (event.type) {
368                                 case Connection.LOAD_COMPLETED: loadcount--; break;
369                                 case Connection.SAVE_COMPLETED: savecount--; break;
370                         }
371             updateDataWorking();
372         }
373                 private function updateDataWorking():void {
374                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
375                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
376                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
377                         else                            { dataWorking.text=""; }
378                         dataWorking.visible=(dataWorking.text!="");
379                 }
380         private function onDataDirty(event:Event):void {
381                         saveButton.enabled=true;
382             if (ExternalInterface.available) {
383               ExternalInterface.call("markChanged", false);
384             }
385                 }
386                 private function onDataClean(event:Event):void {
387                         saveButton.enabled=false;
388             if (ExternalInterface.available) {
389               ExternalInterface.call("markChanged", true);
390             }
391                 }
392                 
393
394
395                 private function scaleHandler(event:MapEvent):void {
396                         dispatchEvent(new Event("rescale"));
397                 }
398                 
399                 [Bindable(event="rescale")]
400                 private function getScale():String {
401                         return String(theMap.scale);
402                 }
403
404         private function dragEnterHandler(event:DragEvent):void {
405             // Get the drop target component from the event object.
406             var dropTarget:Canvas=event.currentTarget as Canvas;
407             // Accept the drag only if the user is dragging poi with tags
408             if (event.dragSource.hasFormat('tags')) 
409             {
410                 DragManager.acceptDragDrop(dropTarget);
411             }
412         }
413         
414         private function dragDropHandler(event:DragEvent):void {
415                         // Deselect the dragged icon
416                         if (event.dragSource.dataForFormat('container')) {
417                                 event.dragSource.dataForFormat('container').selectedItem=-1;
418                         }
419
420                         // Get the tags
421             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
422             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
423             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
424             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
425             
426             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
427             
428             var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
429             for each ( var tag:Object in tags ) {
430                 node.setTag(tag.k, tag.v, createAction.push);
431             }
432                         Connection.getConnectionInstance().registerPOI(node);
433                         MainUndoStack.getGlobalStack().addAction(createAction);
434             theController.setState(new SelectedPOINode(node));
435         }
436
437         /* Called when forcing an initial access token check. */
438         private function onAccessChecked():void {
439             // Floaty panel message "You now have access";
440         }
441
442         private function loadTrace(id:Number):void {
443             var conn:Connection = Connection.getConnectionInstance();
444             conn.addEventListener(Connection.TRACES_LOADED, function (e:Event):void {
445                 for each (var trace:Trace in conn.getTraces()) {
446                     if (trace.id == id) { trace.addToMap(); }
447                 }
448             });
449             conn.fetchUserTraces();
450         }
451
452         ]]></mx:Script>
453
454 </mx:Application>
455