Move the area and tiger stateClass assignment to use EntityUI.setStateClass, and...
[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         
12         <mx:Style source="styles/Application.css"/>
13
14     <mx:Glow id="glowImage" duration="100" 
15         alphaFrom="0.3" alphaTo="1.0" 
16         blurXFrom="0.0" blurXTo="5.0" 
17         blurYFrom="0.0" blurYTo="5.0" 
18         color="0xFF8000"/>
19     <mx:Glow id="unglowImage" duration="100" 
20         alphaFrom="1.0" alphaTo="0.3" 
21         blurXFrom="5.0" blurXTo="0.0" 
22         blurYFrom="5.0" blurYTo="0.0" 
23         color="0xFF8000"/>
24     <mx:WipeLeft id="wipeOut" duration="250"/>
25     <mx:WipeRight id="wipeIn" duration="250"/>
26
27     <mx:ApplicationControlBar dock="true">
28         <mx:PopUpButton id="bgButton" label="Background" openAlways="true"
29             creationComplete="bgButton.popUp = new BackgroundSelector();"/>
30         <mx:PopUpButton id="styleButton" label="Map Style" openAlways="true"
31             creationComplete="styleButton.popUp = new StyleSelector();"/>
32                 <mx:PopUpMenuButton id="gpsButton" itemClick="if (event.index==0) { trackLoader.load(); } else { new MyGpxDialog().init(); }">
33                         <mx:dataProvider>
34                                 <mx:Array>
35                                         <mx:Object label="GPS data" />
36                                         <mx:Object label="My tracks" />
37                                 </mx:Array>
38                         </mx:dataProvider>
39                 </mx:PopUpMenuButton>
40         <mx:Button id="bugsButton" label="Bugs" click="bugLoader.load();" visible="false"/>
41         <mx:Spacer width="100%"/>
42         <mx:Button label="Undo" click="MainUndoStack.getGlobalStack().undo();"
43             enabled="{MainUndoStack.getGlobalStack().canUndo()}"/>
44         <mx:Button label="Redo" click="MainUndoStack.getGlobalStack().redo();"
45             enabled="{MainUndoStack.getGlobalStack().canRedo()}"/>
46         <mx:Spacer width="100%"/>
47         <mx:Button label="Help" click="new HelpDialog().init();" />
48         <mx:Button label="Options" click="new OptionsDialog().init();" /> 
49         <mx:Button label="Save" icon="@Embed('embedded/save.svg')" click="SaveManager.saveChanges();" id="saveButton" 
50                         enabled="false"/>
51     </mx:ApplicationControlBar>
52     
53     <mx:HDividedBox width="100%" height="100%">
54
55           <!-- Tag viewer -->
56           <potlatch2:TagViewer width="25%" height="100%" id="tagViewer"/>
57
58       <mx:Canvas width="75%" height="100%">
59         <mx:Canvas id="map_area" resize="onResizeMap()"
60             top="0" left="0" width="100%" height="100%" dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);">
61         </mx:Canvas>
62         <mx:Image source="@Embed('embedded/zoomIn.svg')" right="3" top="3" click="theMap.zoomIn();"
63             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom in - currently z'+getScale()}" />
64         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
65             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom out - currently z'+getScale()}" />
66         <mx:TextArea id="dataWorking" text="" right="20" top="3" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="18"
67             enabled="false" borderThickness="0"
68             showEffect="{wipeIn}" hideEffect="{wipeOut}"/>
69
70     </mx:Canvas>
71
72     </mx:HDividedBox>
73
74         <mx:Script><![CDATA[
75                 import net.systemeD.halcyon.*;
76                 import net.systemeD.halcyon.connection.*;
77                 import net.systemeD.potlatch2.*;
78                 import net.systemeD.potlatch2.save.SaveManager;
79                 import net.systemeD.potlatch2.controller.*;
80                 import net.systemeD.potlatch2.help.*;
81                 import net.systemeD.potlatch2.options.*;
82                 import net.systemeD.potlatch2.utils.*;
83         import net.systemeD.potlatch2.mygpx.*;
84                 import mx.managers.PopUpManager;
85                 import flash.system.Security;
86                 import flash.net.*;
87                 import flash.events.MouseEvent;
88                 import flash.display.Sprite;
89                 import mx.core.IChildList;
90         import mx.containers.Canvas;
91                 import mx.core.Application;
92         import mx.events.DragEvent;
93         import mx.managers.DragManager;
94         import mx.core.DragSource;
95         import mx.controls.Alert;
96
97         public var theMap:Map;
98         public var theController:EditController;
99                 public var yahoo:Yahoo;
100                 public var trackLoader:TrackLoader;
101                 public var toolbox:Toolbox;
102         public var bugLoader:BugLoader;
103
104                 private var savecount:uint=0;
105                 private var loadcount:uint=0;
106
107         include "version.as";
108
109                 private function initApp():void {
110
111                         Globals.vars.map_area = map_area;
112                         Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
113                         var _root:IChildList = map_area.rawChildren;            // convenient local shorthand
114                         Globals.vars.nocache = loaderInfo.parameters['nocache'] == 'true';
115
116                         // populate sharedObject with loaderInfo parameters if supplied
117                         var obj:SharedObject = SharedObject.getLocal("user_state");
118                         var objChanged:Boolean = false;
119                         if (loaderInfo.parameters['tileurl']) {
120                                 obj.setProperty('background_url',loaderInfo.parameters['tileurl']); 
121                                 obj.setProperty('background_name','Custom'); 
122                                 objChanged=true;
123                         }
124                         if (loaderInfo.parameters['style']) { 
125                                 obj.setProperty('stylesheet_url',loaderInfo.parameters['style']);
126                                 obj.setProperty('stylesheet_name','Custom');
127                                 objChanged=true; 
128                         }
129                         if (objChanged) { obj.flush(); }
130
131                         // load imagery and style XML
132                 var request:DebugURLRequest = new DebugURLRequest("imagery.xml");
133                 var loader:URLLoader = new URLLoader();
134                 loader.addEventListener(Event.COMPLETE, onImageryLoad);
135                 loader.load(request.request);
136
137                         var request2:DebugURLRequest = new DebugURLRequest("stylesheets.xml");
138                         var loader2:URLLoader = new URLLoader();
139                 loader2.addEventListener(Event.COMPLETE, onStylesheetsLoad);
140                 loader2.load(request2.request);
141
142                         // map backdrop object
143             var w:uint = map_area.width;
144             var h:uint = map_area.height;
145             var b:Sprite = new Sprite();
146             b.height=h; b.width=w;
147             b.graphics.beginFill(0xFFFFEA,100); 
148             b.graphics.drawRect(0,0,w,h); 
149             b.graphics.endFill();
150                         _root.addChild(b);
151
152                         // create map and Yahoo
153                         theMap=new Map(this.loaderInfo.parameters);
154                         theMap.backdrop=b;
155                         yahoo=new Yahoo(w,h,theMap);
156                         yahoo.hide();
157                         _root.addChild(yahoo);
158                         _root.addChild(theMap);
159             theMap.updateSize(w,h);
160                         theMap.addEventListener(MapEvent.SCALE, scaleHandler);
161
162                         // add mask for map
163                         var s:Sprite=new Sprite();
164                         s.graphics.beginFill(0xFFFFFF,100);
165                         s.graphics.drawRect(0,0,w,h);
166                         s.graphics.endFill();
167                         _root.addChild(s);
168                         theMap.mask=s;
169
170                         // mouse-up handler attached to stage, so the user can release outside the map
171                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
172                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
173                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
174
175                         // keyboard event attached to stage
176                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
177
178                         // position toolbox
179                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
180                         toolbox.init(theController);
181                         toolbox.x=stage.stageWidth-toolbox.width-15;
182                         toolbox.y=stage.stageHeight-toolbox.height-15;
183
184                         // add debug field
185                         var t:TextField=new TextField();
186                         t.width=500; t.height=150; t.border=true;
187                         t.multiline=true;
188                         _root.addChild(t);
189                         Globals.vars.debug=t;
190             t.visible = loaderInfo.parameters["show_debug"] == 'true';
191                         Globals.vars.root=theMap;       // just for the addDebug function
192
193             theController = new EditController(theMap, tagViewer, toolbox);
194             theController.setActive();
195             
196             var conn:Connection = Connection.getConnectionInstance();
197             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
198             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
199             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
200             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
201             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
202             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
203                         conn.addEventListener(MapEvent.ERROR, onMapError);
204
205             // set the access token from saved cookie
206             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
207             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
208
209                         // create GPS trackloader
210                         trackLoader=new TrackLoader(theMap,conn.apiBase);
211
212             // create Bug loader
213             if (loaderInfo.parameters["bugs_url"] && loaderInfo.parameters["bugs_apikey"]) {
214               bugsButton.visible = true;
215               bugLoader = new BugLoader(theMap, loaderInfo.parameters["bugs_url"], loaderInfo.parameters["bugs_apikey"]);
216             }
217
218             // Force authentication on startup, if required
219             // force_auth == force => checks for access token, and displays OAuth panel if needed
220             var force_auth:String = loaderInfo.parameters["force_auth"];
221             if (!conn.hasAccessToken() && force_auth == 'force') {
222               SaveManager.ensureAccess(onAccessChecked);
223             }
224
225             // show help dialog on startup, if required
226             // show_help == always => on every startup
227             // show_help == once => show on first startup only
228             var show_help:String = loaderInfo.parameters["show_help"];
229
230             if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
231               new HelpDialog().init();
232             }
233
234             // Check if Tiger highlighting should be enabled from saved object
235             Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
236                 }
237                 
238                 public function onMapError(event:MapEvent):void {
239                         Alert.show(event.params.message, 'Error', mx.controls.Alert.OK);
240                 }
241
242         public function onResizeMap():void {
243             if ( theMap != null )
244                 theMap.updateSize(map_area.width, map_area.height);
245
246                         if (toolbox) {
247                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-15);
248                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-15);
249                         }
250         }
251
252         private function onDataStart(event:Event):void {
253                         switch (event.type) {
254                                 case Connection.LOAD_STARTED:   loadcount++; break;
255                                 case Connection.SAVE_STARTED:   savecount++; break;
256                         }
257                         updateDataWorking();
258         }
259         private function onDataComplete(event:Event):void {
260                         switch (event.type) {
261                                 case Connection.LOAD_COMPLETED: loadcount--; break;
262                                 case Connection.SAVE_COMPLETED: savecount--; break;
263                         }
264             updateDataWorking();
265         }
266                 private function updateDataWorking():void {
267                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
268                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
269                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
270                         else                            { dataWorking.text=""; }
271                         dataWorking.visible=(dataWorking.text!="");
272                 }
273         private function onDataDirty(event:Event):void {
274                         saveButton.enabled=true;
275             if (ExternalInterface.available) {
276               ExternalInterface.call("markChanged", false);
277             }
278                 }
279                 private function onDataClean(event:Event):void {
280                         saveButton.enabled=false;
281             if (ExternalInterface.available) {
282               ExternalInterface.call("markChanged", true);
283             }
284                 }
285                 
286         private function onImageryLoad(event:Event):void {
287                         var xml:XML = new XML(URLLoader(event.target).data);
288                         var saved:Object;
289                         if (SharedObject.getLocal("user_state").data['background_url']) {
290                                 saved={ name: SharedObject.getLocal("user_state").data['background_name'],
291                                                 url:  SharedObject.getLocal("user_state").data['background_url' ] };
292                         } else {
293                                 saved={};
294                         }
295
296                         var isSet:Boolean=false;
297             var backgroundSet:Boolean = false;
298
299             theController.imagery=new Array(
300                                 { name: "None", url: "" },
301                                 { name: "Yahoo", url: "yahoo", sourcetag: "Yahoo" } );
302                         for each(var set:XML in xml.set) {
303                                 var obj:Object={};
304                                 for (var a:String in set.children()) {
305                                         obj[set.child(a).name()]=set.child(a);
306                                 }
307                 theController.imagery.push(obj);
308                                 if ((obj.url ==saved.url) ||
309                                     (obj.name==saved.name && obj.name!='Custom')) { isSet=true; }
310                         }
311
312             if (!isSet && saved.name && saved.url && saved.url!='' && saved.url!='yahoo') {
313                 theController.imagery.push(saved);
314                 isSet=true;
315             }
316
317                         for each (var bg:Object in theController.imagery) {
318                                 if (bg.name==saved.name || bg.url==saved.url) {
319                                         setBackground(bg);
320                     backgroundSet = true;
321                                 }
322                         }
323
324             // For most contributors it's useful to set the background to yahoo by default, I reckon, but lets make it a config
325             if (!backgroundSet && loaderInfo.parameters['yahoo_default'] == 'true') {
326                 setBackground(theController.imagery[1]);
327             }
328                 }
329                 
330                 public function setBackground(bg:Object):void {
331                         if (bg.url=='yahoo') { theMap.setBackground(''    ); yahoo.show(); }
332                                         else { theMap.setBackground(bg.url); yahoo.hide(); }
333                         theController.imagerySelected=bg;
334                         var obj:SharedObject = SharedObject.getLocal("user_state");
335                         obj.setProperty('background_url' ,String(bg.url));
336                         obj.setProperty('background_name',String(bg.name));
337                         obj.flush();
338                 }
339
340                 private function onStylesheetsLoad(event:Event):void {
341                         var xml:XML = new XML(URLLoader(event.target).data);
342                         var saved_url:String = SharedObject.getLocal("user_state").data['stylesheet_url'];
343                         var saved_name:String= SharedObject.getLocal("user_state").data['stylesheet_name'];
344                         var isInMenu:Boolean=false, isSet:Boolean=false;
345
346             // first, build the menu from the stylesheet list.
347             // Also ensure the saved_url is in the menu (might be either saved from before, or supplied via loaderInfo)
348             theController.stylesheets=new Array();
349                         for each(var set:XML in xml.stylesheet) {
350                                 var obj:Object={};
351                                 for (var a:String in set.children()) {
352                                         obj[set.child(a).name()]=set.child(a);
353                                 }
354                 theController.stylesheets.push(obj);
355                                 if (obj.url==saved_url || (obj.name==saved_name && obj.name!='Custom')) { isInMenu=true; }
356                         }
357                         if (saved_url && !isInMenu) { theController.stylesheets.push({ name:saved_name, url:saved_url }); }
358
359             // pick a stylesheet to be set. It should be the saved one, if it is in the menu
360             // or alternatively the first one on the menu,
361             // or finally try 'potlatch.css'
362                         for each (var ss:Object in theController.stylesheets) {
363                                 if (ss.name==saved_nameĀ || ss.url==saved_url) {
364                                         setStylesheet(ss.name, ss.url);
365                     isSet = true;
366                     break;
367                                 }
368                         }
369             if (!isSet) {
370               if(theController.stylesheets.length > 0) {
371                 var s:Object = theController.stylesheets[0];
372                 setStylesheet(s.name, s.url);
373               } else {
374                 //hit and hope. FIXME should this be an error state?
375                 theController.stylesheets.push({ name:'Potlatch', url:'potlatch.css'});
376                 setStylesheet('Potlatch','potlatch.css');
377               }
378             }
379                 }
380
381                 public function setStylesheet(name:String,url:String):void {
382                         theMap.setStyle(url);
383                         var obj:SharedObject = SharedObject.getLocal("user_state");
384                         obj.setProperty("stylesheet_url",url);
385                         obj.setProperty("stylesheet_name",name);
386                         obj.flush();
387                 }
388
389                 private function scaleHandler(event:MapEvent):void {
390                         dispatchEvent(new Event("rescale"));
391                 }
392                 
393                 [Bindable(event="rescale")]
394                 private function getScale():String {
395                         return String(theMap.scale);
396                 }
397
398         private function dragEnterHandler(event:DragEvent):void {
399             // Get the drop target component from the event object.
400             var dropTarget:Canvas=event.currentTarget as Canvas;
401             // Accept the drag only if the user is dragging poi with tags
402             if (event.dragSource.hasFormat('tags')) 
403             {
404                 DragManager.acceptDragDrop(dropTarget);
405             }
406         }
407         
408         private function dragDropHandler(event:DragEvent):void {
409                         // Deselect the dragged icon
410                         if (event.dragSource.dataForFormat('container')) {
411                                 event.dragSource.dataForFormat('container').selectedItem=-1;
412                         }
413
414                         // Get the tags
415             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
416             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
417             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
418             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
419             
420             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
421             
422             var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
423             for each ( var tag:Object in tags ) {
424                 node.setTag(tag.k, tag.v, createAction.push);
425             }
426                         Connection.getConnectionInstance().registerPOI(node);
427                         MainUndoStack.getGlobalStack().addAction(createAction);
428             theController.setState(new SelectedPOINode(node));
429         }
430
431         /* Called when forcing an initial access token check. */
432         private function onAccessChecked():void {
433             // Floaty panel message "You now have access";
434         }
435
436         ]]></mx:Script>
437
438 </mx:Application>
439