When changing feature, save tags that have editors in new feature
[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 TabNavigator &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   <!-- merge tags from background layer -->
215
216   <mx:VBox id="backgroundMergePanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
217     <sidepanel:BackgroundMergePanel id="backgroundMergePanelContents" width="100%" />
218   </mx:VBox>
219
220 </mx:ViewStack>
221
222   <fx:Script><![CDATA[
223       import net.systemeD.halcyon.connection.*;
224       import net.systemeD.halcyon.MapPaint;
225       import net.systemeD.potlatch2.EditController;
226       import net.systemeD.potlatch2.mapfeatures.*;
227       import net.systemeD.potlatch2.utils.*;
228       import net.systemeD.controls.CollapsiblePanel;
229
230       import mx.collections.*;
231       import mx.containers.*;
232       import mx.events.*;
233       import mx.core.*;
234       import mx.managers.PopUpManager;
235       import mx.controls.Menu;
236       import mx.controls.Alert;
237       import flash.geom.Point;
238       import flash.net.*;
239       import mx.events.DragEvent;
240       import mx.managers.DragManager;
241       import mx.core.DragSource;
242       import mx.controls.TabBar;
243 //    import flexlib.containers.SuperTabNavigator;
244
245       [Bindable] [Embed(source="../../../embedded/tab_basic.png"       )] private var tabIconBasic:Class;
246       [Bindable] [Embed(source="../../../embedded/tab_address.png"     )] private var tabIconAddress:Class;
247       [Bindable] [Embed(source="../../../embedded/tab_cycle.png"       )] private var tabIconCycle:Class;
248       [Bindable] [Embed(source="../../../embedded/tab_details.png"     )] private var tabIconDetails:Class;
249       [Bindable] [Embed(source="../../../embedded/tab_restrictions.png")] private var tabIconRestrictions:Class;
250       [Bindable] [Embed(source="../../../embedded/tab_transport.png"   )] private var tabIconTransport:Class;
251       [Bindable] [Embed(source="../../../embedded/tab_walk.png"        )] private var tabIconWalk:Class;
252       private var tabIcons:Object= { Basic:tabIconBasic, Details:tabIconDetails, Address:tabIconAddress, Walk:tabIconWalk, Cycle:tabIconCycle, 
253                                          Transport:tabIconTransport, Restrictions:tabIconRestrictions};
254
255       [Bindable]
256       public var dndPrompt:String="Add new points by dragging them onto the map";
257
258       private var editorStackTabNavigator:TabNavigator;
259       private var editorStackAccordion:Accordion;
260       [Bindable] private var editorStack:Container;
261
262       public var mapFeatures:MapFeatures;
263       public var controller:EditController;
264       private var selectedEntity:Entity;
265       private var connection:Connection;
266       private var currentCategorySelector:CategorySelector;
267       private var categorySelectors:Object = {};        // hash of categorySelectors for each limitType
268       private var feature:Feature = null;
269
270       private var rowData:Object;               // relation membership reference, needed so it's accessible from relation actions menu
271
272           public function setEntity(entities:Array, layer:MapPaint=null):void {
273                 UIComponent.suspendBackgroundProcessing();
274                 connection=null;
275
276                 var firstSelected:Entity=null;
277                 if (entities.length==1) { firstSelected=entities[0]; }
278
279                 if (selectedEntity!=firstSelected && selectedEntity!=null) {
280                         selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
281                         selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
282                         selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
283                 }
284
285                 if (entities.length==0) {
286                         // Nothing selected, so show drag-and-drop panel
287                         sidebar.selectedChild = dndPanel;
288
289                 } else if (entities.length==1) {
290                         // Single entity selected, so show tag panel
291                         selectedEntity=firstSelected;
292                         connection=firstSelected.connection;
293                         if (selectedEntity!=null) { selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged); }
294                         if (advancedID!=null) { setupAdvanced(firstSelected); }
295                         if (firstSelected is Relation) { stack.addChild(membersVBox); }
296             if (selectedEntity is Marker && connection is BugConnection) {
297               bugPanelContents.init(selectedEntity, BugConnection(connection));
298               sidebar.selectedChild = bugPanel;
299             } else if (selectedEntity is Marker) {
300               markerPanelContents.init(selectedEntity, layer);
301               sidebar.selectedChild = markerPanel;
302             } else if (connection is SnapshotConnection) {
303               backgroundPanelContents.init(selectedEntity, layer);
304               sidebar.selectedChild = backgroundPanel;
305             } else {
306               refreshFeatureIcon();
307               initialiseEditors();
308               sidebar.selectedChild = tagsPanel;
309             }
310
311         } else if (entities.length==2
312                       && xor(entities[0].connection is SnapshotConnection, entities[1].connection is SnapshotConnection)
313                       && xor(!controller.map.getLayerForEntity(entities[0]).isBackground, !controller.map.getLayerForEntity(entities[1]).isBackground) ) {
314             backgroundMergePanelContents.init(entities);
315             sidebar.selectedChild = backgroundMergePanel;
316
317                 } else if(isMultipleEditable(entities)) {
318                         selectedEntity = new EntityCollection(entities);
319                         selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged);
320             sidebar.selectedChild = multiplePanel;
321                         setupMultiAdvanced(selectedEntity);
322                         connection=entities[0].connection;
323                         
324                 } else {
325                         //The selection contains elements which can't be edited all together.
326                         sidebar.selectedChild = multipleInvalidPanel;
327                 }
328                 UIComponent.resumeBackgroundProcessing();
329       }
330
331       private function xor(a:Boolean, b:Boolean):Boolean {
332           return ( a || b) && !(a && b);
333       }
334
335       private function refreshFeatureIcon():void {
336           var oldFeature:Feature = feature;
337           feature = selectedEntity == null ? null : mapFeatures.findMatchingFeature(selectedEntity);
338           if ( feature != oldFeature ) {
339               if ( oldFeature != null )
340                   oldFeature.removeEventListener("imageChanged", featureImageChanged);
341               if ( feature != null )
342                   feature.addEventListener("imageChanged", featureImageChanged);
343           }
344           setCategorySelector(selectedEntity, feature);
345       }
346
347       private function featureImageChanged(event:Event):void {
348           setCategorySelector(selectedEntity, feature);
349       }
350
351       /** Set the icon, categorySelector and help text for the current entity. */
352       private function setCategorySelector(entity:Entity, feature:Feature):void {
353                         // Remove the "user has selected something" event listener from previous categorySelector,
354                         // and make it invisible because Flex is crap at updating click areas otherwise
355                         if (currentCategorySelector) { 
356                                 currentCategorySelector.removeEventListener("selectedType", changeFeatureType);
357                                 currentCategorySelector.visible=false;
358                         }
359                         
360                         // Have we cached the categorySelector for this limitType? If not, create one
361                         var lt:String=limitType(entity);
362                         if (!categorySelectors[lt]) {
363                                 categorySelectors[lt]=new CategorySelector();
364                                 categorySelectors[lt].setLimitTypes(lt);
365                         }
366                         currentCategorySelector=categorySelectors[lt];
367                         currentCategorySelector.addEventListener("selectedType", changeFeatureType, false, 0, true);
368
369                         // Update surrounding icon/text display
370                         if (feature) {
371                                 iconImage.source = feature.image;
372                                 iconText.htmlText = feature.htmlDetails(entity);
373                                 popupChange.label = feature.name;
374                                 helpLabel.visible = feature.hasHelpURL();
375                                 currentCategorySelector.setSelectedFeature(feature);
376                         } else {
377                                 iconImage.source = null;
378                                 popupChange.label = "unknown";
379                                 helpLabel.visible = false;
380                                 if (entity==null) {
381                                         iconText.htmlText = "<i>Nothing selected</i>";
382                                 } else if (entity.hasTags()) {
383                                         iconText.htmlText = "<b>Not recognised</b><br/><font size='10pt'>Try looking at the tags under the advanced properties</font>";
384                                 } else {
385                                         iconText.htmlText = "<b>No tags set</b><br/><font size='10pt'>Please use the menu below to define what this "+entity.getType()+" is</font>";
386                                 }
387                                 currentCategorySelector.setSelectedFeature(null);
388                         }
389
390                         // Set it as the popup, and make sure it's visible
391                         popupChange.popUp=currentCategorySelector;
392                         currentCategorySelector.visible=true;
393       }
394
395           private function isMultipleEditable(entities:Array):Boolean {
396                 for each(var entity:Entity in entities) {
397                         if(!(entity is Node || entity is Way))
398                                 return false;
399                 }
400                 return true;
401           }
402
403       private function limitType(entity:Entity):String {
404           if      (entity is Node    ) return "point";
405           else if (entity is Way     ) return Way(entity).isArea() ? "area" : "line";
406           else if (entity is Relation) return "relation";
407           return null;
408       }
409
410       private var tabComponents:Object = {};
411       private var subpanelComponents:Object = {};
412
413       private function initialiseEditors():void {
414                 editorStack.removeAllChildren();
415                 if ( selectedEntity == null || feature == null )
416                         return;
417
418                 var basicEditorBox:VBox = createEditorBox();
419                 basicEditorBox.label = "Basic";
420                 basicEditorBox.icon=tabIconBasic;
421                 editorStack.addChild(basicEditorBox);
422
423                 var tabs:Object = {};
424                 var tabList:Array = [];
425                 tabComponents = {};
426                 var subpanels:Object = {};
427                 subpanelComponents = {};
428
429                 // First create the tabs
430                 for each (var factory:EditorFactory in feature.editors) {
431                         var category:String = factory.category;
432                         if (category!='') {
433                                 var tab:VBox = tabs[category];
434                                 if ( tab == null) {
435                                         tab = createEditorBox();
436                                         tab.label = category;
437                                         if (tabIcons[category]) tab.icon=tabIcons[category];
438                                         tabs[category] = tab;
439                                         tabList.push(tab);      
440                                 }
441                         }
442                 }
443
444                 // Put the tabs on-screen in order
445                 tabList.sort(sortCategories,16);
446                 for each (tab in tabList) {
447                         editorStack.addChild(tab);
448                         tabComponents[tab] = [];
449                 }
450
451                 // Then add the individual editors to them
452                 for each (factory in feature.editors) {
453
454                         // Add to basic editor box first
455                         if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
456                                 var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
457                                 if (editor) basicEditorBox.addChild(editor);
458                         }
459
460                         // Then prepare to add to category panel
461                         category=factory.category;
462                         if (factory.category=='') continue;
463                         var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
464                         if (!catEditor) continue;
465                         tab=tabs[category];
466                         
467                         // Create subcategory panel if needed
468                         if (factory.subcategory) {
469                                 var subcategory:String = factory.subcategory;
470                                 if (!subpanels[category]) { subpanels[category]={}; }
471                                 var subpanel:CollapsiblePanel = subpanels[category][subcategory];
472                                 if (!subpanel) {
473                                         subpanel=new CollapsiblePanel(false);
474                                         subpanel.percentWidth=100;
475                                         subpanel.styleName="subcategoryPanel";
476                                         subpanel.title=subcategory;
477                                         subpanels[category][subcategory]=subpanel;
478                                         tabComponents[tab].push(subpanel);
479                                 }
480                                 subpanel.addChild(catEditor);
481                         } else {
482                                 tabComponents[tab].push(catEditor);
483                         }
484                 }
485       }
486
487         // ** FIXME: Order probably shouldn't be hard-coded, but configurable
488         private static var categoryOrder:Array=["Restrictions","Transport","Cycle","Walk","Address","Details"]; // reverse order
489         private function sortCategories(a:VBox,b:VBox):int {
490                 var a1:int=categoryOrder.indexOf(a.label);
491                 var a2:int=categoryOrder.indexOf(b.label);
492                 if (a1<a2) { return 1; }
493                 else if (a1>a2) { return -1; }
494                 return 0;
495         }
496         
497       private function createEditorBox():VBox {
498           var box:VBox = new VBox();
499           box.percentWidth = 100;
500           box.percentHeight = 100;
501           box.styleName = "dndEditorContainer";
502           return box;
503       }
504
505       private function ensureEditorsPopulated(tab:VBox):void {
506           var components:Array = tabComponents[tab];
507           if ( components == null || tab == null || tab.numChildren >= components.length )
508               return;
509           for each (var component:DisplayObject in components ) {
510               tab.addChild(component);
511           }
512       }
513
514         private function initEditorStackUIs():void {
515                 editorStackTabNavigator = new TabNavigator();
516 //              editorStackTabNavigator.allowTabSqueezing=false;
517 //              editorStackTabNavigator.minTabWidth=10;
518 //              editorStackTabNavigator.closePolicy="close_never";
519 //              editorStackTabNavigator.scrollSpeed=20;
520                 editorStackTabNavigator.creationPolicy="auto";
521                 editorStackTabNavigator.percentWidth=100;
522                 editorStackTabNavigator.percentHeight=100;
523                 editorStackTabNavigator.styleName="dndStackTab";
524 //              editorStackTabNavigator.popUpButtonPolicy="off"
525
526
527                 editorStackAccordion = new Accordion();
528                 editorStackAccordion.percentWidth=100;
529                 editorStackAccordion.percentHeight=100;
530                 editorStackAccordion.creationPolicy="auto";
531                 editorStackAccordion.styleName="dndStackAccordion";
532                 /* FIXME: the accordion icons should be right-aligned. See:
533                 http://www.kristoferjoseph.com/blog/2008/11/06/positioning-the-flex-accordion-header-icon
534                 http://blog.flexexamples.com/2007/09/13/changing-text-alignment-in-an-flex-accordion-header/
535                 */
536
537                 setEditorStackUI(true);
538         }
539
540         private function setEditorStackUI(isTabbed:Boolean):void {
541                 var children:Array=[]; var i:uint;
542
543                 if (editorStack) {
544                         // blank existing component
545                         editorStack.removeEventListener("change",editorStackUIChange);
546                         editorStack.removeEventListener("updateComplete",editorStackUIUpdate);
547                         editorStack.removeAllChildren();
548                         editorContainer.removeChildAt(1);
549                 }
550
551                 // replace with new component
552                 editorStack = (isTabbed ? editorStackTabNavigator : editorStackAccordion) as Container;
553                 editorContainer.addChild(editorStack);
554
555                 // re-add children and listeners
556                 initialiseEditors();
557                 editorStack.addEventListener("change",editorStackUIChange);
558                 editorStack.addEventListener("updateComplete",editorStackUIUpdate);
559         }
560
561         private function editorStackUIChange(event:Event):void {
562                 ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox);
563         }
564
565         private function editorStackUIUpdate(event:Event):void {
566                 if (editorStack is TabNavigator) {
567                         var e:TabNavigator = editorStack as TabNavigator;
568                         if (e.selectedIndex<0) { return; }
569                         for (var i:uint=0; i<e.numChildren; i++) {
570                                 e.getTabAt(i).selected=(i==e.selectedIndex);
571                         }
572                 }
573         }
574
575
576         public function togglePanel():void {
577                 if (stack.selectedChild==editorContainer && selectedEntity!=null) {
578                         stack.selectedChild=advancedContainer;
579                 } else if (stack.selectedChild!=editorContainer) {
580                         stack.selectedChild=editorContainer;
581                 }
582         }
583
584         public function selectAdvancedPanel():void {
585                 checkAdvanced();
586                 stack.selectedChild=advancedContainer;
587         }
588
589       private function checkAdvanced():void {
590           if ( selectedEntity != null )
591              setupAdvanced(selectedEntity);
592       }
593
594       private var listeningToRelations:Array = [];
595
596       private function setupAdvanced(entity:Entity):void {
597                 if (!advancedTagGrid) advancedContainer.createComponentsFromDescriptors();      // if Flex hasn't created it, force it
598                 advancedTagGrid.init(entity);
599
600                 if ( entity == null ) {
601                         advancedID.htmlText = "";
602                 } else {
603                         var entityText:String = "xx";
604                         if      ( entity is Node     ) entityText = "Node";
605                         else if ( entity is Way      ) entityText = "Way";
606                         else if ( entity is Relation ) entityText = "Relation";
607                         advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
608                 }
609
610                 removeRelationListeners();
611
612                 if ( entity == null ) {
613                         relationsGrid.dataProvider = null;
614                 } else {
615                         resetRelationsGrid(entity);
616                         entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
617                         entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
618                 }
619       }
620
621           private function setupMultiAdvanced(entity:Entity):void {
622                 multiAdvancedTagGrid.init(entity);
623                 resetRelationsGrid(entity);
624                 entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation, false, 0, true);
625                 entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation, false, 0, true);
626       }
627
628           public function addNewTag():void {
629                 if (stack.selectedChild!=advancedContainer) { return; }
630                 advancedTagGrid.addNewTag();
631           }
632
633       private function addedToRelation(event:RelationMemberEvent):void {
634          resetRelationsGrid(selectedEntity);
635       }
636
637       private function removedFromRelation(event:RelationMemberEvent):void {
638          resetRelationsGrid(selectedEntity);
639       }
640
641       private function removeRelationListeners():void {
642           for each( var rel:Relation in listeningToRelations ) {
643               rel.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
644               rel.removeEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
645               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
646           }
647           listeningToRelations = [];
648           if (relationsGrid) relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
649           if (multiRelationsGrid) multiRelationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
650       }
651
652       private function resetRelationsGrid(entity:Entity):void {
653           removeRelationListeners();
654
655           var instance:DataGrid=relationsGrid;
656           if (entity is EntityCollection) instance=multiRelationsGrid;
657           var memberships:Array = entity.getRelationMemberships();
658           for each (var m:Object in memberships) {
659               m.relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
660               m.relation.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
661               m.relation.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
662               listeningToRelations.push(m.relation);
663           }
664           instance.dataProvider = memberships;
665           instance.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
666       }
667
668       private function relationRoleChanged(event:DataGridEvent):void {
669                 if (event.dataField != 'role') { return; }      // shouldn't really happen
670
671                 var relations:Array=event.currentTarget.dataProvider.toArray();
672                 var props:Object=relations[event.rowIndex];
673
674                 var relation:Relation=props['relation'];
675                 var newRole:String=event.itemRenderer.data['role'];
676
677                 if (selectedEntity is EntityCollection) {
678                         for each (var entity:Entity in EntityCollection(selectedEntity).entities) {
679                                 var indexes:Array=relation.findEntityMemberIndexes(entity);
680                                 for each (var index:int in indexes) {
681                                         relation.setMember(index, new RelationMember(entity,newRole), MainUndoStack.getGlobalStack().addAction);
682                                 }
683                         }
684                 } else {
685                         relation.setMember(props['index'], new RelationMember(selectedEntity,newRole), MainUndoStack.getGlobalStack().addAction);
686                 }
687       }
688
689       private function relationTagChanged(event:TagEvent):void {
690           resetRelationsGrid(selectedEntity);
691       }
692
693       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
694           resetRelationsGrid(selectedEntity);
695       }
696
697       private function checkMembers():void {
698           if (selectedEntity is Relation) {
699             setupMembers(selectedEntity as Relation);
700           }
701       }
702
703       private function setupMembers(rel:Relation):void {
704           var members:Array = [];
705           for (var i:int=0 ; i<rel.length; i++) {
706             var props:Object = {};
707             var member:RelationMember = rel.getMember(i);
708             props["id"] = member.entity.id;
709             props["type"] = member.entity.getType();
710             props["role"] = member.role;
711
712             members.push(props);
713           }
714           membersGrid.dataProvider = members;
715           membersGrid.dataProvider.addEventListener('collectionChange', membersChange);
716       }
717
718       private function membersChange(event:Event):void {
719           // Dropping all the members and re-adding them isn't exactly optimal
720           // but is at least robust for any kind of change.
721           // Figuring out a better way is someone else's FIXME
722
723           var rel:Relation = selectedEntity as Relation;
724           var action:CompositeUndoableAction = new CompositeUndoableAction("Rearrange relation members for "+rel);
725
726           // drop members
727           for (var i:int=rel.length-1 ; i>=0; i--) {
728             rel.removeMemberByIndex(i, action.push);
729           }
730
731           // add members in new order
732           for each(var memberObject:Object in membersGrid.dataProvider) {
733             var e:Entity;
734             var id:Number = memberObject.id;
735                         switch (memberObject.type) {
736                                 case 'node':            e = connection.getNode(id); break;
737                 case 'way':                     e = connection.getWay(id); break;
738                                 case 'relation':        e = connection.getRelation(id); break;
739             }
740             rel.appendMember(new RelationMember(e, memberObject.role), action.push);
741           }
742           MainUndoStack.getGlobalStack().addAction(action);
743       }
744
745       private function editRelation(id:Number):void {
746           var panel:RelationEditorPanel = RelationEditorPanel(
747               PopUpManager.createPopUp(Application(FlexGlobals.topLevelApplication), RelationEditorPanel, true));
748           panel.setRelation(connection.getRelation(id));
749           PopUpManager.centerPopUp(panel);
750       }
751
752         /** Create relation actions menu */
753
754         public function createRelationMenu(button:PopUpButton):void {
755                 var menu:Menu = new Menu(); 
756                 var dp:Object = [ {label: "Select all members"}, 
757                                                   {label: "Deselect all members"}, 
758                                                   {label: "Add selection to this relation", enabled: false},
759                                                   {label: "Delete relation"} ]; 
760                 menu.dataProvider = dp; 
761                 menu.addEventListener("itemClick", selectRelationMenu); 
762                 button.popUp = menu;
763         }
764
765         /** Enable 'add selection to...' entry only if some of the selection isn't in the relation.
766             Called each time the menu is clicked. */
767         
768         public function updateRelationMenu(event:Event):void {
769                 rowData=event.target.parent.data;       // this makes it accessible from selectRelationMenu
770                 var menu:Menu = Menu(event.target.popUp);
771                 var enable:Boolean = false;
772                 if (selectedEntity != null && selectedEntity is EntityCollection) {
773                         // Enable only if some entities aren't a member of the relation
774                         enable=!rowData.universal;
775                 }
776                 if (enable==menu.dataProvider[2].enabled) return;
777                 menu.dataProvider[2].enabled=enable;
778                 menu.invalidateList();
779         }
780
781         /** Do the action selected in the relation actions menu */
782
783         public function selectRelationMenu(event:MenuEvent):void {
784                 var rel:Relation=rowData.relation;
785                 var entities:Array;
786                 var controller:EditController=FlexGlobals.topLevelApplication.theController;
787                 switch (event.index) {
788                         case 0: // Select all members
789                                 entities=selectedEntity.entities.concat(rel.memberEntities);
790                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return arr.indexOf(e) == i } );      // remove duplicates
791                                 // ** FIXME: This is a really horrible way of changing the controller state
792                                 controller.setState(controller.findStateForSelection(entities));
793                                 break;
794
795                         case 1: // Deselect all members
796                                 entities=selectedEntity.entities;
797                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return !e.hasParent(rel) } );
798                                 controller.setState(controller.findStateForSelection(entities));
799                                 break;
800
801                         case 2: // Add selection to this relation
802                                 var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
803                                 for each (var entity:Entity in selectedEntity.entities) {
804                                         if (!entity.hasParent(rel)) {
805                                                 rel.appendMember(new RelationMember(entity,''), undo.push);
806                                         }
807                                 }
808                                 MainUndoStack.getGlobalStack().addAction(undo);
809                                 break;
810                         
811                         case 3: // Delete relation
812                                 Alert.show("Do you really want to delete the relation?","Are you sure?",Alert.YES | Alert.CANCEL,null,
813                                         function(event:CloseEvent):void { 
814                                                 if (event.detail==Alert.CANCEL) return;
815                                                 rel.remove(MainUndoStack.getGlobalStack().addAction);
816                                         } );
817                                 break;
818                 }
819         }
820
821       private function tagChanged(event:TagEvent):void {
822           refreshFeatureIcon();
823       }
824
825       public function loadFeatures():void {
826           mapFeatures = MapFeatures.getInstance();
827           stack.removeChild(membersVBox); // remove by default, will be added if relation
828       }
829
830       /** Open up a new browser page, showing the help page as defined in Map Features XML file .*/
831       public function openDescription():void {
832           if ( feature != null && feature.hasHelpURL() )
833               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
834       }
835
836       /** Open up a new browser page showing OSM's view of the current entity. */
837       public function openEntityPage():void {
838           if (selectedEntity != null && selectedEntity.id >= 0) {
839               // This is slightly hard-coded, but not drastically. The ../s could be changed for string manipulation of the apiBase
840               var urlBase:String = connection.apiBase + '../../browse/'
841               navigateToURL(new URLRequest(urlBase+selectedEntity.getType()+'/'+selectedEntity.id), "potlatch_browse");
842           }
843       }
844
845       public function addToRelation():void {
846           new RelationSelectPanel().init(selectedEntity,new Object());
847       }
848
849       private function removeFromRelation(id:Number, index:int=-1):void {
850                 var rel:Relation=connection.getRelation(id);
851                 if (index>-1) {
852                         rel.removeMemberByIndex(index, MainUndoStack.getGlobalStack().addAction);
853                 } else if (selectedEntity is EntityCollection) {
854                         var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
855                         for each (var e:Entity in EntityCollection(selectedEntity).entities) rel.removeMember(e,undo.push);
856                         MainUndoStack.getGlobalStack().addAction(undo);
857                 }
858       }
859
860       public function changeFeatureType(event:Event):void {
861           if ( selectedEntity == null )
862               return;
863
864           UIComponent.suspendBackgroundProcessing();
865           var newFeature:Feature = currentCategorySelector.selectedType;
866           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
867           var action:CompositeUndoableAction = new CompositeUndoableAction(
868                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
869                   selectedEntity.suspend();
870           
871           // build a list of tags that are editable in new feature
872           var editableTags:Array = new Array();
873           for each( var editor:EditorFactory in newFeature.editors ) {
874               if ( editor is SingleTagEditorFactory ) {
875                   var singleTagEditor:SingleTagEditorFactory = editor as SingleTagEditorFactory;
876                   editableTags.push(singleTagEditor.key);
877               }
878           }
879
880           // remove tags from the current feature
881           if ( feature != null ) {
882               for each( var oldtag:Object in feature.tags ) {
883                   if ( editableTags.indexOf(oldtag["k"]) < 0 ) {
884                       selectedEntity.setTag(oldtag["k"], null, action.push);
885                   }
886               }
887           }
888
889           // set tags for new feature
890           if ( newFeature != null ) {
891               for each( var newtag:Object in newFeature.tags ) {
892                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
893               }
894           }
895
896                   selectedEntity.resume();
897           undoStack(action);
898           popupChange.close();
899           initialiseEditors();
900           UIComponent.resumeBackgroundProcessing();
901       }
902
903         private function resizePOIGrid(event:Event):void {
904                 var rows:Number=event.target.dataProvider.length/event.target.columnCount;
905                 if (rows!=Math.floor(rows)) { rows=Math.floor(rows+1); }
906                 event.target.height=rows*(event.target.rowHeight+1);
907         }
908   ]]></fx:Script>
909 </mx:VBox>
910