32d5fe308af37d79c7aab5ea24b5b91a768d83c2
[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" toolTip="{'Zoom in - currently z'+getScale()}" />
63         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
64             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom out - currently z'+getScale()}" />
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         public var bugLoader:BugLoader;
102         public var bikeShopLoader:BikeShopLoader;
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
155             // Auto-load vector backgrounds from config
156             // This could go spectacularly wrong if map.init completes before the event listener below is added
157             var vectorloader:AutoVectorBackground = new AutoVectorBackground(theMap);
158             theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void {vectorloader.load();});
159
160                         theMap.backdrop=b;
161                         yahoo=new Yahoo(w,h,theMap);
162                         yahoo.hide();
163                         _root.addChild(yahoo);
164                         _root.addChild(theMap);
165             theMap.updateSize(w,h);
166                         theMap.addEventListener(MapEvent.SCALE, scaleHandler);
167
168                         // add mask for map
169                         var s:Sprite=new Sprite();
170                         s.graphics.beginFill(0xFFFFFF,100);
171                         s.graphics.drawRect(0,0,w,h);
172                         s.graphics.endFill();
173                         _root.addChild(s);
174                         theMap.mask=s;
175
176                         // mouse-up handler attached to stage, so the user can release outside the map
177                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
178                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
179                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
180
181                         // keyboard event attached to stage
182                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
183
184                         // position toolbox
185                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
186                         toolbox.init(theController);
187                         toolbox.x=stage.stageWidth-toolbox.width-15;
188                         toolbox.y=stage.stageHeight-toolbox.height-15;
189
190                         // add debug field
191                         var t:TextField=new TextField();
192                         t.width=500; t.height=150; t.border=true;
193                         t.multiline=true;
194                         _root.addChild(t);
195                         Globals.vars.debug=t;
196             t.visible = loaderInfo.parameters["show_debug"] == 'true';
197                         Globals.vars.root=theMap;       // just for the addDebug function
198
199             theController = new EditController(theMap, tagViewer, toolbox);
200             theController.setActive();
201             
202             var conn:Connection = Connection.getConnectionInstance();
203             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
204             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
205             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
206             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
207             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
208             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
209                         conn.addEventListener(MapEvent.ERROR, onMapError);
210
211             // set the access token from saved cookie
212             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
213             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
214
215                         // create GPS trackloader
216                         trackLoader=new TrackLoader(theMap,conn.apiBase);
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={ url: ''};
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                                 var a:XML;
305                                 for each (a in set.@*) { obj[a.name().localName]=a.toString(); }
306                                 for each (a in set.* ) { obj[a.name()          ]=a.toString(); }
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({url:''}); yahoo.show(); }
332                                         else { theMap.setBackground(bg      ); 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                 public function getAvailableImagery():Array {
341                         var available:Array=[];
342                         for each (var bg:Object in theController.imagery) {
343                                 if (bg.minlon) {
344                                         // if there's a bbox, check the current viewport intersects it
345                                         if (((theMap.edge_l>bg.minlon && theMap.edge_l<bg.maxlon) ||
346                                              (theMap.edge_r>bg.minlon && theMap.edge_r<bg.maxlon) ||
347                                              (theMap.edge_l<bg.minlon && theMap.edge_r>bg.maxlon)) &&
348                                             ((theMap.edge_b>bg.minlat && theMap.edge_b<bg.maxlat) ||
349                                              (theMap.edge_t>bg.minlat && theMap.edge_t<bg.maxlat) ||
350                                              (theMap.edge_b<bg.minlat && theMap.edge_t>bg.maxlat))) {
351                                                 available.push(bg);
352                                         }
353                                 } else {
354                                         // if there's no bbox (i.e. global set), include it anyway
355                                         available.push(bg);
356                                 }
357                         }
358                         return available;
359                 }
360
361                 private function onStylesheetsLoad(event:Event):void {
362                         var xml:XML = new XML(URLLoader(event.target).data);
363                         var saved_url:String = SharedObject.getLocal("user_state").data['stylesheet_url'];
364                         var saved_name:String= SharedObject.getLocal("user_state").data['stylesheet_name'];
365                         var isInMenu:Boolean=false, isSet:Boolean=false;
366
367             // first, build the menu from the stylesheet list.
368             // Also ensure the saved_url is in the menu (might be either saved from before, or supplied via loaderInfo)
369             theController.stylesheets=new Array();
370                         for each(var set:XML in xml.stylesheet) {
371                                 var obj:Object={};
372                                 for (var a:String in set.children()) {
373                                         obj[set.child(a).name()]=set.child(a);
374                                 }
375                 theController.stylesheets.push(obj);
376                                 if (obj.url==saved_url || (obj.name==saved_name && obj.name!='Custom')) { isInMenu=true; }
377                         }
378                         if (saved_url && !isInMenu) { theController.stylesheets.push({ name:saved_name, url:saved_url }); }
379
380             // pick a stylesheet to be set. It should be the saved one, if it is in the menu
381             // or alternatively the first one on the menu,
382             // or finally try 'potlatch.css'
383                         for each (var ss:Object in theController.stylesheets) {
384                                 if (ss.name==saved_nameĀ || ss.url==saved_url) {
385                                         setStylesheet(ss.name, ss.url);
386                     isSet = true;
387                     break;
388                                 }
389                         }
390             if (!isSet) {
391               if(theController.stylesheets.length > 0) {
392                 var s:Object = theController.stylesheets[0];
393                 setStylesheet(s.name, s.url);
394               } else {
395                 //hit and hope. FIXME should this be an error state?
396                 theController.stylesheets.push({ name:'Potlatch', url:'potlatch.css'});
397                 setStylesheet('Potlatch','potlatch.css');
398               }
399             }
400                 }
401
402                 public function setStylesheet(name:String,url:String):void {
403                         theMap.setStyle(url);
404                         var obj:SharedObject = SharedObject.getLocal("user_state");
405                         obj.setProperty("stylesheet_url",url);
406                         obj.setProperty("stylesheet_name",name);
407                         obj.flush();
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         ]]></mx:Script>
458
459 </mx:Application>
460