Refactoring in progress
[potlatch2.git] / potlatch2.mxml
index aeaa71d..94f364c 100644 (file)
@@ -7,9 +7,11 @@
        horizontalScrollPolicy="off"
        verticalScrollPolicy="off"
        horizontalAlign="center" 
-       addedToStage="initApp()"
+       addedToStage="startInit()"
        preloader="net.systemeD.potlatch2.Preloader">
-       
+
+    <map:LocalizationMap xmlns:map="l10n.map.*" />
+
        <mx:Style source="styles/Application.css"/>
 
     <mx:Glow id="glowImage" duration="100" 
         <mx:PopUpButton id="styleButton" label="Map Style" openAlways="true" styleName="appBarButton"
             creationComplete="styleButton.popUp = new StyleSelector();"/>
                <mx:PopUpMenuButton id="gpsButton" styleName="appBarButton"
-                   itemClick="if (event.index==0) { trackLoader.load(); } else { new MyGpxDialog().init(); }">
+                   itemClick="if (event.index==0) { trackLoader.load(); } 
+                         else if (event.index==1) { new MyGpxDialog().init(); } 
+                                             else { mx.controls.Menu(gpsButton.popUp).selectedIndex=0; 
+                                                    mx.controls.Menu(gpsButton.popUp).selectedIndex=0; /* Yes, we do need to call it twice */
+                                                    theMap.removeVectorLayer(theMap.findVectorLayer('GPS tracks')); }">
                        <mx:dataProvider>
                                <mx:Array>
-                                       <mx:Object label="GPS data" />
-                                       <mx:Object label="My tracks" />
+                                       <mx:Object label="GPS data" id="gpsData" />
+                                       <mx:Object label="My tracks" id="myTracks" />
+                                       <mx:Object label="Clear" id="clearGps" />
                                </mx:Array>
                        </mx:dataProvider>
                </mx:PopUpMenuButton>
         <mx:Button id="redo" label="Redo" click="MainUndoStack.getGlobalStack().redo();" styleName="appBarButton"
             enabled="{MainUndoStack.getGlobalStack().canRedo()}"/>
         <mx:Spacer width="100%"/>
-        <mx:Button label="Help" click="new HelpDialog().init();" styleName="appBarButton" />
-        <mx:Button label="Options" click="new OptionsDialog().init();" styleName="appBarButton" /> 
+        <mx:Button id="helpButton" label="Help" click="new HelpDialog().init();" styleName="appBarButton" />
+        <mx:Button id="optionsButton" label="Options" click="new OptionsDialog().init();" styleName="appBarButton" />
         <mx:Button label="Save" icon="@Embed('embedded/upload.svg')" disabledIcon="@Embed('embedded/upload_disabled.svg')" styleName="appBarButton"
                        click="SaveManager.saveChanges();" id="saveButton" enabled="false"/>
     </mx:ApplicationControlBar>
-
-    <map:LocalizationMap xmlns:map="l10n.map.*" />
     
     <mx:HDividedBox width="100%" height="100%">
 
@@ -67,6 +72,8 @@
             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom in - currently z'+getScale()}" />
         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom out - currently z'+getScale()}" />
+        <mx:Image source="@Embed('embedded/search.svg')" right="3" top="40" click="new FindDialog().init();"
+            rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="Find place" />
         <mx:TextArea id="dataWorking" text="" right="20" top="3" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="18"
             enabled="false" borderThickness="0"
             showEffect="{wipeIn}" hideEffect="{wipeOut}"/>
@@ -82,6 +89,7 @@
                import net.systemeD.halcyon.connection.*;
                import net.systemeD.potlatch2.*;
                import net.systemeD.potlatch2.save.SaveManager;
+               import net.systemeD.potlatch2.find.*;
                import net.systemeD.potlatch2.collections.*;
                import net.systemeD.potlatch2.controller.*;
                import net.systemeD.potlatch2.help.*;
 
         include "version.as";
 
-               private function initApp():void {
+               private function startInit():void {
+            /* For reasons that I don't yet understand, the en_US locale is the default and doesn't work at all. */
+            /* Change this to another locale (e.g. fr_FR) to see the differences. */
+            if (loaderInfo.parameters['locale']) {
+              dispatchEvent(new LocaleEvent(LocaleEvent.LOAD_LOCALE,loaderInfo.parameters['locale']));
+            }
 
-            /* For reasons that I don't yet understand, the en_US locale is the default and doesn't work at all. Use en_GB instead. */
-            /* Change this to another locale (e.g. fr_FR) to see the differences. This will obviously become done differently at some point. */
-            dispatchEvent(new LocaleEvent(LocaleEvent.LOAD_LOCALE,'en_GB'));
+                       // Load font and don't do anything until that's done
+                       var loader:Loader = new Loader();
+                       loader.contentLoaderInfo.addEventListener(Event.COMPLETE, continueInit);
+                       loader.load(new URLRequest("FontLibrary.swf"));
+               }
+               
+               private function continueInit(r:Event):void {
+                       // Set font
+                       var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
+                       Font.registerFont(FontLibrary.DejaVu);
 
                        Globals.vars.map_area = map_area;
                        Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
 
                        // pass additional parameters to map
                        var params:Object={}; var k:String;
-                       for (k in this.loaderInfo.parameters) {
-                               params[k]=this.loaderInfo.parameters[k];
-                       }
-                       for (k in SharedObject.getLocal('user_state').data) {
-                               params[k]=SharedObject.getLocal('user_state').data[k];
-                       }
-                       params['tileblocks']=[new RegExp("google","i")];        // hard-coded block on Google tiles
+                       for (k in this.loaderInfo.parameters) params[k]=this.loaderInfo.parameters[k];
+                       for (k in SharedObject.getLocal('user_state').data) params[k]=SharedObject.getLocal('user_state').data[k];
 
-                       // create map and Yahoo
+                       // Create map
                        theMap=new Map(params);
 
+                       // Initialise 900913 background
+                       // >>>> REFACTOR: something odd about accessing map.tileparams here...
+                       map.tileset.blocks=[new RegExp("google","i")];  // hard-coded block on Google tiles
+                       map.tileset.init(map.tileparams, false, 
+                                        initparams['background_dim']    ==null ? true  : initparams['background_dim'],
+                                        initparams['background_sharpen']==null ? false : initparams['background_sharpen']);
+
+                       // Add core data layer
+                       // >>>> REFACTOR: shouldn't be hardcoded to XMLConnection
+                       var conn:Connection = new XMLConnection("Main", initparams['api'], initparams['policy'], initparams);
+            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);
+                       conn.addEventListener(AttentionEvent.ATTENTION, onAttention);
+                       conn.addEventListener(AttentionEvent.ALERT, onAlert);
+                       map.addLayer(conn,initparams['styleurl'],false);
+
+                       // Set start position of map
+                       // >>>> REFACTOR: what happens if lat/lon/zoom not supplied? (Hurleston GPX case)
+                       map.init(initparams['lat'], initparams['lon'], initparams['zoom']);
+
             // Auto-load vector backgrounds from config
             // This could go spectacularly wrong if map.init completes before the event listener below is added
             theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void { VectorBackgrounds.instance().init(theMap); });
 
                        theMap.backdrop=b;
-                       yahoo=new Yahoo(w,h,theMap);
+                       yahoo=new Yahoo(theMap);
                        yahoo.hide();
                        _root.addChild(yahoo);
                        _root.addChild(theMap);
 
                        // keyboard event attached to stage
                        stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
+            
+                       // mouse-position listener for co-ordinate display
+            theMap.addEventListener(MapEvent.MOUSE_MOVE, mouseoverHandler);
 
                        // position toolbox
                        toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
             theController = new EditController(theMap, tagViewer, toolbox);
             theController.setActive();
             
-            theMap.addEventListener(MapEvent.MOUSEOVER, mouseoverHandler);
-            theMap.addEventListener(MapEvent.TOGGLE_LATLON, togglelatlonHandler);
-            
-            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);
-                       conn.addEventListener(AttentionEvent.ATTENTION, onAttention);
-                       conn.addEventListener(AttentionEvent.ALERT, onAlert);
-
             // set the access token from saved cookie
             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
             }
         }
 
-        private function togglelatlonHandler(e:MapEvent):void {
-            coordsbox.visible = e.params.latlon;
-        }
-
-
         private function onDataStart(event:Event):void {
                        switch (event.type) {
                                case Connection.LOAD_STARTED:   loadcount++; break;
 
                        // 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));
+
+            // If you dnd quick enough, this exposes a flex bug and event.stageX/Y become negative.
+            // Take the mouse positions from a displayObject's stage for consistent results.
+            var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.target.stage.mouseX, event.target.stage.mouseY));
             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);
+            var node:Node = Connection.getConnection().createNode({}, lat, lon, createAction.push);
             for each ( var tag:Object in tags ) {
                 node.setTag(tag.k, tag.v, createAction.push);
             }
-                       Connection.getConnectionInstance().registerPOI(node);
+                       Connection.getConnection().registerPOI(node);
                        MainUndoStack.getGlobalStack().addAction(createAction);
             theController.setState(new SelectedPOINode(node));
         }
         }
 
         private function loadTrace(id:Number):void {
-            var conn:Connection = Connection.getConnectionInstance();
+            var conn:Connection = Connection.getConnection();
             conn.addEventListener(Connection.TRACES_LOADED, function (e:Event):void {
                 for each (var trace:Trace in conn.getTraces()) {
                     if (trace.id == id) { trace.addToMap(); }