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