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