Merge commit '2.0' into history
[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
14   <!-- Drag & drop icon panel -->
15
16   <mx:VBox id="dndPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
17     <mx:Text id="dndPanelText" text="{dndPrompt}" width="100%" styleName="helpInfo" />
18         <mx:Repeater id="dndRep" dataProvider="{MapFeatures.getInstance().getCategoriesForType('point')}" styleName="dndRepeater">
19                 <mx:HBox width="100%" styleName="dndPanelCategory">
20                         <mx:Label text="{dndRep.currentItem.name}:" styleName="dndPanelCategoryLabel"/>
21                 </mx:HBox>
22
23                 <mx:TileList dataProvider="{dndRep.currentItem.getFeaturesForType('point', true)}" width="100%" height="1"
24                                      rowHeight="32" columnWidth="32" updateComplete="resizePOIGrid(event)" styleName="dndPanelTileList">
25                         <mx:itemRenderer>
26                                 <mx:Component>
27                                         <mx:VBox toolTip="{data.name}">
28                                                 <mx:Script><![CDATA[
29                                                         import mx.events.DragEvent;
30                                                         import mx.managers.DragManager;
31                                                         import mx.core.DragSource;
32
33                                                         private function dragPOI(event:MouseEvent, tags:Array):void {
34                                                                 // Get the drag initiator component from the event object.
35                                                                 var dragInitiator:Image = event.currentTarget as Image;
36                                                                 var dragSource:DragSource = new DragSource();
37                                                                 dragSource.addData(tags, 'tags');
38                                                                 dragSource.addData(event.target.parent.parent.parent.parent, 'container');
39
40                                                                 var dragProxy:Image = new Image();
41                                                                 dragProxy.source = dragInitiator.source;
42                                                                 dragProxy.width = dragInitiator.width;   // must set width and height explicitly
43                                                                 dragProxy.height = dragInitiator.height; // for non-embedded images
44                                                                 DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
45                                                         }
46                                                 ]]></mx:Script>
47                                                 <mx:Image id="foo" source="{data.dndimage}" height="24" width="24" mouseMove="dragPOI(event, data.tags)" toolTip="{data.name}" />
48                                         </mx:VBox>
49                                 </mx:Component>
50                         </mx:itemRenderer>
51                 </mx:TileList>
52         </mx:Repeater>
53   </mx:VBox>
54
55   <!-- Standard tagging panel -->
56
57   <mx:VBox id="tagsPanel" width="100%" height="100%" creationPolicy="auto">
58     <mx:ViewStack id="stack" width="100%" height="100%">
59       <mx:VBox width="100%" height="100%" label="Simple" id="editorContainer" creationComplete="initEditorStackUIs()" styleName="dndPanelVbox">
60         <mx:VBox width="100%" verticalGap="1" styleName="dndTagHeader">
61           <mx:HBox width="100%" id="iconContainer" styleName="featureSelector">
62             <mx:Image id="iconImage"/>
63             <mx:Text condenseWhite="true" width="100%" id="iconText" styleName="dndIconText"/>
64           </mx:HBox>
65           <mx:HBox width="100%">
66             <mx:PopUpButton id="popupChange" openAlways="true" width="100%" styleName="dndTagPopUpMenu" closeDuration="0" />
67             <mx:LinkButton icon="@Embed('../../../embedded/information.svg')" click="openDescription()" id="helpLabel" styleName="helpInfo"/>
68           </mx:HBox>
69         </mx:VBox>
70       </mx:VBox>
71       <mx:VBox width="100%" height="100%" label="Advanced" id="advancedContainer" initialize="checkAdvanced()" verticalGap="1">
72         <mx:Label id="advancedID" click="new HistoryDialog().init(selectedEntity);">
73           <mx:htmlText><![CDATA[<i>No Selection</i>]]></mx:htmlText>
74         </mx:Label>
75
76                 <potlatch2:TagGrid id="advancedTagGrid" width="100%" height="75%" />
77
78         <mx:HBox horizontalAlign="right" width="100%">
79           <mx:LinkButton label="Delete" click="advancedTagGrid.removeTag()" id="advancedDeleteButton" enabled="{advancedTagGrid.selectedItem != null? true : false}"/>
80           <mx:LinkButton label="Add" click="advancedTagGrid.addNewTag()" id="advancedAddButton"/>
81         </mx:HBox>
82
83         <mx:DataGrid editable="true" width="100%" height="25%" id="relationsGrid"
84             doubleClickEnabled="true"
85             itemDoubleClick="editRelation(relationsGrid.selectedItem.id)"
86             doubleClick="if (event.target.parent==relationsGrid) { addToRelation(); }">
87             <mx:columns>
88                 <mx:DataGridColumn editable="false" dataField="description" headerText="Relation"/>
89                 <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
90                 <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
91                     <mx:itemEditor><mx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></mx:Component></mx:itemEditor>
92                 </mx:DataGridColumn>
93                                 <mx:DataGridColumn width="20" editable="false">
94                                         <mx:itemRenderer>
95                                                 <mx:Component>
96                                     <mx:HBox horizontalAlign="center" verticalAlign="middle">
97                                                                 <mx:PopUpButton arrowButtonWidth="12" paddingLeft="0" paddingRight="0" width="12" height="12" 
98                                                                                 open="{outerDocument.updateRelationMenu(event);}" 
99                                                                                 creationComplete="{outerDocument.createRelationMenu(PopUpButton(event.target));}"/>
100                                                         </mx:HBox>
101                                                 </mx:Component>
102                                         </mx:itemRenderer>
103                                 </mx:DataGridColumn>
104             </mx:columns>
105         </mx:DataGrid>
106
107         <mx:HBox horizontalAlign="right" width="100%">
108           <mx:LinkButton label="Remove from" click="removeFromRelation(relationsGrid.selectedItem.id, relationsGrid.selectedItem.index)"
109                           enabled="{relationsGrid.selectedItem != null? true : false}"/>
110           <mx:LinkButton label="Add to" click="addToRelation()"/>
111         </mx:HBox>
112
113       </mx:VBox>
114
115       <mx:VBox width="100%" height="100%" label="Members" id="membersVBox" initialize="checkMembers()" verticalGap="1">
116         <mx:Label id="membersText" text="Relation Members"/>
117         <mx:DataGrid editable="true" width="100%" height="100%" id="membersGrid"
118                       dragEnabled="true" dragMoveEnabled="true" dropEnabled="true">
119           <mx:columns>
120             <mx:DataGridColumn editable="false" dataField="type" headerText="Type"/>
121             <mx:DataGridColumn editable="false" dataField="id" headerText="ID"/>
122             <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
123                                 <mx:itemEditor><mx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></mx:Component></mx:itemEditor>
124                         </mx:DataGridColumn>
125           </mx:columns>
126         </mx:DataGrid>
127       </mx:VBox>
128
129       </mx:ViewStack>
130
131           <mx:HBox width="100%">
132                 <mx:LinkBar dataProvider="{stack}"/>
133                 <mx:Spacer width="100%"/>
134                 <mx:LinkButton
135                         icon="@Embed('../../../embedded/view_tabbed.png')"
136                         disabledIcon="@Embed('../../../embedded/view_tabbed_disabled.png')"
137                         click="setEditorStackUI(true)" id="tabNavigatorLabel" paddingTop="6"
138                         toolTip="Show in tabs"
139                         enabled="{editorStack is Accordion &amp;&amp; stack.selectedIndex==0}" />
140                 <mx:LinkButton
141                         icon="@Embed('../../../embedded/view_accordion.png')"
142                         disabledIcon="@Embed('../../../embedded/view_accordion_disabled.png')"
143                         click="setEditorStackUI(false)" id="accordionLabel" paddingTop="6"
144                         toolTip="Show in sliding windows"
145                         enabled="{editorStack is SuperTabNavigator &amp;&amp; stack.selectedIndex==0}" />
146           </mx:HBox>
147   </mx:VBox>
148
149   <!-- Multiple selection -->
150
151   <mx:VBox id="multiplePanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
152     <potlatch2:TagGrid id="multiAdvancedTagGrid" width="100%" height="75%" />
153         <mx:HBox horizontalAlign="right" width="100%">
154           <mx:LinkButton label="Delete" click="multiAdvancedTagGrid.removeTag()" enabled="{multiAdvancedTagGrid.selectedItem != null? true : false}"/>
155           <mx:LinkButton label="Add" click="multiAdvancedTagGrid.addNewTag()" />
156         </mx:HBox>
157
158     <mx:DataGrid editable="true" width="100%" height="25%" id="multiRelationsGrid"
159         doubleClickEnabled="true"
160         itemDoubleClick="editRelation(multiRelationsGrid.selectedItem.id)"
161         doubleClick="if (event.target.parent==multiRelationsGrid) { addToRelation(); }">
162         <mx:columns>
163             <mx:DataGridColumn editable="false" dataField="description" headerText="Relation"/>
164             <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
165             <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
166                 <mx:itemEditor><mx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></mx:Component></mx:itemEditor>
167             </mx:DataGridColumn>
168                         <mx:DataGridColumn width="20" editable="false">
169                                 <mx:itemRenderer>
170                                         <mx:Component>
171                             <mx:HBox horizontalAlign="center" verticalAlign="middle">
172                                                         <mx:PopUpButton arrowButtonWidth="12" paddingLeft="0" paddingRight="0" width="12" height="12" 
173                                                                         open="{outerDocument.updateRelationMenu(event);}" 
174                                                                         creationComplete="{outerDocument.createRelationMenu(PopUpButton(event.target));}"/>
175                                                 </mx:HBox>
176                                         </mx:Component>
177                                 </mx:itemRenderer>
178                         </mx:DataGridColumn>
179         </mx:columns>
180     </mx:DataGrid>
181     <mx:HBox horizontalAlign="right" width="100%">
182       <mx:LinkButton label="Remove from" click="removeFromRelation(multiRelationsGrid.selectedItem.id)"
183                       enabled="{multiRelationsGrid.selectedItem != null? true : false}"/>
184       <mx:LinkButton label="Add to" click="addToRelation()"/>
185     </mx:HBox>
186
187   </mx:VBox>
188
189   <!-- Multiple selection but items cannot be edited -->
190
191   <mx:VBox id="multipleInvalidPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
192         <mx:Text id="multipleInvalidPanelText" text="You have selected multiple items." width="100%" styleName="helpInfo" />
193   </mx:VBox>
194
195   <!-- Generic marker panel -->
196
197   <mx:VBox id="markerPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
198     <sidepanel:MarkerPanel id="markerPanelContents" width="100%"/>
199   </mx:VBox>
200
201   <!-- Bug editing panel -->
202
203   <mx:VBox id="bugPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
204     <sidepanel:BugPanel id="bugPanelContents" width="100%"/>
205   </mx:VBox>
206
207 </mx:ViewStack>
208
209   <mx:Script><![CDATA[
210       import net.systemeD.halcyon.connection.*;
211       import net.systemeD.halcyon.VectorLayer;
212       import net.systemeD.potlatch2.mapfeatures.*;
213       import net.systemeD.potlatch2.history.HistoryDialog;
214
215       import mx.collections.*;
216       import mx.containers.*;
217       import mx.events.*;
218       import mx.core.*;
219       import mx.managers.PopUpManager;
220       import mx.controls.Menu;
221       import flash.geom.Point;
222       import flash.net.*;
223       import mx.events.DragEvent;
224       import mx.managers.DragManager;
225       import mx.core.DragSource;
226       import flexlib.containers.SuperTabNavigator;
227
228       [Bindable]
229       public var dndPrompt:String="Add new points by dragging them onto the map";
230
231       private var editorStackTabNavigator:SuperTabNavigator;
232       private var editorStackAccordion:Accordion;
233       [Bindable] private var editorStack:Container;
234
235       public var mapFeatures:MapFeatures;
236       private var selectedEntity:Entity;
237       private var currentCategorySelector:CategorySelector;
238       private var categorySelectors:Object = {};        // hash of categorySelectors for each limitType
239       private var feature:Feature = null;
240
241       private var rowData:Object;               // relation membership reference, needed so it's accessible from relation actions menu
242
243           public function setEntity(entities:Array, layer:VectorLayer=null):void {
244                 UIComponent.suspendBackgroundProcessing();
245
246                 var firstSelected:Entity=null;
247                 if (entities.length==1) { firstSelected=entities[0]; }
248
249                 if (selectedEntity!=firstSelected && selectedEntity!=null) {
250                         selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
251                         selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
252                         selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
253                 }
254
255                 if (entities.length==0) {
256                         // Nothing selected, so show drag-and-drop panel
257                         sidebar.selectedChild = dndPanel;
258
259                 } else if (entities.length==1) {
260                         // Single entity selected, so show tag panel
261                         selectedEntity=firstSelected;
262                         if (selectedEntity!=null) { selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged); }
263                         if (advancedID!=null) { setupAdvanced(firstSelected); }
264                         if (firstSelected is Relation) { stack.addChild(membersVBox); }
265             if (selectedEntity is Marker && layer is BugLayer) {
266               bugPanelContents.init(selectedEntity, layer);
267               sidebar.selectedChild = bugPanel;
268             } else if (selectedEntity is Marker) {
269               markerPanelContents.init(selectedEntity, layer);
270               sidebar.selectedChild = markerPanel;
271             } else {
272               refreshFeatureIcon();
273               initialiseEditors();
274               sidebar.selectedChild = tagsPanel;
275             }
276
277                 } else if(isMultipleEditable(entities)) {
278                         selectedEntity = new EntityCollection(entities);
279                         selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged);
280             sidebar.selectedChild = multiplePanel;
281                         setupMultiAdvanced(selectedEntity);
282
283                 } else {
284                         //The selection contains elements which can't be edited all together.
285                         sidebar.selectedChild = multipleInvalidPanel;
286                 }
287                 UIComponent.resumeBackgroundProcessing();
288       }
289
290       private function refreshFeatureIcon():void {
291           var oldFeature:Feature = feature;
292           feature = selectedEntity == null ? null : mapFeatures.findMatchingFeature(selectedEntity);
293           if ( feature != oldFeature ) {
294               if ( oldFeature != null )
295                   oldFeature.removeEventListener("imageChanged", featureImageChanged);
296               if ( feature != null )
297                   feature.addEventListener("imageChanged", featureImageChanged);
298           }
299           setCategorySelector(selectedEntity, feature);
300       }
301
302       private function featureImageChanged(event:Event):void {
303           setCategorySelector(selectedEntity, feature);
304       }
305
306       /** Set the icon, categorySelector and help text for the current entity. */
307       private function setCategorySelector(entity:Entity, feature:Feature):void {
308                         // Remove the "user has selected something" event listener from previous categorySelector,
309                         // and make it invisible because Flex is crap at updating click areas otherwise
310                         if (currentCategorySelector) { 
311                                 currentCategorySelector.removeEventListener("selectedType", changeFeatureType);
312                                 currentCategorySelector.visible=false;
313                         }
314                         
315                         // Have we cached the categorySelector for this limitType? If not, create one
316                         var lt:String=limitType(entity);
317                         if (!categorySelectors[lt]) {
318                                 categorySelectors[lt]=new CategorySelector();
319                                 categorySelectors[lt].setLimitTypes(lt);
320                         }
321                         currentCategorySelector=categorySelectors[lt];
322                         currentCategorySelector.addEventListener("selectedType", changeFeatureType, false, 0, true);
323
324                         // Update surrounding icon/text display
325                         if (feature) {
326                                 iconImage.source = feature.image;
327                                 iconText.htmlText = feature.htmlDetails(entity);
328                                 popupChange.label = feature.name;
329                                 helpLabel.visible = feature.hasHelpURL();
330                                 currentCategorySelector.setSelectedFeature(feature);
331                         } else {
332                                 iconImage.source = null;
333                                 popupChange.label = "unknown";
334                                 helpLabel.visible = false;
335                                 if (entity==null) {
336                                         iconText.htmlText = "<i>Nothing selected</i>";
337                                 } else if (entity.hasTags()) {
338                                         iconText.htmlText = "<b>Not recognised</b><br/><font size='10pt'>Try looking at the tags under the advanced properties</font>";
339                                 } else {
340                                         iconText.htmlText = "<b>No tags set</b><br/><font size='10pt'>Please use the menu below to define what this "+entity.getType()+" is</font>";
341                                 }
342                                 currentCategorySelector.setSelectedFeature(null);
343                         }
344
345                         // Set it as the popup, and make sure it's visible
346                         popupChange.popUp=currentCategorySelector;
347                         currentCategorySelector.visible=true;
348       }
349
350           private function isMultipleEditable(entities:Array):Boolean {
351                 for each(var entity:Entity in entities) {
352                         if(!(entity is Node || entity is Way))
353                                 return false;
354                 }
355                 return true;
356           }
357
358       private function limitType(entity:Entity):String {
359           if      (entity is Node    ) return "point";
360           else if (entity is Way     ) return Way(entity).isArea() ? "area" : "line";
361           else if (entity is Relation) return "relation";
362           return null;
363       }
364
365       private var tabComponents:Object = {};
366
367       private function initialiseEditors():void {
368           editorStack.removeAllChildren();
369           if ( selectedEntity == null || feature == null )
370               return;
371
372           var editorBox:VBox = createEditorBox();
373           editorBox.label = "Basic";
374           editorStack.addChild(editorBox);
375
376           var tabs:Object = {};
377           tabComponents = {};
378
379           for each (var factory:EditorFactory in feature.editors) {
380               if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
381                   var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
382                   if ( editor != null )
383                       editorBox.addChild(editor);
384               }
385               var category:String = factory.category;
386               if (category!='') {
387                       var tab:VBox = tabs[category];
388                       if ( tab == null) {
389                           tab = createEditorBox();
390                           tab.label = category;
391                           editorStack.addChild(tab);
392                           tabs[category] = tab;
393                           tabComponents[tab] = [];
394                       }
395                       var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
396                       if ( catEditor != null )
397                           tabComponents[tab].push(catEditor);
398                       //    tab.addChild(catEditor);
399               }
400           }
401       }
402
403       private function createEditorBox():VBox {
404           var box:VBox = new VBox();
405           box.percentWidth = 100;
406           box.percentHeight = 100;
407           box.styleName = "dndEditorContainer";
408           return box;
409       }
410
411       private function ensureEditorsPopulated(tab:VBox):void {
412           var components:Array = tabComponents[tab];
413           if ( components == null || tab == null || tab.numChildren >= components.length )
414               return;
415           for each (var component:DisplayObject in components ) {
416               tab.addChild(component);
417           }
418       }
419
420         private function initEditorStackUIs():void {
421                 editorStackTabNavigator = new SuperTabNavigator();
422                 editorStackTabNavigator.allowTabSqueezing=false;
423                 editorStackTabNavigator.minTabWidth=10;
424                 editorStackTabNavigator.closePolicy="close_never";
425                 editorStackTabNavigator.scrollSpeed=20;
426                 editorStackTabNavigator.creationPolicy="auto";
427                 editorStackTabNavigator.percentWidth=100;
428                 editorStackTabNavigator.percentHeight=100;
429                 editorStackTabNavigator.styleName="dndStackTab";
430                 editorStackTabNavigator.popUpButtonPolicy="off"
431
432
433                 editorStackAccordion = new Accordion();
434                 editorStackAccordion.percentWidth=100;
435                 editorStackAccordion.percentHeight=100;
436                 editorStackAccordion.creationPolicy="auto";
437                 editorStackAccordion.styleName="dndStackAccordion";
438
439                 setEditorStackUI(true);
440         }
441
442         private function setEditorStackUI(isTabbed:Boolean):void {
443                 var children:Array=[]; var i:uint;
444
445                 if (editorStack) {
446                         // blank existing component
447                         editorStack.removeEventListener("change",editorStackUIChange);
448                         editorStack.removeEventListener("updateComplete",editorStackUIUpdate);
449                         editorStack.removeAllChildren();
450                         editorContainer.removeChildAt(1);
451                 }
452
453                 // replace with new component
454                 editorStack = (isTabbed ? editorStackTabNavigator : editorStackAccordion) as Container;
455                 editorContainer.addChild(editorStack);
456
457                 // re-add children and listeners
458                 initialiseEditors();
459                 editorStack.addEventListener("change",editorStackUIChange);
460                 editorStack.addEventListener("updateComplete",editorStackUIUpdate);
461         }
462
463         private function editorStackUIChange(event:Event):void {
464                 ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox);
465         }
466
467         private function editorStackUIUpdate(event:Event):void {
468                 if (editorStack is SuperTabNavigator) {
469                         var e:SuperTabNavigator = editorStack as SuperTabNavigator;
470                         if (e.selectedIndex<0) { return; }
471                         for (var i:uint=0; i<e.numChildren; i++) {
472                                 e.getTabAt(i).selected=(i==e.selectedIndex);
473                         }
474                 }
475         }
476
477
478         public function togglePanel():void {
479                 if (stack.selectedChild==editorContainer && selectedEntity!=null) {
480                         stack.selectedChild=advancedContainer;
481                 } else if (stack.selectedChild!=editorContainer) {
482                         stack.selectedChild=editorContainer;
483                 }
484         }
485
486         public function selectAdvancedPanel():void {
487                 checkAdvanced();
488                 stack.selectedChild=advancedContainer;
489         }
490
491       private function checkAdvanced():void {
492           if ( selectedEntity != null )
493              setupAdvanced(selectedEntity);
494       }
495
496       private var listeningToRelations:Array = [];
497
498       private function setupAdvanced(entity:Entity):void {
499                 if (!advancedTagGrid) advancedContainer.createComponentsFromDescriptors();      // if Flex hasn't created it, force it
500                 advancedTagGrid.init(entity);
501
502                 if ( entity == null ) {
503                         advancedID.htmlText = "";
504                 } else {
505                         var entityText:String = "xx";
506                         if      ( entity is Node     ) entityText = "Node";
507                         else if ( entity is Way      ) entityText = "Way";
508                         else if ( entity is Relation ) entityText = "Relation";
509                         advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
510                 }
511
512                 removeRelationListeners();
513
514                 if ( entity == null ) {
515                         relationsGrid.dataProvider = null;
516                 } else {
517                         resetRelationsGrid(entity);
518                         entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
519                         entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
520                 }
521       }
522
523           private function setupMultiAdvanced(entity:Entity):void {
524                 multiAdvancedTagGrid.init(entity);
525                 resetRelationsGrid(entity);
526                 entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation, false, 0, true);
527                 entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation, false, 0, true);
528       }
529
530           public function addNewTag():void {
531                 if (stack.selectedChild!=advancedContainer) { return; }
532                 advancedTagGrid.addNewTag();
533           }
534
535       private function addedToRelation(event:RelationMemberEvent):void {
536          resetRelationsGrid(selectedEntity);
537       }
538
539       private function removedFromRelation(event:RelationMemberEvent):void {
540          resetRelationsGrid(selectedEntity);
541       }
542
543       private function removeRelationListeners():void {
544           for each( var rel:Relation in listeningToRelations ) {
545               rel.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
546               rel.removeEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
547               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
548           }
549           listeningToRelations = [];
550           if (relationsGrid) relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
551           if (multiRelationsGrid) multiRelationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
552       }
553
554       private function resetRelationsGrid(entity:Entity):void {
555           removeRelationListeners();
556
557           var instance:DataGrid=relationsGrid;
558           if (entity is EntityCollection) instance=multiRelationsGrid;
559           var memberships:Array = entity.getRelationMemberships();
560           for each (var m:Object in memberships) {
561               m.relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
562               m.relation.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
563               m.relation.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
564               listeningToRelations.push(m.relation);
565           }
566           instance.dataProvider = memberships;
567           instance.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
568       }
569
570       private function relationRoleChanged(event:DataGridEvent):void {
571                 if (event.dataField != 'role') { return; }      // shouldn't really happen
572
573                 var relations:Array=event.currentTarget.dataProvider.toArray();
574                 var props:Object=relations[event.rowIndex];
575
576                 var relation:Relation=props['relation'];
577                 var newRole:String=event.itemRenderer.data['role'];
578
579                 if (selectedEntity is EntityCollection) {
580                         for each (var entity:Entity in EntityCollection(selectedEntity).entities) {
581                                 var indexes:Array=relation.findEntityMemberIndexes(entity);
582                                 for each (var index:int in indexes) {
583                                         relation.setMember(index, new RelationMember(entity,newRole), MainUndoStack.getGlobalStack().addAction);
584                                 }
585                         }
586                 } else {
587                         relation.setMember(props['index'], new RelationMember(selectedEntity,newRole), MainUndoStack.getGlobalStack().addAction);
588                 }
589       }
590
591       private function relationTagChanged(event:TagEvent):void {
592           resetRelationsGrid(selectedEntity);
593       }
594
595       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
596           resetRelationsGrid(selectedEntity);
597       }
598
599       private function checkMembers():void {
600           if (selectedEntity is Relation) {
601             setupMembers(selectedEntity as Relation);
602           }
603       }
604
605       private function setupMembers(rel:Relation):void {
606           var members:Array = [];
607           for (var i:int=0 ; i<rel.length; i++) {
608             var props:Object = {};
609             var member:RelationMember = rel.getMember(i);
610             props["id"] = member.entity.id;
611             props["type"] = member.entity.getType();
612             props["role"] = member.role;
613
614             members.push(props);
615           }
616           membersGrid.dataProvider = members;
617           membersGrid.dataProvider.addEventListener('collectionChange', membersChange);
618       }
619
620       private function membersChange(event:Event):void {
621           // Dropping all the members and re-adding them isn't exactly optimal
622           // but is at least robust for any kind of change.
623           // Figuring out a better way is someone else's FIXME
624
625           var conn:Connection = Connection.getConnectionInstance();
626           var rel:Relation = selectedEntity as Relation
627           var action:CompositeUndoableAction = new CompositeUndoableAction("Rearrange relation members for "+rel);
628
629           // drop members
630           for (var i:int=rel.length-1 ; i>=0; i--) {
631             rel.removeMemberByIndex(i, action.push);
632           }
633
634           // add members in new order
635           for each(var memberObject:Object in membersGrid.dataProvider) {
636             var e:Entity;
637             var id:Number = memberObject.id;
638             if(memberObject.type == 'node') {
639               e = conn.getNode(id);
640             } else if (memberObject.type == 'way') {
641               e = conn.getWay(id);
642             } else if (memberObject.type == 'relation') {
643               e = conn.getRelation(id);
644             }
645             rel.appendMember(new RelationMember(e, memberObject.role), action.push);
646           }
647           MainUndoStack.getGlobalStack().addAction(action);
648       }
649
650       private function editRelation(id:Number):void {
651           var panel:RelationEditorPanel = RelationEditorPanel(
652               PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
653           panel.setRelation(Connection.getConnectionInstance().getRelation(id));
654           PopUpManager.centerPopUp(panel);
655       }
656
657         /** Create relation actions menu */
658
659         public function createRelationMenu(button:PopUpButton):void {
660                 var menu:Menu = new Menu(); 
661                 var dp:Object = [ {label: "Select all members"}, 
662                                                   {label: "Deselect all members"}, 
663                                                   {label: "Add selection to this relation", enabled: false} ]; 
664                 menu.dataProvider = dp; 
665                 menu.addEventListener("itemClick", selectRelationMenu); 
666                 button.popUp = menu;
667         }
668
669         /** Enable 'add selection to...' entry only if some of the selection isn't in the relation.
670             Called each time the menu is clicked. */
671         
672         public function updateRelationMenu(event:Event):void {
673                 rowData=event.target.parent.data;       // this makes it accessible from selectRelationMenu
674                 var menu:Menu = Menu(event.target.popUp);
675                 var enable:Boolean = false;
676                 if (selectedEntity != null && selectedEntity is EntityCollection) {
677                         // Enable only if some entities aren't a member of the relation
678                         enable=!rowData.universal;
679                 }
680                 if (enable==menu.dataProvider[2].enabled) return;
681                 menu.dataProvider[2].enabled=enable;
682                 menu.invalidateList();
683         }
684
685         /** Do the action selected in the relation actions menu */
686
687         public function selectRelationMenu(event:MenuEvent):void {
688                 var rel:Relation=rowData.relation;
689                 var entities:Array;
690                 var controller:EditController=Application.application.theController;
691                 switch (event.index) {
692                         case 0: // Select all members
693                                 entities=selectedEntity.entities.concat(rel.memberEntities);
694                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return arr.indexOf(e) == i } );      // remove duplicates
695                                 // ** FIXME: This is a really horrible way of changing the controller state
696                                 controller.setState(controller.findStateForSelection(entities));
697                                 break;
698
699                         case 1: // Deselect all members
700                                 entities=selectedEntity.entities;
701                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return !e.hasParent(rel) } );
702                                 controller.setState(controller.findStateForSelection(entities));
703                                 break;
704
705                         case 2: // Add selection to this relation
706                                 var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
707                                 for each (var entity:Entity in selectedEntity.entities) {
708                                         if (!entity.hasParent(rel)) {
709                                                 rel.appendMember(new RelationMember(entity,''), undo.push);
710                                         }
711                                 }
712                                 MainUndoStack.getGlobalStack().addAction(undo);
713                                 break;
714                 }
715         }
716
717       private function tagChanged(event:TagEvent):void {
718           refreshFeatureIcon();
719       }
720
721       public function loadFeatures():void {
722           mapFeatures = MapFeatures.getInstance();
723           stack.removeChild(membersVBox); // remove by default, will be added if relation
724       }
725
726       /** Open up a new browser page, showing the help page as defined in Map Features XML file .*/
727       public function openDescription():void {
728           if ( feature != null && feature.hasHelpURL() )
729               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
730       }
731
732       public function addToRelation():void {
733           new RelationSelectPanel().init(selectedEntity,new Object());
734       }
735
736       private function removeFromRelation(id:Number, index:int=-1):void {
737                 var rel:Relation=Connection.getConnectionInstance().getRelation(id);
738                 if (index>-1) {
739                         rel.removeMemberByIndex(index, MainUndoStack.getGlobalStack().addAction);
740                 } else if (selectedEntity is EntityCollection) {
741                         var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
742                         for each (var e:Entity in EntityCollection(selectedEntity).entities) rel.removeMember(e,undo.push);
743                         MainUndoStack.getGlobalStack().addAction(undo);
744                 }
745       }
746
747       public function changeFeatureType(event:Event):void {
748           if ( selectedEntity == null )
749               return;
750
751           UIComponent.suspendBackgroundProcessing();
752           var newFeature:Feature = currentCategorySelector.selectedType;
753           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
754           var action:CompositeUndoableAction = new CompositeUndoableAction(
755                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
756                   selectedEntity.suspend();
757
758           // remove tags from the current feature
759           if ( feature != null ) {
760               for each( var oldtag:Object in feature.tags ) {
761                   selectedEntity.setTag(oldtag["k"], null, action.push);
762               }
763           }
764
765           // set tags for new feature
766           if ( newFeature != null ) {
767               for each( var newtag:Object in newFeature.tags ) {
768                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
769               }
770           }
771
772                   selectedEntity.resume();
773           undoStack(action);
774           popupChange.close();
775           initialiseEditors();
776           UIComponent.resumeBackgroundProcessing();
777       }
778
779         private function resizePOIGrid(event:Event):void {
780                 var rows:Number=event.target.dataProvider.length/event.target.columnCount;
781                 if (rows!=Math.floor(rows)) { rows=Math.floor(rows+1); }
782                 event.target.height=rows*(event.target.rowHeight+1);
783         }
784   ]]></mx:Script>
785 </mx:VBox>
786