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