ADD support for non-drag-and-droppable point features. These are specified as <point...
[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.image}" 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" creationComplete="initFeatureBox()" openAlways="true" width="100%" styleName="dndTagPopUpMenu"/>
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="openEntityPage()">
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
214       import mx.collections.*;
215       import mx.containers.*;
216       import mx.events.*;
217       import mx.core.*;
218       import mx.managers.PopUpManager;
219       import mx.controls.Menu;
220       import flash.geom.Point;
221       import flash.net.*;
222       import mx.events.DragEvent;
223       import mx.managers.DragManager;
224       import mx.core.DragSource;
225       import flexlib.containers.SuperTabNavigator;
226
227       private static const dndPrompt:String="Add new points by dragging them onto the map";
228
229       private var editorStackTabNavigator:SuperTabNavigator;
230       private var editorStackAccordion:Accordion;
231       [Bindable] private var editorStack:Container;
232
233       public var mapFeatures:MapFeatures;
234       private var selectedEntity:Entity;
235       private var tw:CategorySelector = null;
236       private var feature:Feature = null;
237
238       private var rowData:Object;               // relation membership reference, needed so it's accessible from relation actions menu
239
240           public function setEntity(entities:Array, layer:VectorLayer=null):void {
241                 UIComponent.suspendBackgroundProcessing();
242
243                 var firstSelected:Entity=null;
244                 if (entities.length==1) { firstSelected=entities[0]; }
245
246                 if (selectedEntity!=firstSelected && selectedEntity!=null) {
247                         selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
248                         selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
249                         selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
250                 }
251
252                 if (entities.length==0) {
253                         // Nothing selected, so show drag-and-drop panel
254                         sidebar.selectedChild = dndPanel;
255
256                 } else if (entities.length==1) {
257                         // Single entity selected, so show tag panel
258                         selectedEntity=firstSelected;
259                         if (selectedEntity!=null) { selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged); }
260                         if (advancedID!=null) { setupAdvanced(firstSelected); }
261                         if (firstSelected is Relation) { stack.addChild(membersVBox); }
262             if (selectedEntity is Marker && layer is BugLayer) {
263               bugPanelContents.init(selectedEntity, layer);
264               sidebar.selectedChild = bugPanel;
265             } else if (selectedEntity is Marker) {
266               markerPanelContents.init(selectedEntity, layer);
267               sidebar.selectedChild = markerPanel;
268             } else {
269               refreshFeatureIcon();
270               initialiseEditors();
271               sidebar.selectedChild = tagsPanel;
272             }
273
274                 } else if(isMultipleEditable(entities)) {
275                         selectedEntity = new EntityCollection(entities);
276                         selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged);
277             sidebar.selectedChild = multiplePanel;
278                         setupMultiAdvanced(selectedEntity);
279
280                 } else {
281                         //The selection contains elements which can't be edited all together.
282                         sidebar.selectedChild = multipleInvalidPanel;
283                 }
284                 UIComponent.resumeBackgroundProcessing();
285       }
286
287       private function refreshFeatureIcon():void {
288           var oldFeature:Feature = feature;
289           feature = selectedEntity == null ? null : mapFeatures.findMatchingFeature(selectedEntity);
290           if ( feature != oldFeature ) {
291               if ( oldFeature != null )
292                   oldFeature.removeEventListener("imageChanged", featureImageChanged);
293               if ( feature != null )
294                   feature.addEventListener("imageChanged", featureImageChanged);
295           }
296
297           if ( feature != null && feature.name != null ) {
298               setFeatureIcon(selectedEntity, feature);
299           } else {
300               blankFeatureIcon(selectedEntity);
301           }
302       }
303
304       private function featureImageChanged(event:Event):void {
305           setFeatureIcon(selectedEntity, feature);
306       }
307
308       private function setFeatureIcon(entity:Entity, feature:Feature):void {
309           //blankFeatureIcon(entity);
310
311           iconImage.source = feature.image;
312
313           var txt:String = feature.htmlDetails(entity);
314           iconText.htmlText = txt;
315           popupChange.label = feature.name;
316           setLimitTypes(entity);
317           tw.setSelectedFeature(feature);
318           helpLabel.visible = feature.hasHelpURL();
319       }
320
321           private function isMultipleEditable(entities:Array):Boolean {
322                 for each(var entity:Entity in entities) {
323                         if(!(entity is Node || entity is Way))
324                                 return false;
325                 }
326                 return true;
327           }
328
329       private function setLimitTypes(entity:Entity):void {
330           var type:String = null;
331           if ( entity is Node )
332               type = "point";
333           else if ( entity is Way )
334               type = Way(entity).isArea() ? "area" : "line";
335           else if ( entity is Relation )
336               type = "relation";
337           tw.setLimitTypes(type);
338       }
339
340       private function blankFeatureIcon(entity:Entity):void {
341           iconImage.source = null;
342           popupChange.label = "unknown";
343           setLimitTypes(entity);
344                   if (entity == null) {
345                         iconText.htmlText = "<i>Nothing selected</i>";
346             tw.setNoSelectedFeature();
347                   } else if (entity.hasTags()) {
348                         iconText.htmlText = "<b>Not recognised</b><br/><font size='10pt'>Try looking at the tags under the advanced properties</font>";
349             tw.setSelectedFeature(null);
350                   } else {
351                         iconText.htmlText = "<b>No tags set</b><br/><font size='10pt'>Please use the menu below to define what this "+entity.getType()+" is</font>";
352             tw.setSelectedFeature(null);
353           }
354           helpLabel.visible = false;
355       }
356
357       private var tabComponents:Object = {};
358
359       private function initialiseEditors():void {
360           editorStack.removeAllChildren();
361           if ( selectedEntity == null || feature == null )
362               return;
363
364           var editorBox:VBox = createEditorBox();
365           editorBox.label = "Basic";
366           editorStack.addChild(editorBox);
367
368           var tabs:Object = {};
369           tabComponents = {};
370
371           for each (var factory:EditorFactory in feature.editors) {
372               if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
373                   var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
374                   if ( editor != null )
375                       editorBox.addChild(editor);
376               }
377               var category:String = factory.category;
378               if (category!='') {
379                       var tab:VBox = tabs[category];
380                       if ( tab == null) {
381                           tab = createEditorBox();
382                           tab.label = category;
383                           editorStack.addChild(tab);
384                           tabs[category] = tab;
385                           tabComponents[tab] = [];
386                       }
387                       var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
388                       if ( catEditor != null )
389                           tabComponents[tab].push(catEditor);
390                       //    tab.addChild(catEditor);
391               }
392           }
393       }
394
395       private function createEditorBox():VBox {
396           var box:VBox = new VBox();
397           box.percentWidth = 100;
398           box.percentHeight = 100;
399           box.styleName = "dndEditorContainer";
400           return box;
401       }
402
403       private function ensureEditorsPopulated(tab:VBox):void {
404           var components:Array = tabComponents[tab];
405           if ( components == null || tab == null || tab.numChildren >= components.length )
406               return;
407           for each (var component:DisplayObject in components ) {
408               tab.addChild(component);
409           }
410       }
411
412         private function initEditorStackUIs():void {
413                 editorStackTabNavigator = new SuperTabNavigator();
414                 editorStackTabNavigator.allowTabSqueezing=false;
415                 editorStackTabNavigator.minTabWidth=10;
416                 editorStackTabNavigator.closePolicy="close_never";
417                 editorStackTabNavigator.scrollSpeed=20;
418                 editorStackTabNavigator.creationPolicy="auto";
419                 editorStackTabNavigator.percentWidth=100;
420                 editorStackTabNavigator.percentHeight=100;
421                 editorStackTabNavigator.styleName="dndStackTab";
422                 editorStackTabNavigator.popUpButtonPolicy="off"
423
424
425                 editorStackAccordion = new Accordion();
426                 editorStackAccordion.percentWidth=100;
427                 editorStackAccordion.percentHeight=100;
428                 editorStackAccordion.creationPolicy="auto";
429                 editorStackAccordion.styleName="dndStackAccordion";
430
431                 setEditorStackUI(true);
432         }
433
434         private function setEditorStackUI(isTabbed:Boolean):void {
435                 var children:Array=[]; var i:uint;
436
437                 if (editorStack) {
438                         // blank existing component
439                         editorStack.removeEventListener("change",editorStackUIChange);
440                         editorStack.removeEventListener("updateComplete",editorStackUIUpdate);
441                         editorStack.removeAllChildren();
442                         editorContainer.removeChildAt(1);
443                 }
444
445                 // replace with new component
446                 editorStack = (isTabbed ? editorStackTabNavigator : editorStackAccordion) as Container;
447                 editorContainer.addChild(editorStack);
448
449                 // re-add children and listeners
450                 initialiseEditors();
451                 editorStack.addEventListener("change",editorStackUIChange);
452                 editorStack.addEventListener("updateComplete",editorStackUIUpdate);
453         }
454
455         private function editorStackUIChange(event:Event):void {
456                 ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox);
457         }
458
459         private function editorStackUIUpdate(event:Event):void {
460                 if (editorStack is SuperTabNavigator) {
461                         var e:SuperTabNavigator = editorStack as SuperTabNavigator;
462                         if (e.selectedIndex<0) { return; }
463                         for (var i:uint=0; i<e.numChildren; i++) {
464                                 e.getTabAt(i).selected=(i==e.selectedIndex);
465                         }
466                 }
467         }
468
469
470         public function togglePanel():void {
471                 if (stack.selectedChild==editorContainer && selectedEntity!=null) {
472                         stack.selectedChild=advancedContainer;
473                 } else if (stack.selectedChild!=editorContainer) {
474                         stack.selectedChild=editorContainer;
475                 }
476         }
477
478         public function selectAdvancedPanel():void {
479                 checkAdvanced();
480                 stack.selectedChild=advancedContainer;
481         }
482
483       private function checkAdvanced():void {
484           if ( selectedEntity != null )
485              setupAdvanced(selectedEntity);
486       }
487
488       /**
489       * When you enter a new tag and press enter, the focus moves to the add button
490       * Adding an event listener to the button and listening for + means that you
491       * can add two consecutive tags with the same keypress. This relies on focus
492       * moving to the "add" button, though, so it's not robust to rearranging the UI.
493       */
494       private function advancedAddButtonKeyboardEvent(event:KeyboardEvent):void {
495           switch (event.keyCode) {
496             case 187:   addNewTag(); break;                          // + - add tag
497             case 107:   addNewTag(); break;                          // numpad plus
498           }
499       }
500
501       private var listeningToRelations:Array = [];
502
503       private function setupAdvanced(entity:Entity):void {
504                 if (!advancedTagGrid) advancedContainer.createComponentsFromDescriptors();      // if Flex hasn't created it, force it
505                 advancedTagGrid.init(entity);
506         advancedAddButton.addEventListener(KeyboardEvent.KEY_DOWN, advancedAddButtonKeyboardEvent, false, 0, true);
507         advancedDeleteButton.addEventListener(KeyboardEvent.KEY_DOWN, advancedAddButtonKeyboardEvent, false, 0, true);
508
509                 if ( entity == null ) {
510                         advancedID.htmlText = "";
511                 } else {
512                         var entityText:String = "xx";
513                         if      ( entity is Node     ) entityText = "Node";
514                         else if ( entity is Way      ) entityText = "Way";
515                         else if ( entity is Relation ) entityText = "Relation";
516                         advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
517                 }
518
519                 removeRelationListeners();
520
521                 if ( entity == null ) {
522                         relationsGrid.dataProvider = null;
523                 } else {
524                         resetRelationsGrid(entity);
525                         entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
526                         entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
527                 }
528       }
529
530           private function setupMultiAdvanced(entity:Entity):void {
531                 multiAdvancedTagGrid.init(entity);
532                 resetRelationsGrid(entity);
533                 entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation, false, 0, true);
534                 entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation, false, 0, true);
535       }
536
537           public function addNewTag():void {
538                 if (stack.selectedChild!=advancedContainer) { return; }
539                 advancedTagGrid.addNewTag();
540           }
541
542       private function addedToRelation(event:RelationMemberEvent):void {
543          resetRelationsGrid(selectedEntity);
544       }
545
546       private function removedFromRelation(event:RelationMemberEvent):void {
547          resetRelationsGrid(selectedEntity);
548       }
549
550       private function removeRelationListeners():void {
551           for each( var rel:Relation in listeningToRelations ) {
552               rel.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
553               rel.removeEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
554               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
555           }
556           listeningToRelations = [];
557           if (relationsGrid) relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
558           if (multiRelationsGrid) multiRelationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
559       }
560
561       private function resetRelationsGrid(entity:Entity):void {
562           removeRelationListeners();
563
564           var instance:DataGrid=relationsGrid;
565           if (entity is EntityCollection) instance=multiRelationsGrid;
566           var memberships:Array = entity.getRelationMemberships();
567           for each (var m:Object in memberships) {
568               m.relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
569               m.relation.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
570               m.relation.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
571               listeningToRelations.push(m.relation);
572           }
573           instance.dataProvider = memberships;
574           instance.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
575       }
576
577       private function relationRoleChanged(event:DataGridEvent):void {
578                 if (event.dataField != 'role') { return; }      // shouldn't really happen
579
580                 var relations:Array=event.currentTarget.dataProvider.toArray();
581                 var props:Object=relations[event.rowIndex];
582
583                 var relation:Relation=props['relation'];
584                 var newRole:String=event.itemRenderer.data['role'];
585
586                 if (selectedEntity is EntityCollection) {
587                         for each (var entity:Entity in EntityCollection(selectedEntity).entities) {
588                                 var indexes:Array=relation.findEntityMemberIndexes(entity);
589                                 for each (var index:int in indexes) {
590                                         relation.setMember(index, new RelationMember(entity,newRole));
591                                 }
592                         }
593                 } else {
594                         relation.setMember(props['index'], new RelationMember(selectedEntity,newRole));
595                 }
596       }
597
598       private function relationTagChanged(event:TagEvent):void {
599           resetRelationsGrid(selectedEntity);
600       }
601
602       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
603           resetRelationsGrid(selectedEntity);
604       }
605
606       private function checkMembers():void {
607           if (selectedEntity is Relation) {
608             setupMembers(selectedEntity as Relation);
609           }
610       }
611
612       private function setupMembers(rel:Relation):void {
613           var members:Array = [];
614           for (var i:int=0 ; i<rel.length; i++) {
615             var props:Object = {};
616             var member:RelationMember = rel.getMember(i);
617             props["id"] = member.entity.id;
618             props["type"] = member.entity.getType();
619             props["role"] = member.role;
620
621             members.push(props);
622           }
623           membersGrid.dataProvider = members;
624           membersGrid.dataProvider.addEventListener('collectionChange', membersChange);
625       }
626
627       private function membersChange(event:Event):void {
628           // Dropping all the members and re-adding them isn't exactly optimal
629           // but is at least robust for any kind of change.
630           // Figuring out a better way is someone else's FIXME
631
632           var conn:Connection = Connection.getConnectionInstance();
633           var rel:Relation = selectedEntity as Relation
634           var action:CompositeUndoableAction = new CompositeUndoableAction("Rearrange relation members for "+rel);
635
636           // drop members
637           for (var i:int=rel.length-1 ; i>=0; i--) {
638             rel.removeMemberByIndex(i, action.push);
639           }
640
641           // add members in new order
642           for each(var memberObject:Object in membersGrid.dataProvider) {
643             var e:Entity;
644             var id:Number = memberObject.id;
645             if(memberObject.type == 'node') {
646               e = conn.getNode(id);
647             } else if (memberObject.type == 'way') {
648               e = conn.getWay(id);
649             } else if (memberObject.type == 'relation') {
650               e = conn.getRelation(id);
651             }
652             rel.appendMember(new RelationMember(e, memberObject.role), action.push);
653           }
654           MainUndoStack.getGlobalStack().addAction(action);
655       }
656
657       private function editRelation(id:Number):void {
658           var panel:RelationEditorPanel = RelationEditorPanel(
659               PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
660           panel.setRelation(Connection.getConnectionInstance().getRelation(id));
661           PopUpManager.centerPopUp(panel);
662       }
663
664         /** Create relation actions menu */
665
666         public function createRelationMenu(button:PopUpButton):void {
667                 var menu:Menu = new Menu(); 
668                 var dp:Object = [ {label: "Select all members"}, 
669                                                   {label: "Deselect all members"}, 
670                                                   {label: "Add selection to this relation", enabled: false} ]; 
671                 menu.dataProvider = dp; 
672                 menu.addEventListener("itemClick", selectRelationMenu); 
673                 button.popUp = menu;
674         }
675
676         /** Enable 'add selection to...' entry only if some of the selection isn't in the relation.
677             Called each time the menu is clicked. */
678         
679         public function updateRelationMenu(event:Event):void {
680                 rowData=event.target.parent.data;       // this makes it accessible from selectRelationMenu
681                 var menu:Menu = Menu(event.target.popUp);
682                 var enable:Boolean = false;
683                 if (selectedEntity != null && selectedEntity is EntityCollection) {
684                         // Enable only if some entities aren't a member of the relation
685                         enable=!rowData.universal;
686                 }
687                 if (enable==menu.dataProvider[2].enabled) return;
688                 menu.dataProvider[2].enabled=enable;
689                 menu.invalidateList();
690         }
691
692         /** Do the action selected in the relation actions menu */
693
694         public function selectRelationMenu(event:MenuEvent):void {
695                 var rel:Relation=rowData.relation;
696                 var entities:Array;
697                 var controller:EditController=Application.application.theController;
698                 switch (event.index) {
699                         case 0: // Select all members
700                                 entities=selectedEntity.entities.concat(rel.memberEntities);
701                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return arr.indexOf(e) == i } );      // remove duplicates
702                                 // ** FIXME: This is a really horrible way of changing the controller state
703                                 controller.setState(controller.findStateForSelection(entities));
704                                 break;
705
706                         case 1: // Deselect all members
707                                 entities=selectedEntity.entities;
708                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return !e.hasParent(rel) } );
709                                 controller.setState(controller.findStateForSelection(entities));
710                                 break;
711
712                         case 2: // Add selection to this relation
713                                 var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
714                                 for each (var entity:Entity in selectedEntity.entities) {
715                                         if (!entity.hasParent(rel)) {
716                                                 rel.appendMember(new RelationMember(entity,''), undo.push);
717                                         }
718                                 }
719                                 MainUndoStack.getGlobalStack().addAction(undo);
720                                 break;
721                 }
722         }
723
724       private function tagChanged(event:TagEvent):void {
725               if(selectedEntity != null && selectedEntity is EntityCollection) {
726                         setupMultiAdvanced(selectedEntity);
727                     return;
728                   }
729
730           refreshFeatureIcon();
731           // ** FIXME - changing tags on Advanced tab should update simple view
732           // (but putting initialiseEditors here breaks other stuff, because it causes
733           // the Basic pane to be selected)
734
735           // if the advancedTagGrid has already been set up, it needs to be refreshed.
736           // FIXME make this better, maybe advancedTagGrid should be event listening.
737           if(advancedContainer.initialized) {
738             checkAdvanced();
739           }
740       }
741
742       public function loadFeatures():void {
743           mapFeatures = MapFeatures.getInstance();
744           stack.removeChild(membersVBox); // remove by default, will be added if relation
745       }
746
747       /** Open up a new browser page, showing the help page as defined in Map Features XML file .*/
748       public function openDescription():void {
749           if ( feature != null && feature.hasHelpURL() )
750               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
751       }
752
753       /** Open up a new browser page showing OSM's view of the current entity. */
754       public function openEntityPage():void {
755           if (selectedEntity != null && selectedEntity.id >= 0) {
756               // This is slightly hard-coded, but not drastically. The ../s could be changed for string manipulation of the apiBase
757               var urlBase:String = Connection.getConnectionInstance().apiBase + '../../browse/'
758               navigateToURL(new URLRequest(urlBase+selectedEntity.getType()+'/'+selectedEntity.id), "potlatch_browse");
759           }
760       }
761
762       public function addToRelation():void {
763           new RelationSelectPanel().init(selectedEntity,new Object());
764       }
765
766       private function removeFromRelation(id:Number, index:int=-1):void {
767                 var rel:Relation=Connection.getConnectionInstance().getRelation(id);
768                 if (index>-1) {
769                         rel.removeMemberByIndex(index, MainUndoStack.getGlobalStack().addAction);
770                 } else if (selectedEntity is EntityCollection) {
771                         var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
772                         for each (var e:Entity in EntityCollection(selectedEntity).entities) rel.removeMember(e,undo.push);
773                         MainUndoStack.getGlobalStack().addAction(undo);
774                 }
775       }
776
777       public function initFeatureBox():void {
778           tw = new CategorySelector();
779           tw.addEventListener("selectedType", changeFeatureType);
780           popupChange.popUp = tw;
781       }
782
783       public function changeFeatureType(event:Event):void {
784           if ( selectedEntity == null )
785               return;
786
787           UIComponent.suspendBackgroundProcessing();
788           var newFeature:Feature = tw.selectedType;
789           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
790           var action:CompositeUndoableAction = new CompositeUndoableAction(
791                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
792                   selectedEntity.suspend();
793
794           // remove tags from the current feature
795           if ( feature != null ) {
796               for each( var oldtag:Object in feature.tags ) {
797                   selectedEntity.setTag(oldtag["k"], null, action.push);
798               }
799           }
800
801           // set tags for new feature
802           if ( newFeature != null ) {
803               for each( var newtag:Object in newFeature.tags ) {
804                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
805               }
806           }
807
808                   selectedEntity.resume();
809           undoStack(action);
810           popupChange.close();
811           initialiseEditors();
812           UIComponent.resumeBackgroundProcessing();
813       }
814
815         private function resizePOIGrid(event:Event):void {
816                 var rows:Number=event.target.dataProvider.length/event.target.columnCount;
817                 if (rows!=Math.floor(rows)) { rows=Math.floor(rows+1); }
818                 event.target.height=rows*(event.target.rowHeight+1);
819         }
820   ]]></mx:Script>
821 </mx:VBox>
822