Recalculate lengths when extending / shortening ways - allows names to update position
[potlatch2.git] / potlatch2.mxml
index ca19e63de613aaef7310cf13c7cb40e78dd0ef04..6ca393578ccf9e5f44b3ff4f703d84d7aa71b362 100755 (executable)
@@ -4,6 +4,8 @@
        xmlns:halcyon="net.systemeD.halcyon.*"
        xmlns:potlatch2="net.systemeD.potlatch2.*"
        layout="vertical"
+       horizontalScrollPolicy="off"
+       verticalScrollPolicy="off"
        horizontalAlign="center" 
        addedToStage="initApp()">
        
     <mx:WipeRight id="wipeIn" duration="250"/>
 
     <mx:ApplicationControlBar dock="true">
+        <mx:PopUpButton id="bgButton" label="Background" openAlways="true"
+            creationComplete="bgButton.popUp = new BackgroundSelector();"/>
+        <mx:PopUpButton id="styleButton" label="Map Style" openAlways="true"
+            creationComplete="styleButton.popUp = new StyleSelector();"/>
+        <mx:Button label="GPS" click="trackLoader.load();"/>
         <mx:Spacer width="100%"/>
-        <mx:Button label="Save" icon="@Embed('embedded/save.svg')" click="SaveManager.saveChanges();"/>
+        <mx:Button label="Undo" click="MainUndoStack.getGlobalStack().undo();"
+            enabled="{MainUndoStack.getGlobalStack().canUndo()}"/>
+        <mx:Button label="Redo" click="MainUndoStack.getGlobalStack().redo();"
+            enabled="{MainUndoStack.getGlobalStack().canRedo()}"/>
+        <mx:Spacer width="100%"/>
+        <mx:Button label="Help" click="new HelpDialog().init();" />
+        <mx:Button label="Options" click="new OptionsDialog().init();" /> 
+        <mx:Button label="Save" icon="@Embed('embedded/save.svg')" click="SaveManager.saveChanges();" id="saveButton" 
+                       enabled="false"/>
     </mx:ApplicationControlBar>
     
     <mx:HDividedBox width="100%" height="100%">
 
-      <mx:VBox height="100%" width="25%" horizontalAlign="right">
-        <potlatch2:TagViewer width="100%" height="100%" id="tagViewer"/>
-      </mx:VBox>
+         <!-- Tag viewer -->
+         <potlatch2:TagViewer width="25%" height="100%" id="tagViewer"/>
+
       <mx:Canvas width="75%" height="100%">
         <mx:Canvas id="map_area" resize="onResizeMap()"
-            top="0" left="0" width="100%" height="100%">
+            top="0" left="0" width="100%" height="100%" dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);">
         </mx:Canvas>
         <mx:Image source="@Embed('embedded/zoomIn.svg')" right="3" top="3" click="theMap.zoomIn();"
             rollOverEffect="glowImage" rollOutEffect="unglowImage"/>
         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
             rollOverEffect="glowImage" rollOutEffect="unglowImage"/>
-        <mx:Label id="dataWorking" text="" right="20" top="3"
+        <mx:TextArea id="dataWorking" text="" right="20" top="3" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="18"
+            enabled="false" borderThickness="0"
             showEffect="{wipeIn}" hideEffect="{wipeOut}"/>
-      </mx:Canvas>
+
+    </mx:Canvas>
+
     </mx:HDividedBox>
 
        <mx:Script><![CDATA[
                import net.systemeD.halcyon.connection.*;
                import net.systemeD.potlatch2.*;
                import net.systemeD.potlatch2.save.SaveManager;
+               import net.systemeD.potlatch2.controller.*;
+               import net.systemeD.potlatch2.help.*;
+               import net.systemeD.potlatch2.options.*;
+               import net.systemeD.potlatch2.utils.*;
+               import mx.managers.PopUpManager;
                import flash.system.Security;
                import flash.net.*;
                import flash.events.MouseEvent;
                import mx.core.IChildList;
         import mx.containers.Canvas;
                import mx.core.Application;
+        import mx.events.DragEvent;
+        import mx.managers.DragManager;
+        import mx.core.DragSource;
+        import mx.controls.Alert;
 
         public var theMap:Map;
+        public var theController:EditController;
+               public var yahoo:Yahoo;
+               public var trackLoader:TrackLoader;
+               public var toolbox:Toolbox;
+
+               private var savecount:uint=0;
+               private var loadcount:uint=0;
+               
+               public var version:String="(Foxbase) Alpha";                    // mxml won't read it if it's a const. Go figure
 
                private function initApp():void {
 
-                       Globals.vars.map_area=map_area;
-                       Globals.vars.root=map_area.rawChildren;                 // set up global reference to root level
-                       var _root:IChildList=map_area.rawChildren;              // convenient local shorthand
+                       Globals.vars.map_area = map_area;
+                       Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
+                       var _root:IChildList = map_area.rawChildren;            // convenient local shorthand
+                       Globals.vars.nocache = loaderInfo.parameters['nocache'] == 'true';
+
+                       // populate sharedObject with loaderInfo parameters if supplied
+                       var obj:SharedObject = SharedObject.getLocal("user_state");
+                       var objChanged:Boolean = false;
+                       if (loaderInfo.parameters['tileurl']) {
+                               obj.setProperty('background_url',loaderInfo.parameters['tileurl']); 
+                               obj.setProperty('background_name','Custom'); 
+                               objChanged=true;
+                       }
+                       if (loaderInfo.parameters['style']) { 
+                               obj.setProperty('stylesheet_url',loaderInfo.parameters['style']);
+                               obj.setProperty('stylesheet_name','Custom');
+                               objChanged=true; 
+                       }
+                       if (objChanged) { obj.flush(); }
+
+                       // load imagery and style XML
+               var request:DebugURLRequest = new DebugURLRequest("imagery.xml");
+               var loader:URLLoader = new URLLoader();
+               loader.addEventListener(Event.COMPLETE, onImageryLoad);
+               loader.load(request.request);
+
+                       var request2:DebugURLRequest = new DebugURLRequest("stylesheets.xml");
+                       var loader2:URLLoader = new URLLoader();
+               loader2.addEventListener(Event.COMPLETE, onStylesheetsLoad);
+               loader2.load(request2.request);
 
                        // map backdrop object
             var w:uint = map_area.width;
             b.graphics.endFill();
                        _root.addChild(b);
 
-                       // add map
+                       // create map and Yahoo
                        theMap=new Map(this.loaderInfo.parameters);
                        theMap.backdrop=b;
+                       yahoo=new Yahoo(w,h,theMap);
+                       yahoo.hide();
+                       _root.addChild(yahoo);
                        _root.addChild(theMap);
-            theMap.updateSize(w, h);
+            theMap.updateSize(w,h);
 
                        // add mask for map
                        var s:Sprite=new Sprite();
                        _root.addChild(s);
                        theMap.mask=s;
 
-                       // add crosshair
-                       /*s=new Sprite();
-                       s.graphics.lineStyle(2,0);
-                       s.graphics.moveTo(stage.stageWidth/2-20,stage.stageHeight/2);
-                       s.graphics.lineTo(stage.stageWidth/2+20,stage.stageHeight/2);
-                       s.graphics.moveTo(stage.stageWidth/2,stage.stageHeight/2-20);
-                       s.graphics.lineTo(stage.stageWidth/2,stage.stageHeight/2+20);
-                       _root.addChild(s);*/
-
                        // mouse-up handler attached to stage, so the user can release outside the map
                        stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
                        Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
                        // keyboard event attached to stage
                        stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
 
-                       // example listener event
-                       var myListenerObj:Object = new Object();
-                       myListenerObj.mapHandler=function(event:MapEvent):void {
-                               Globals.vars.debug.appendText("Download event fired - "+event.minlat+","+event.minlon+"\n");
-                       };
-                       theMap.addEventListener(MapEvent.DOWNLOAD, myListenerObj.mapHandler);
+                       // position toolbox
+                       toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
+                       toolbox.init(theController);
+                       toolbox.x=stage.stageWidth-toolbox.width-15;
+                       toolbox.y=stage.stageHeight-toolbox.height-15;
 
                        // add debug field
                        var t:TextField=new TextField();
-                       t.width=400; t.height=100; t.border=true;
+                       t.width=500; t.height=150; t.border=true;
                        t.multiline=true;
                        _root.addChild(t);
                        Globals.vars.debug=t;
             t.visible = loaderInfo.parameters["show_debug"] == 'true';
                        Globals.vars.root=theMap;       // just for the addDebug function
 
-            var controller:EditController = new EditController(theMap, tagViewer);
-            controller.setActive();
+            theController = new EditController(theMap, tagViewer, toolbox);
+            theController.setActive();
             
             var conn:Connection = Connection.getConnectionInstance();
             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
+            conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
+            conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
+            conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
+            conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
+                       conn.addEventListener(MapEvent.ERROR, onMapError);
+
+                       // create GPS trackloader
+                       trackLoader=new TrackLoader(theMap,conn.apiBase);
+               }
+               
+               public function onMapError(event:MapEvent):void {
+                       Alert.show(event.params.message, 'Error', mx.controls.Alert.OK);
                }
 
         public function onResizeMap():void {
             if ( theMap != null )
                 theMap.updateSize(map_area.width, map_area.height);
+
+                       if (toolbox) {
+                               toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-15);
+                               toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-15);
+                       }
         }
 
         private function onDataStart(event:Event):void {
-            dataWorking.text = event.type == Connection.LOAD_STARTED ? "Loading data..." : "Saving Data...";
-            dataWorking.visible = true;
+                       switch (event.type) {
+                               case Connection.LOAD_STARTED:   loadcount++; break;
+                               case Connection.SAVE_STARTED:   savecount++; break;
+                       }
+                       updateDataWorking();
         }
         private function onDataComplete(event:Event):void {
-            dataWorking.visible = false;
+                       switch (event.type) {
+                               case Connection.LOAD_COMPLETED: loadcount--; break;
+                               case Connection.SAVE_COMPLETED: savecount--; break;
+                       }
+            updateDataWorking();
+        }
+               private function updateDataWorking():void {
+                       if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
+                       else if (loadcount>0)           { dataWorking.text="Loading data..."; }
+                       else if (savecount>0)           { dataWorking.text="Saving data..."; }
+                       else                            { dataWorking.text=""; }
+                       dataWorking.visible=(dataWorking.text!="");
+               }
+        private function onDataDirty(event:Event):void {
+                       saveButton.enabled=true;
+               }
+               private function onDataClean(event:Event):void {
+                       saveButton.enabled=false;
+               }
+               
+        private function onImageryLoad(event:Event):void {
+                       var xml:XML = new XML(URLLoader(event.target).data);
+                       var saved_url:String = SharedObject.getLocal("user_state").data['background_url'];
+                       var saved_name:String= SharedObject.getLocal("user_state").data['background_name'];
+                       var xml_url:String, xml_name:String, isSet:Boolean=false;
+            theController.imagery=new Array(
+                               { label: "None", data: "" },
+                               { label: "Yahoo", data: "yahoo" } );
+                       for each(var set:XML in xml.set) {
+                               xml_url= set.child("url");
+                               xml_name=set.child("name");
+                theController.imagery.push({ label:xml_name, data:xml_url });
+                               if (xml_url==saved_url || (xml_name==saved_name && xml_name!='Custom')) { isSet=true; }
+                       }
+                       if (!isSet) { theController.imagery.push({ label:saved_name, data:saved_url }); }
+
+                       for each (var bg:Object in theController.imagery) {
+                               if (bg['label']==saved_nameĀ || bg['data']==saved_url) {
+                                       setBackground(bg['label'], bg['data']);
+                               }
+                       }
+               }
+               
+               public function setBackground(name:String,url:String):void {
+                       // ** this should take an object with all parameters (source tag, etc.)
+                       if (url=='yahoo') { theMap.setBackground('') ; yahoo.show(); }
+                                    else { theMap.setBackground(url); yahoo.hide(); }
+                       var obj:SharedObject = SharedObject.getLocal("user_state");
+                       obj.setProperty("background_url",url );
+                       obj.setProperty("background_name",name);
+                       obj.flush();
+               }
+
+               private function onStylesheetsLoad(event:Event):void {
+                       var xml:XML = new XML(URLLoader(event.target).data);
+                       var saved_url:String = SharedObject.getLocal("user_state").data['stylesheet_url'];
+                       var saved_name:String= SharedObject.getLocal("user_state").data['stylesheet_name'];
+                       var xml_url:String, xml_name:String, isInMenu:Boolean=false, isSet:Boolean=false;
+
+            // first, build the menu from the stylesheet list.
+            // Also ensure the saved_url is in the menu (might be either saved from before, or supplied via loaderInfo)
+            theController.stylesheets=new Array();
+                       for each(var set:XML in xml.stylesheet) {
+                               xml_url= set.child("url");
+                               xml_name=set.child("name");
+                theController.stylesheets.push({ label:xml_name, data:xml_url });
+                               if (xml_url==saved_url || (xml_name==saved_name && xml_name!='Custom')) { isInMenu=true; }
+                       }
+                       if (saved_url && !isInMenu) { theController.stylesheets.push({ label:saved_name, data:saved_url }); }
+
+            // pick a stylesheet to be set. It should be the saved one, if it is in the menu
+            // or alternatively the first one on the menu,
+            // or finally try 'potlatch.css'
+                       for each (var ss:Object in theController.stylesheets) {
+                               if (ss['label']==saved_nameĀ || ss['data']==saved_url) {
+                                       setStylesheet(ss['label'], ss['data']);
+                    isSet = true;
+                    break;
+                               }
+                       }
+            if (!isSet) {
+              if(theController.stylesheets.length > 0) {
+                var s:Object = theController.stylesheets[0];
+                setStylesheet(s['label'], s['data']);
+              } else {
+                //hit and hope. FIXME should this be an error state?
+                theController.stylesheets.push({ label:'Potlatch', data:'potlatch.css'});
+                setStylesheet('Potlatch','potlatch.css');
+              }
+            }
+               }
+
+               public function setStylesheet(name:String,url:String):void {
+                       theMap.setStyle(url);
+                       var obj:SharedObject = SharedObject.getLocal("user_state");
+                       obj.setProperty("stylesheet_url",url);
+                       obj.setProperty("stylesheet_name",name);
+                       obj.flush();
+               }
+
+
+        private function dragEnterHandler(event:DragEvent):void {
+            // Get the drop target component from the event object.
+            var dropTarget:Canvas=event.currentTarget as Canvas;
+            // Accept the drag only if the user is dragging poi with tags
+            if (event.dragSource.hasFormat('tags')) 
+            {
+                DragManager.acceptDragDrop(dropTarget);
+            }
+        }
+        
+        private function dragDropHandler(event:DragEvent):void {
+                       // Deselect the dragged icon
+                       if (event.dragSource.dataForFormat('container')) {
+                               event.dragSource.dataForFormat('container').selectedItem=-1;
+                       }
+
+                       // Get the tags
+            var tags:Array = event.dragSource.dataForFormat('tags') as Array;
+            var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.stageX, event.stageY));
+            var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
+            var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
+            
+            var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
+            
+            var node:Node = Connection.getConnectionInstance().createNode({}, lat, lon, createAction.push);
+            for each ( var tag:Object in tags ) {
+                node.setTag(tag.k, tag.v, createAction.push);
+            }
+                       Connection.getConnectionInstance().registerPOI(node);
+                       MainUndoStack.getGlobalStack().addAction(createAction);
+            theController.setState(new SelectedPOINode(node));
         }
+
        ]]></mx:Script>
 
 </mx:Application>