apply multiple-selection tagging patch by Christian Resch (thanks!)
[potlatch2.git] / net / systemeD / potlatch2 / TagViewer.mxml
1 <?xml version="1.0" encoding="utf-8"?>
2 <mx:VBox
3         xmlns:mx="http://www.adobe.com/2006/mxml"
4         xmlns:flexlib="flexlib.containers.*"
5         xmlns:controls="net.systemeD.controls.*"
6         xmlns:potlatch2="net.systemeD.potlatch2.*"
7     xmlns:sidepanel="net.systemeD.potlatch2.panels.*"
8         horizontalScrollPolicy="off"
9     backgroundColor="white"
10     initialize="loadFeatures()">
11
12 <mx:ViewStack id="sidebar" width="100%" height="100%" creationPolicy="all">
13   <mx:VBox id="dndPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
14     <mx:Text id="dndPanelText" text="{dndPrompt}" width="100%" styleName="helpInfo" />
15         <mx:Repeater id="dndRep" dataProvider="{MapFeatures.getInstance().getCategoriesForType('point')}" styleName="dndRepeater">
16                 <mx:HBox width="100%" styleName="dndPanelCategory">
17                         <mx:Label text="{dndRep.currentItem.name}:" styleName="dndPanelCategoryLabel"/>
18                 </mx:HBox>
19
20                 <mx:TileList dataProvider="{dndRep.currentItem.getFeaturesForType('point')}" width="100%" height="1"
21                                      rowHeight="32" columnWidth="32" updateComplete="resizePOIGrid(event)" styleName="dndPanelTileList">
22                         <mx:itemRenderer>
23                                 <mx:Component>
24                                         <mx:VBox toolTip="{data.name}">
25                                                 <mx:Script><![CDATA[
26                                                         import mx.events.DragEvent;
27                                                         import mx.managers.DragManager;
28                                                         import mx.core.DragSource;
29
30                                                         private function dragPOI(event:MouseEvent, tags:Array):void {
31                                                                 // Get the drag initiator component from the event object.
32                                                                 var dragInitiator:Image = event.currentTarget as Image;
33                                                                 var dragSource:DragSource = new DragSource();
34                                                                 dragSource.addData(tags, 'tags');
35                                                                 dragSource.addData(event.target.parent.parent.parent.parent, 'container');
36
37                                                                 var dragProxy:Image = new Image();
38                                                                 dragProxy.source = dragInitiator.source;
39                                                                 dragProxy.width = dragInitiator.width;   // must set width and height explicitly
40                                                                 dragProxy.height = dragInitiator.height; // for non-embedded images
41                                                                 DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
42                                                         }
43                                                 ]]></mx:Script>
44                                                 <mx:Image id="foo" source="{data.image}" height="24" width="24" mouseMove="dragPOI(event, data.tags)" toolTip="{data.name}" />
45                                         </mx:VBox>
46                                 </mx:Component>
47                         </mx:itemRenderer>
48                 </mx:TileList>
49         </mx:Repeater>
50   </mx:VBox>
51   
52   <mx:VBox id="tagsPanel" width="100%" height="100%" creationPolicy="auto">
53     <mx:ViewStack id="stack" width="100%" height="100%">
54       <mx:VBox width="100%" height="100%" label="Simple" id="editorContainer" creationComplete="initEditorStackUIs()" styleName="dndPanelVbox">
55         <mx:VBox width="100%" verticalGap="1" styleName="dndTagHeader">
56           <mx:HBox width="100%" id="iconContainer" styleName="featureSelector">
57             <mx:Image id="iconImage"/>
58             <mx:Text condenseWhite="true" width="100%" id="iconText" styleName="dndIconText"/>
59           </mx:HBox>
60           <mx:HBox width="100%">
61             <mx:PopUpButton id="popupChange" creationComplete="initFeatureBox()" openAlways="true" width="100%" styleName="dndTagPopUpMenu"/>
62             <mx:LinkButton icon="@Embed('../../../embedded/information.svg')" click="openDescription()" id="helpLabel" styleName="helpInfo"/>
63           </mx:HBox>
64         </mx:VBox>
65       </mx:VBox>
66       <mx:VBox width="100%" height="100%" label="Advanced" id="advancedContainer" initialize="checkAdvanced()" verticalGap="1">
67         <mx:Label id="advancedID" click="openEntityPage()">
68           <mx:htmlText><![CDATA[<i>No Selection</i>]]></mx:htmlText>
69         </mx:Label>
70
71                 <potlatch2:TagGrid id="advancedTagGrid" width="100%" height="75%" />
72
73         <mx:HBox horizontalAlign="right" width="100%">
74           <mx:LinkButton label="Delete" click="advancedTagGrid.removeTag()" enabled="{advancedTagGrid.selectedItem != null? true : false}"/>
75           <mx:LinkButton label="Add" click="advancedTagGrid.addNewTag()" id="advancedAddButton"/>
76         </mx:HBox>
77         
78         <mx:DataGrid editable="true" width="100%" height="25%" id="relationsGrid"
79             doubleClickEnabled="true"
80             itemDoubleClick="editRelation(relationsGrid.selectedItem.id)"
81             doubleClick="if (event.target.parent==relationsGrid) { addToRelation(); }">
82             <mx:columns>
83                 <mx:DataGridColumn editable="false" dataField="description" headerText="Relation"/>
84                 <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
85                 <mx:DataGridColumn editable="true" dataField="role" headerText="Role"/>
86             </mx:columns>
87         </mx:DataGrid>
88
89         <mx:HBox horizontalAlign="right" width="100%">
90           <mx:LinkButton label="Remove from" click="removeFromRelation(relationsGrid.selectedItem.id, relationsGrid.selectedItem.index)" 
91                           enabled="{relationsGrid.selectedItem != null? true : false}"/>
92           <mx:LinkButton label="Add to" click="addToRelation()"/>
93         </mx:HBox>
94
95       </mx:VBox>
96
97       <mx:VBox width="100%" height="100%" label="Members" id="membersVBox" initialize="checkMembers()" verticalGap="1">
98         <mx:Label id="membersText" text="Relation Members"/>
99         <mx:DataGrid editable="true" width="100%" height="100%" id="membersGrid"
100                       dragEnabled="true" dragMoveEnabled="true" dropEnabled="true">
101           <mx:columns>
102             <mx:DataGridColumn editable="false" dataField="type" headerText="Type"/>
103             <mx:DataGridColumn editable="false" dataField="id" headerText="ID"/>
104             <mx:DataGridColumn editable="true" dataField="role" headerText="Role"/>
105           </mx:columns>
106         </mx:DataGrid>
107       </mx:VBox>
108       
109       </mx:ViewStack>
110
111           <mx:HBox width="100%">
112                 <mx:LinkBar dataProvider="{stack}"/>
113                 <mx:Spacer width="100%"/>
114                 <mx:LinkButton 
115                         icon="@Embed('../../../embedded/view_tabbed.png')"
116                         disabledIcon="@Embed('../../../embedded/view_tabbed_disabled.png')"
117                         click="setEditorStackUI(true)" id="tabNavigatorLabel" paddingTop="6" 
118                         toolTip="Show in tabs"
119                         enabled="{editorStack is Accordion &amp;&amp; stack.selectedIndex==0}" />
120                 <mx:LinkButton
121                         icon="@Embed('../../../embedded/view_accordion.png')" 
122                         disabledIcon="@Embed('../../../embedded/view_accordion_disabled.png')"
123                         click="setEditorStackUI(false)" id="accordionLabel" paddingTop="6"
124                         toolTip="Show in sliding windows"
125                         enabled="{editorStack is SuperTabNavigator &amp;&amp; stack.selectedIndex==0}" />
126           </mx:HBox>
127   </mx:VBox>
128
129   <mx:VBox id="multiplePanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
130     <potlatch2:TagGrid id="multiAdvancedTagGrid" width="100%" height="75%" />
131         <mx:HBox horizontalAlign="right" width="100%">
132           <mx:LinkButton label="Delete" click="multiAdvancedTagGrid.removeTag()" enabled="{multiAdvancedTagGrid.selectedItem != null? true : false}"/>
133           <mx:LinkButton label="Add" click="multiAdvancedTagGrid.addNewTag()" />
134         </mx:HBox>
135   </mx:VBox>
136         
137   <mx:VBox id="multipleInvalidPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
138         <mx:Text id="multipleInvalidPanelText" text="You have selected multiple items." width="100%" styleName="helpInfo" />
139   </mx:VBox>
140
141   <mx:VBox id="markerPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
142     <sidepanel:MarkerPanel id="markerPanelContents" width="100%"/>
143   </mx:VBox>
144
145   <mx:VBox id="bugPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
146     <sidepanel:BugPanel id="bugPanelContents" width="100%"/>
147   </mx:VBox>
148
149 </mx:ViewStack>
150
151   <mx:Script><![CDATA[
152       import net.systemeD.halcyon.connection.*;
153       import net.systemeD.halcyon.VectorLayer;
154       import net.systemeD.potlatch2.mapfeatures.*;
155
156       import mx.collections.*;
157       import mx.containers.*;
158       import mx.events.*;
159       import mx.core.*;
160       import mx.managers.PopUpManager;
161       import flash.geom.Point;
162       import flash.net.*;
163       import mx.events.DragEvent;
164       import mx.managers.DragManager;
165       import mx.core.DragSource;
166       import flexlib.containers.SuperTabNavigator;
167
168       private static const dndPrompt:String="Add new points by dragging them onto the map";
169
170       private var editorStackTabNavigator:SuperTabNavigator;
171       private var editorStackAccordion:Accordion;
172       [Bindable] private var editorStack:Container;
173
174       public var mapFeatures:MapFeatures;
175       private var selectedEntity:Entity;
176       private var tw:CategorySelector = null;
177       private var feature:Feature = null;
178
179           public function setEntity(entities:Array, layer:VectorLayer=null):void {
180                 UIComponent.suspendBackgroundProcessing();
181                 
182                 var firstSelected:Entity=null;
183                 if (entities.length==1) { firstSelected=entities[0]; }
184                 
185                 if (selectedEntity!=firstSelected && selectedEntity!=null) {
186                         selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
187                 }
188                 
189                 if (entities.length==0) {
190                         // Nothing selected, so show drag-and-drop panel
191                         sidebar.selectedChild = dndPanel;
192                 
193                 } else if (entities.length==1) {
194                         // Single entity selected, so show tag panel
195                         selectedEntity=firstSelected;
196                         if (selectedEntity!=null) { selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged); }
197                         if (advancedID!=null) { setupAdvanced(firstSelected); }
198                         if (firstSelected is Relation) { stack.addChild(membersVBox); }
199             if (selectedEntity is Marker && layer is BugLayer) {
200               bugPanelContents.init(selectedEntity, layer);
201               sidebar.selectedChild = bugPanel;
202             } else if (selectedEntity is Marker) {
203               markerPanelContents.init(selectedEntity, layer);
204               sidebar.selectedChild = markerPanel;
205             } else {
206               refreshFeatureIcon();
207               initialiseEditors();
208               sidebar.selectedChild = tagsPanel;
209             }
210                 
211                 } else if(isMultipleEditable(entities)) {
212                         selectedEntity = new EntityCollection(entities);
213                         selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged);
214             sidebar.selectedChild = multiplePanel;
215                         setupMultiAdvanced(selectedEntity);
216                         
217                 } else {
218                         //The selection contains elements which can't be edited all together.
219                         sidebar.selectedChild = multipleInvalidPanel;
220                 }
221                 UIComponent.resumeBackgroundProcessing();
222       }
223
224       private function refreshFeatureIcon():void {
225           var oldFeature:Feature = feature;
226           feature = selectedEntity == null ? null : mapFeatures.findMatchingFeature(selectedEntity);
227           if ( feature != oldFeature ) {
228               if ( oldFeature != null )
229                   oldFeature.removeEventListener("imageChanged", featureImageChanged);
230               if ( feature != null )
231                   feature.addEventListener("imageChanged", featureImageChanged);
232           }
233
234           if ( feature != null && feature.name != null ) {
235               setFeatureIcon(selectedEntity, feature);
236           } else {
237               blankFeatureIcon(selectedEntity);
238           }
239       }
240
241       private function featureImageChanged(event:Event):void {
242           setFeatureIcon(selectedEntity, feature);
243       }
244       
245       private function setFeatureIcon(entity:Entity, feature:Feature):void {
246           //blankFeatureIcon(entity);
247           
248           iconImage.source = feature.image;
249
250           var txt:String = feature.htmlDetails(entity);
251           iconText.htmlText = txt;
252           popupChange.label = feature.name;
253           setLimitTypes(entity);
254           tw.setSelectedFeature(feature);
255           helpLabel.visible = feature.hasHelpURL();
256       }
257           
258           private function isMultipleEditable(entities:Array):Boolean {
259                 for each(var entity:Entity in entities) {
260                         if(!(entity is Node || entity is Way))
261                                 return false;
262                 }
263                 return true;
264           }
265       
266       private function setLimitTypes(entity:Entity):void {
267           var type:String = null;
268           if ( entity is Node )
269               type = "point";
270           else if ( entity is Way )
271               type = Way(entity).isArea() ? "area" : "line";
272           else if ( entity is Relation )
273               type = "relation";
274           tw.setLimitTypes(type);
275       }
276
277       private function blankFeatureIcon(entity:Entity):void {
278           iconImage.source = null;
279           popupChange.label = "unknown";
280           setLimitTypes(entity);
281                   if (entity == null) { 
282                         iconText.htmlText = "<i>Nothing selected</i>";
283             tw.setNoSelectedFeature();
284                   } else if (entity.hasTags()) {
285                         iconText.htmlText = "<b>Not recognised</b><br/><font size='10pt'>Try looking at the tags under the advanced properties</font>";
286             tw.setSelectedFeature(null);
287                   } else {
288                         iconText.htmlText = "<b>No tags set</b><br/><font size='10pt'>Please use the menu below to define what this "+entity.getType()+" is</font>";
289             tw.setSelectedFeature(null);
290           }
291           helpLabel.visible = false;
292       }
293
294       private var tabComponents:Object = {};
295       
296       private function initialiseEditors():void {
297           editorStack.removeAllChildren();
298           if ( selectedEntity == null || feature == null )
299               return;
300           
301           var editorBox:VBox = createEditorBox();
302           editorBox.label = "Basic";
303           editorStack.addChild(editorBox);
304           
305           var tabs:Object = {};
306           tabComponents = {};
307           
308           for each (var factory:EditorFactory in feature.editors) {
309               if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
310                   var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
311                   if ( editor != null )
312                       editorBox.addChild(editor);
313               }
314               var category:String = factory.category;
315               if (category!='') {
316                       var tab:VBox = tabs[category];
317                       if ( tab == null) {
318                           tab = createEditorBox();
319                           tab.label = category;
320                           editorStack.addChild(tab);
321                           tabs[category] = tab;
322                           tabComponents[tab] = [];
323                       }
324                       var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
325                       if ( catEditor != null )
326                           tabComponents[tab].push(catEditor);
327                       //    tab.addChild(catEditor);
328               }
329           }
330       }
331       
332       private function createEditorBox():VBox {
333           var box:VBox = new VBox();
334           box.percentWidth = 100;
335           box.percentHeight = 100;
336           box.styleName = "dndEditorContainer";
337           return box;
338       }
339
340       private function ensureEditorsPopulated(tab:VBox):void {
341           var components:Array = tabComponents[tab];
342           if ( components == null || tab == null || tab.numChildren >= components.length )
343               return;
344           for each (var component:DisplayObject in components ) {
345               tab.addChild(component);
346           }
347       }
348       
349         private function initEditorStackUIs():void {
350                 editorStackTabNavigator = new SuperTabNavigator();
351                 editorStackTabNavigator.allowTabSqueezing=false;
352                 editorStackTabNavigator.minTabWidth=10;
353                 editorStackTabNavigator.closePolicy="close_never";
354                 editorStackTabNavigator.scrollSpeed=20;
355                 editorStackTabNavigator.creationPolicy="auto";
356                 editorStackTabNavigator.percentWidth=100;
357                 editorStackTabNavigator.percentHeight=100;
358                 editorStackTabNavigator.styleName="dndStackTab";
359                 editorStackTabNavigator.popUpButtonPolicy="off"
360
361
362                 editorStackAccordion = new Accordion();
363                 editorStackAccordion.percentWidth=100;
364                 editorStackAccordion.percentHeight=100;
365                 editorStackAccordion.creationPolicy="auto";
366                 editorStackAccordion.styleName="dndStackAccordion";
367
368                 setEditorStackUI(true);
369         }
370
371         private function setEditorStackUI(isTabbed:Boolean):void {
372                 var children:Array=[]; var i:uint;
373
374                 if (editorStack) {
375                         // blank existing component
376                         editorStack.removeEventListener("change",editorStackUIChange);
377                         editorStack.removeEventListener("updateComplete",editorStackUIUpdate);
378                         editorStack.removeAllChildren();
379                         editorContainer.removeChildAt(1);
380                 }
381
382                 // replace with new component
383                 editorStack = (isTabbed ? editorStackTabNavigator : editorStackAccordion) as Container;
384                 editorContainer.addChild(editorStack);
385
386                 // re-add children and listeners
387                 initialiseEditors();
388                 editorStack.addEventListener("change",editorStackUIChange);
389                 editorStack.addEventListener("updateComplete",editorStackUIUpdate);
390         }
391         
392         private function editorStackUIChange(event:Event):void {
393                 ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox);
394         }
395
396         private function editorStackUIUpdate(event:Event):void {
397                 if (editorStack is SuperTabNavigator) {
398                         var e:SuperTabNavigator = editorStack as SuperTabNavigator;
399                         if (e.selectedIndex<0) { return; }
400                         for (var i:uint=0; i<e.numChildren; i++) {
401                                 e.getTabAt(i).selected=(i==e.selectedIndex);
402                         }
403                 }
404         }
405
406
407         public function togglePanel():void {
408                 if (stack.selectedChild==editorContainer && selectedEntity!=null) {
409                         stack.selectedChild=advancedContainer;
410                 } else if (stack.selectedChild!=editorContainer) {
411                         stack.selectedChild=editorContainer;
412                 }
413         }
414
415       private function checkAdvanced():void {
416           if ( selectedEntity != null )
417              setupAdvanced(selectedEntity);
418       }
419
420       /**
421       * When you enter a new tag and press enter, the focus moves to the add button
422       * Adding an event listener to the button and listening for + means that you
423       * can add two consecutive tags with the same keypress. This relies on focus
424       * moving to the "add" button, though, so it's not robust to rearranging the UI.
425       */
426       private function advancedAddButtonKeyboardEvent(event:KeyboardEvent):void {
427           switch (event.keyCode) {
428             case 187:   addNewTag(); break;                          // + - add tag
429           }
430       }
431
432       private var listeningToRelations:Array = [];
433       
434       private function setupAdvanced(entity:Entity):void {
435                 if (!advancedTagGrid) advancedContainer.createComponentsFromDescriptors();      // if Flex hasn't created it, force it
436                 advancedTagGrid.init(entity);
437         advancedAddButton.addEventListener(KeyboardEvent.KEY_DOWN, advancedAddButtonKeyboardEvent);
438
439                 if ( entity == null ) {
440                         advancedID.htmlText = "";
441                 } else {
442                         var entityText:String = "xx";
443                         if      ( entity is Node     ) entityText = "Node";
444                         else if ( entity is Way      ) entityText = "Way";
445                         else if ( entity is Relation ) entityText = "Relation";
446                         advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
447                 }
448
449                 removeRelationListeners();
450                 if ( selectedEntity != null ) {
451                         selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
452                         selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
453                 }
454
455                 if ( entity == null ) {
456                         relationsGrid.dataProvider = null;
457                 } else {
458                         resetRelationsGrid(entity);
459                         entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
460                         entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
461                 }
462       }
463           
464           private function setupMultiAdvanced(entity:Entity):void {
465                 multiAdvancedTagGrid.init(entity);
466       }
467
468           public function addNewTag():void {
469                 if (stack.selectedChild!=advancedContainer) { return; }
470                 advancedTagGrid.addNewTag();
471           }
472       
473       private function addedToRelation(event:RelationMemberEvent):void {
474          resetRelationsGrid(selectedEntity);
475       }
476
477       private function removedFromRelation(event:RelationMemberEvent):void {
478          resetRelationsGrid(selectedEntity);
479       }
480
481       private function removeRelationListeners():void {
482           for each( var rel:Relation in listeningToRelations ) {
483               rel.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
484               rel.removeEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
485               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
486           }
487           listeningToRelations = [];
488           relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
489       }
490             
491       private function resetRelationsGrid(entity:Entity):void {
492           removeRelationListeners();
493           var relations:Array = [];
494           for each( var rel:Relation in entity.parentRelations ) {
495               for each( var memberIndex:int in rel.findEntityMemberIndexes(entity)) {
496                   var props:Object = {};
497                   props["relation"] = rel;
498                   props["id"] = rel.id;
499                   props["index"] = memberIndex;
500                   props["role"] = rel.getMember(memberIndex).role;
501                   props["description"] = rel.getDescription();
502                   props["id_idx"] = rel.id + "/"+memberIndex;
503
504                   relations.push(props);
505               }
506               
507               rel.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
508               rel.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
509               rel.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
510               listeningToRelations.push(rel);
511           }
512           relationsGrid.dataProvider = relations;
513           relationsGrid.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
514       }
515       
516       private function relationRoleChanged(event:DataGridEvent):void {
517                 if (event.dataField != 'role') { return; }      // shouldn't really happen
518
519                 var relations:Array=event.currentTarget.dataProvider.toArray();
520                 var props:Object=relations[event.rowIndex];
521
522                 var relation:Relation=props['relation'];
523                 var index:uint=props['index'];
524                 var newRole:String=event.itemRenderer.data['role'];
525
526                 relation.setMember(index, new RelationMember(selectedEntity,newRole));
527       }
528
529       private function relationTagChanged(event:TagEvent):void {
530           resetRelationsGrid(selectedEntity);
531       }
532
533       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
534           resetRelationsGrid(selectedEntity);
535       }
536       
537       private function checkMembers():void {
538           if (selectedEntity is Relation) {
539             setupMembers(selectedEntity as Relation);
540           }
541       }
542       
543       private function setupMembers(rel:Relation):void {
544           var members:Array = [];
545           for (var i:int=0 ; i<rel.length; i++) {
546             var props:Object = {};
547             var member:RelationMember = rel.getMember(i);
548             props["id"] = member.entity.id;
549             props["type"] = member.entity.getType();
550             props["role"] = member.role;
551             
552             members.push(props);
553           }
554           membersGrid.dataProvider = members;
555           membersGrid.dataProvider.addEventListener('collectionChange', membersChange); 
556       }
557       
558       private function membersChange(event:Event):void {
559           // Dropping all the members and re-adding them isn't exactly optimal
560           // but is at least robust for any kind of change.
561           // Figuring out a better way is someone else's FIXME
562           
563           var conn:Connection = Connection.getConnectionInstance();
564           var rel:Relation = selectedEntity as Relation
565           var action:CompositeUndoableAction = new CompositeUndoableAction("Rearrange relation members for "+rel);
566           
567           // drop members
568           for (var i:int=rel.length-1 ; i>=0; i--) {
569             rel.removeMemberByIndex(i, action.push);
570           }
571           
572           // add members in new order
573           for each(var memberObject:Object in membersGrid.dataProvider) {
574             var e:Entity;
575             var id:Number = memberObject.id;
576             if(memberObject.type == 'node') {
577               e = conn.getNode(id);
578             } else if (memberObject.type == 'way') {
579               e = conn.getWay(id);
580             } else if (memberObject.type == 'relation') {
581               e = conn.getRelation(id);
582             }
583             rel.appendMember(new RelationMember(e, memberObject.role), action.push);
584           }
585           MainUndoStack.getGlobalStack().addAction(action);
586       }
587       
588       private function editRelation(id:Number):void {
589           var panel:RelationEditorPanel = RelationEditorPanel(
590               PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
591           panel.setRelation(Connection.getConnectionInstance().getRelation(id));
592           PopUpManager.centerPopUp(panel);
593       }
594       
595       private function tagChanged(event:TagEvent):void {
596               if(selectedEntity != null && selectedEntity is EntityCollection) {
597                         setupMultiAdvanced(selectedEntity);
598                     return;
599                   }
600                   
601           refreshFeatureIcon();
602           // if the advancedTagGrid has already been set up, it needs to be refreshed.
603           // FIXME make this better, maybe advancedTagGrid should be event listening.
604           if(advancedContainer.initialized) {
605             checkAdvanced();
606           }
607       }
608
609       public function loadFeatures():void {
610           mapFeatures = MapFeatures.getInstance();
611           stack.removeChild(membersVBox); // remove by default, will be added if relation
612       }
613
614       public function openDescription():void {
615           if ( feature != null && feature.hasHelpURL() )
616               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
617       }
618
619       public function openEntityPage():void {
620           if (selectedEntity != null && selectedEntity.id >= 0) {
621               // This is slightly hard-coded, but not drastically. The ../s could be changed for string manipulation of the apiBase
622               var urlBase:String = Connection.getConnectionInstance().apiBase + '../../browse/'
623               navigateToURL(new URLRequest(urlBase+selectedEntity.getType()+'/'+selectedEntity.id), "potlatch_browse");
624           }
625       }
626
627       public function addToRelation():void {
628           new RelationSelectPanel().init(selectedEntity,new Object());
629       }
630       
631       private function removeFromRelation(id:Number, index:int):void {
632           Connection.getConnectionInstance().getRelation(id).removeMemberByIndex(index, MainUndoStack.getGlobalStack().addAction);
633       }
634       
635       public function initFeatureBox():void {
636           tw = new CategorySelector();
637           tw.addEventListener("selectedType", changeFeatureType);
638           popupChange.popUp = tw;
639       }
640       
641       public function changeFeatureType(event:Event):void {
642           if ( selectedEntity == null )
643               return;
644
645           UIComponent.suspendBackgroundProcessing();
646           var newFeature:Feature = tw.selectedType;
647           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
648           var action:CompositeUndoableAction = new CompositeUndoableAction(
649                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
650                   selectedEntity.suspend();
651
652           // remove tags from the current feature
653           if ( feature != null ) {
654               for each( var oldtag:Object in feature.tags ) {
655                   selectedEntity.setTag(oldtag["k"], null, action.push);
656               }
657           }
658           
659           // set tags for new feature
660           if ( newFeature != null ) {
661               for each( var newtag:Object in newFeature.tags ) {
662                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
663               }
664           }
665           
666                   selectedEntity.resume();
667           undoStack(action);
668           popupChange.close();
669           initialiseEditors();
670           UIComponent.resumeBackgroundProcessing();
671       }
672       
673         private function resizePOIGrid(event:Event):void {
674                 var rows:Number=event.target.dataProvider.length/event.target.columnCount;
675                 if (rows!=Math.floor(rows)) { rows=Math.floor(rows+1); }
676                 event.target.height=rows*(event.target.rowHeight+1);
677         }
678   ]]></mx:Script>
679 </mx:VBox>
680