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