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