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