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