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