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