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