First cut at styling TIGER data via an option. Needs lots of propagation of uid 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: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                 
220                 public function onMapError(event:MapEvent):void {
221                         Alert.show(event.params.message, 'Error', mx.controls.Alert.OK);
222                 }
223
224         public function onResizeMap():void {
225             if ( theMap != null )
226                 theMap.updateSize(map_area.width, map_area.height);
227
228                         if (toolbox) {
229                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-15);
230                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-15);
231                         }
232         }
233
234         private function onDataStart(event:Event):void {
235                         switch (event.type) {
236                                 case Connection.LOAD_STARTED:   loadcount++; break;
237                                 case Connection.SAVE_STARTED:   savecount++; break;
238                         }
239                         updateDataWorking();
240         }
241         private function onDataComplete(event:Event):void {
242                         switch (event.type) {
243                                 case Connection.LOAD_COMPLETED: loadcount--; break;
244                                 case Connection.SAVE_COMPLETED: savecount--; break;
245                         }
246             updateDataWorking();
247         }
248                 private function updateDataWorking():void {
249                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
250                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
251                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
252                         else                            { dataWorking.text=""; }
253                         dataWorking.visible=(dataWorking.text!="");
254                 }
255         private function onDataDirty(event:Event):void {
256                         saveButton.enabled=true;
257             if (ExternalInterface.available) {
258               ExternalInterface.call("markChanged", false);
259             }
260                 }
261                 private function onDataClean(event:Event):void {
262                         saveButton.enabled=false;
263             if (ExternalInterface.available) {
264               ExternalInterface.call("markChanged", true);
265             }
266                 }
267                 
268         private function onImageryLoad(event:Event):void {
269                         var xml:XML = new XML(URLLoader(event.target).data);
270                         var saved_url:String = SharedObject.getLocal("user_state").data['background_url'];
271                         var saved_name:String= SharedObject.getLocal("user_state").data['background_name'];
272                         var xml_url:String, xml_name:String, isSet:Boolean=false;
273             theController.imagery=new Array(
274                                 { label: "None", data: "" },
275                                 { label: "Yahoo", data: "yahoo" } );
276                         for each(var set:XML in xml.set) {
277                                 xml_url= set.child("url");
278                                 xml_name=set.child("name");
279                 theController.imagery.push({ label:xml_name, data:xml_url });
280                                 if (xml_url==saved_url || (xml_name==saved_name && xml_name!='Custom')) { isSet=true; }
281                         }
282                         if (!isSet) { theController.imagery.push({ label:saved_name, data:saved_url }); }
283
284                         for each (var bg:Object in theController.imagery) {
285                                 if (bg['label']==saved_nameĀ || bg['data']==saved_url) {
286                                         setBackground(bg['label'], bg['data']);
287                                 }
288                         }
289                 }
290                 
291                 public function setBackground(name:String,url:String):void {
292                         // ** this should take an object with all parameters (source tag, etc.)
293                         if (url=='yahoo') { theMap.setBackground('') ; yahoo.show(); }
294                                      else { theMap.setBackground(url); yahoo.hide(); }
295                         var obj:SharedObject = SharedObject.getLocal("user_state");
296                         obj.setProperty("background_url",url );
297                         obj.setProperty("background_name",name);
298                         obj.flush();
299                 }
300
301                 private function onStylesheetsLoad(event:Event):void {
302                         var xml:XML = new XML(URLLoader(event.target).data);
303                         var saved_url:String = SharedObject.getLocal("user_state").data['stylesheet_url'];
304                         var saved_name:String= SharedObject.getLocal("user_state").data['stylesheet_name'];
305                         var xml_url:String, xml_name:String, isInMenu:Boolean=false, isSet:Boolean=false;
306
307             // first, build the menu from the stylesheet list.
308             // Also ensure the saved_url is in the menu (might be either saved from before, or supplied via loaderInfo)
309             theController.stylesheets=new Array();
310                         for each(var set:XML in xml.stylesheet) {
311                                 xml_url= set.child("url");
312                                 xml_name=set.child("name");
313                 theController.stylesheets.push({ label:xml_name, data:xml_url });
314                                 if (xml_url==saved_url || (xml_name==saved_name && xml_name!='Custom')) { isInMenu=true; }
315                         }
316                         if (saved_url && !isInMenu) { theController.stylesheets.push({ label:saved_name, data:saved_url }); }
317
318             // pick a stylesheet to be set. It should be the saved one, if it is in the menu
319             // or alternatively the first one on the menu,
320             // or finally try 'potlatch.css'
321                         for each (var ss:Object in theController.stylesheets) {
322                                 if (ss['label']==saved_nameĀ || ss['data']==saved_url) {
323                                         setStylesheet(ss['label'], ss['data']);
324                     isSet = true;
325                     break;
326                                 }
327                         }
328             if (!isSet) {
329               if(theController.stylesheets.length > 0) {
330                 var s:Object = theController.stylesheets[0];
331                 setStylesheet(s['label'], s['data']);
332               } else {
333                 //hit and hope. FIXME should this be an error state?
334                 theController.stylesheets.push({ label:'Potlatch', data:'potlatch.css'});
335                 setStylesheet('Potlatch','potlatch.css');
336               }
337             }
338                 }
339
340                 public function setStylesheet(name:String,url:String):void {
341                         theMap.setStyle(url);
342                         var obj:SharedObject = SharedObject.getLocal("user_state");
343                         obj.setProperty("stylesheet_url",url);
344                         obj.setProperty("stylesheet_name",name);
345                         obj.flush();
346                 }
347
348
349         private function dragEnterHandler(event:DragEvent):void {
350             // Get the drop target component from the event object.
351             var dropTarget:Canvas=event.currentTarget as Canvas;
352             // Accept the drag only if the user is dragging poi with tags
353             if (event.dragSource.hasFormat('tags')) 
354             {
355                 DragManager.acceptDragDrop(dropTarget);
356             }
357         }
358         
359         private function dragDropHandler(event:DragEvent):void {
360                         // Deselect the dragged icon
361                         if (event.dragSource.dataForFormat('container')) {
362                                 event.dragSource.dataForFormat('container').selectedItem=-1;
363                         }
364
365                         // Get the tags
366             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
367             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
368             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
369             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
370             
371             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
372             
373             var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
374             for each ( var tag:Object in tags ) {
375                 node.setTag(tag.k, tag.v, createAction.push);
376             }
377                         Connection.getConnectionInstance().registerPOI(node);
378                         MainUndoStack.getGlobalStack().addAction(createAction);
379             theController.setState(new SelectedPOINode(node));
380         }
381
382         /* Called when forcing an initial access token check. */
383         private function onAccessChecked():void {
384             // Floaty panel message "You now have access";
385         }
386
387         ]]></mx:Script>
388
389 </mx:Application>
390