First stab at displaying bugs
[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 label="Bugs" click="bugLoader.load();" />
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             bugLoader = new BugLoader(theMap,'', 'fooKey456789');
214
215             // Force authentication on startup, if required
216             // force_auth == force => checks for access token, and displays OAuth panel if needed
217             var force_auth:String = loaderInfo.parameters["force_auth"];
218             if (!conn.hasAccessToken() && force_auth == 'force') {
219               SaveManager.ensureAccess(onAccessChecked);
220             }
221
222             // show help dialog on startup, if required
223             // show_help == always => on every startup
224             // show_help == once => show on first startup only
225             var show_help:String = loaderInfo.parameters["show_help"];
226
227             if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
228               new HelpDialog().init();
229             }
230
231             // Check if Tiger highlighting should be enabled from saved object
232             Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
233                 }
234                 
235                 public function onMapError(event:MapEvent):void {
236                         Alert.show(event.params.message, 'Error', mx.controls.Alert.OK);
237                 }
238
239         public function onResizeMap():void {
240             if ( theMap != null )
241                 theMap.updateSize(map_area.width, map_area.height);
242
243                         if (toolbox) {
244                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-15);
245                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-15);
246                         }
247         }
248
249         private function onDataStart(event:Event):void {
250                         switch (event.type) {
251                                 case Connection.LOAD_STARTED:   loadcount++; break;
252                                 case Connection.SAVE_STARTED:   savecount++; break;
253                         }
254                         updateDataWorking();
255         }
256         private function onDataComplete(event:Event):void {
257                         switch (event.type) {
258                                 case Connection.LOAD_COMPLETED: loadcount--; break;
259                                 case Connection.SAVE_COMPLETED: savecount--; break;
260                         }
261             updateDataWorking();
262         }
263                 private function updateDataWorking():void {
264                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
265                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
266                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
267                         else                            { dataWorking.text=""; }
268                         dataWorking.visible=(dataWorking.text!="");
269                 }
270         private function onDataDirty(event:Event):void {
271                         saveButton.enabled=true;
272             if (ExternalInterface.available) {
273               ExternalInterface.call("markChanged", false);
274             }
275                 }
276                 private function onDataClean(event:Event):void {
277                         saveButton.enabled=false;
278             if (ExternalInterface.available) {
279               ExternalInterface.call("markChanged", true);
280             }
281                 }
282                 
283         private function onImageryLoad(event:Event):void {
284                         var xml:XML = new XML(URLLoader(event.target).data);
285                         var saved:Object;
286                         if (SharedObject.getLocal("user_state").data['background_url']) {
287                                 saved={ name: SharedObject.getLocal("user_state").data['background_name'],
288                                                 url:  SharedObject.getLocal("user_state").data['background_url' ] };
289                         } else {
290                                 saved={};
291                         }
292
293                         var isSet:Boolean=false;
294             var backgroundSet:Boolean = false;
295
296             theController.imagery=new Array(
297                                 { name: "None", url: "" },
298                                 { name: "Yahoo", url: "yahoo", sourcetag: "Yahoo" } );
299                         for each(var set:XML in xml.set) {
300                                 var obj:Object={};
301                                 for (var a:String in set.children()) {
302                                         obj[set.child(a).name()]=set.child(a);
303                                 }
304                 theController.imagery.push(obj);
305                                 if ((obj.url ==saved.url) ||
306                                     (obj.name==saved.name && obj.name!='Custom')) { isSet=true; }
307                         }
308
309             if (!isSet && saved.name && saved.url && saved.url!='' && saved.url!='yahoo') {
310                 theController.imagery.push(saved);
311                 isSet=true;
312             }
313
314                         for each (var bg:Object in theController.imagery) {
315                                 if (bg.name==saved.name || bg.url==saved.url) {
316                                         setBackground(bg);
317                     backgroundSet = true;
318                                 }
319                         }
320
321             // For most contributors it's useful to set the background to yahoo by default, I reckon, but lets make it a config
322             if (!backgroundSet && loaderInfo.parameters['yahoo_default'] == 'true') {
323                 setBackground(theController.imagery[1]);
324             }
325                 }
326                 
327                 public function setBackground(bg:Object):void {
328                         if (bg.url=='yahoo') { theMap.setBackground(''    ); yahoo.show(); }
329                                         else { theMap.setBackground(bg.url); yahoo.hide(); }
330                         theController.imagerySelected=bg;
331                         var obj:SharedObject = SharedObject.getLocal("user_state");
332                         obj.setProperty('background_url' ,String(bg.url));
333                         obj.setProperty('background_name',String(bg.name));
334                         obj.flush();
335                 }
336
337                 private function onStylesheetsLoad(event:Event):void {
338                         var xml:XML = new XML(URLLoader(event.target).data);
339                         var saved_url:String = SharedObject.getLocal("user_state").data['stylesheet_url'];
340                         var saved_name:String= SharedObject.getLocal("user_state").data['stylesheet_name'];
341                         var isInMenu:Boolean=false, isSet:Boolean=false;
342
343             // first, build the menu from the stylesheet list.
344             // Also ensure the saved_url is in the menu (might be either saved from before, or supplied via loaderInfo)
345             theController.stylesheets=new Array();
346                         for each(var set:XML in xml.stylesheet) {
347                                 var obj:Object={};
348                                 for (var a:String in set.children()) {
349                                         obj[set.child(a).name()]=set.child(a);
350                                 }
351                 theController.stylesheets.push(obj);
352                                 if (obj.url==saved_url || (obj.name==saved_name && obj.name!='Custom')) { isInMenu=true; }
353                         }
354                         if (saved_url && !isInMenu) { theController.stylesheets.push({ name:saved_name, url:saved_url }); }
355
356             // pick a stylesheet to be set. It should be the saved one, if it is in the menu
357             // or alternatively the first one on the menu,
358             // or finally try 'potlatch.css'
359                         for each (var ss:Object in theController.stylesheets) {
360                                 if (ss.name==saved_nameĀ || ss.url==saved_url) {
361                                         setStylesheet(ss.name, ss.url);
362                     isSet = true;
363                     break;
364                                 }
365                         }
366             if (!isSet) {
367               if(theController.stylesheets.length > 0) {
368                 var s:Object = theController.stylesheets[0];
369                 setStylesheet(s.name, s.url);
370               } else {
371                 //hit and hope. FIXME should this be an error state?
372                 theController.stylesheets.push({ name:'Potlatch', url:'potlatch.css'});
373                 setStylesheet('Potlatch','potlatch.css');
374               }
375             }
376                 }
377
378                 public function setStylesheet(name:String,url:String):void {
379                         theMap.setStyle(url);
380                         var obj:SharedObject = SharedObject.getLocal("user_state");
381                         obj.setProperty("stylesheet_url",url);
382                         obj.setProperty("stylesheet_name",name);
383                         obj.flush();
384                 }
385
386                 private function scaleHandler(event:MapEvent):void {
387                         dispatchEvent(new Event("rescale"));
388                 }
389                 
390                 [Bindable(event="rescale")]
391                 private function getScale():String {
392                         return String(theMap.scale);
393                 }
394
395         private function dragEnterHandler(event:DragEvent):void {
396             // Get the drop target component from the event object.
397             var dropTarget:Canvas=event.currentTarget as Canvas;
398             // Accept the drag only if the user is dragging poi with tags
399             if (event.dragSource.hasFormat('tags')) 
400             {
401                 DragManager.acceptDragDrop(dropTarget);
402             }
403         }
404         
405         private function dragDropHandler(event:DragEvent):void {
406                         // Deselect the dragged icon
407                         if (event.dragSource.dataForFormat('container')) {
408                                 event.dragSource.dataForFormat('container').selectedItem=-1;
409                         }
410
411                         // Get the tags
412             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
413             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
414             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
415             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
416             
417             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
418             
419             var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
420             for each ( var tag:Object in tags ) {
421                 node.setTag(tag.k, tag.v, createAction.push);
422             }
423                         Connection.getConnectionInstance().registerPOI(node);
424                         MainUndoStack.getGlobalStack().addAction(createAction);
425             theController.setState(new SelectedPOINode(node));
426         }
427
428         /* Called when forcing an initial access token check. */
429         private function onAccessChecked():void {
430             // Floaty panel message "You now have access";
431         }
432
433         ]]></mx:Script>
434
435 </mx:Application>
436