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