d90322a380c0adcaaeabf89761d87fae9823bda5
[potlatch2.git] / net / systemeD / potlatch2 / TagViewer.mxml
1 <?xml version="1.0" encoding="utf-8"?>
2 <!---
3   The TagViewer is the container for the entire sidebar. It has a number of components, and subpanels, in a ViewStack that change
4   depending on what is selected, i.e. the ControllerState.
5
6   @see net.systemeD.potlatch2.controller.ControllerState
7     -->
8 <mx:VBox
9     xmlns:fx="http://ns.adobe.com/mxml/2009"
10         xmlns:mx="library://ns.adobe.com/flex/mx"
11         xmlns:flexlib="flexlib.containers.*"
12         xmlns:controls="net.systemeD.controls.*"
13         xmlns:potlatch2="net.systemeD.potlatch2.*"
14     xmlns:sidepanel="net.systemeD.potlatch2.panels.*"
15         horizontalScrollPolicy="off"
16     backgroundColor="white"
17     initialize="loadFeatures()">
18
19 <mx:ViewStack id="sidebar" width="100%" height="100%" creationPolicy="all">
20
21   <sidepanel:DragAndDropPanel id="dndPanel" />
22
23   <!-- Standard tagging panel -->
24
25   <mx:VBox id="tagsPanel" width="100%" height="100%" creationPolicy="auto" tabChildren="true">
26     <mx:ViewStack id="stack" width="100%" height="100%" change="tagsPanel.tabChildren=(event.newIndex==0)">
27       <mx:VBox width="100%" height="100%" label="Simple" id="editorContainer" creationComplete="initEditorStackUIs()" styleName="dndPanelVbox">
28         <mx:VBox width="100%" verticalGap="1" styleName="dndTagHeader">
29           <mx:HBox width="100%" id="iconContainer" styleName="featureSelector">
30             <mx:Image id="iconImage"/>
31             <mx:Text condenseWhite="true" width="100%" id="iconText" styleName="dndIconText"/>
32           </mx:HBox>
33           <mx:HBox width="100%">
34             <mx:PopUpButton id="popupChange" openAlways="true" width="100%" styleName="dndTagPopUpMenu" />
35             <mx:LinkButton icon="@Embed('../../../embedded/information.svg')" click="openDescription()" id="helpLabel" styleName="helpInfo"/>
36           </mx:HBox>
37           <mx:HBox width="100%" id="summaryContainer" visible="false">
38             <mx:Text condenseWhite="true" width="100%" id="featureSummary" link="togglePanel()" />
39           </mx:HBox>
40         </mx:VBox>
41       </mx:VBox>
42       <mx:VBox width="100%" height="100%" label="Advanced" id="advancedContainer" initialize="checkAdvanced()" verticalGap="1">
43         <mx:Label id="advancedID" click="new HistoryDialog().init(selectedEntity);">
44           <mx:htmlText><![CDATA[<i>No Selection</i>]]></mx:htmlText>
45         </mx:Label>
46
47                 <potlatch2:TagGrid id="advancedTagGrid" width="100%" height="75%" />
48
49         <mx:HBox horizontalAlign="right" width="100%">
50           <mx:LinkButton label="Delete" click="advancedTagGrid.removeTag()" id="advancedDeleteButton" enabled="{advancedTagGrid.selectedItem != null? true : false}"/>
51           <mx:LinkButton label="Add" click="advancedTagGrid.addNewTag()" id="advancedAddButton"/>
52         </mx:HBox>
53
54         <mx:DataGrid editable="true" width="100%" height="25%" id="relationsGrid"
55             doubleClickEnabled="true"
56             itemDoubleClick="editRelation(relationsGrid.selectedItem.id)"
57             doubleClick="if (event.target.parent==relationsGrid) { addToRelation(); }">
58             <mx:columns>
59                 <mx:DataGridColumn editable="false" dataField="description" headerText="Relation" minWidth="100">
60                     <mx:itemRenderer>
61                         <fx:Component>
62                             <mx:Text x="4" y="0" width="100%" selectable="false" htmlText="{outerDocument.adaptHTMLDescription(data.description)}" height="20"/>
63                         </fx:Component>
64                     </mx:itemRenderer>
65                 </mx:DataGridColumn>
66                 <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
67                 <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
68                     <mx:itemEditor><fx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></fx:Component></mx:itemEditor>
69                 </mx:DataGridColumn>
70                                 <mx:DataGridColumn width="40" minWidth="40" editable="false">
71                                         <mx:itemRenderer>
72                                                 <fx:Component>
73                                                         <mx:HBox horizontalAlign="center" verticalAlign="middle" paddingLeft="4">
74                                                                 <mx:PopUpButton arrowButtonWidth="12" paddingLeft="0" paddingRight="0" width="12" height="12" 
75                                                                                 open="{outerDocument.updateRelationMenu(event);}" 
76                                                                                 creationComplete="{outerDocument.createRelationMenu(PopUpButton(event.target));}"/>
77                                                                 <mx:Image source="@Embed('../../../embedded/delete_small.svg')"
78                                                                           click='event.stopPropagation();outerDocument.removeFromRelation(data.id, data.index);'
79                                                                           buttonMode="true" useHandCursor="true" width="12" height="12" />
80                                                         </mx:HBox>
81                                                 </fx:Component>
82                                         </mx:itemRenderer>
83                                 </mx:DataGridColumn>
84             </mx:columns>
85         </mx:DataGrid>
86
87         <mx:HBox horizontalAlign="right" width="100%">
88           <mx:LinkButton label="Remove from" click="removeFromRelation(relationsGrid.selectedItem.id, relationsGrid.selectedItem.index)"
89                           enabled="{relationsGrid.selectedItem != null? true : false}"/>
90           <mx:LinkButton label="Add to" click="addToRelation()"/>
91         </mx:HBox>
92
93       </mx:VBox>
94
95       <mx:VBox width="100%" height="100%" label="Members" id="membersVBox" initialize="checkMembers()" verticalGap="1">
96         <mx:Label id="membersText" text="Relation Members"/>
97         <mx:DataGrid editable="true" width="100%" height="100%" id="membersGrid"
98                       dragEnabled="true" dragMoveEnabled="true" dropEnabled="true">
99           <mx:columns>
100             <mx:DataGridColumn editable="false" dataField="type" headerText="Type"/>
101             <mx:DataGridColumn editable="false" dataField="id" headerText="ID"/>
102             <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
103                                 <mx:itemEditor><fx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></fx:Component></mx:itemEditor>
104                         </mx:DataGridColumn>
105           </mx:columns>
106         </mx:DataGrid>
107       </mx:VBox>
108
109       </mx:ViewStack>
110
111           <mx:HBox width="100%">
112                 <mx:LinkBar dataProvider="{stack}"/>
113                 <mx:Spacer width="100%"/>
114                 <mx:LinkButton
115                         icon="@Embed('../../../embedded/view_tabbed.png')"
116                         disabledIcon="@Embed('../../../embedded/view_tabbed_disabled.png')"
117                         click="setEditorStackUI(true)" id="tabNavigatorLabel" paddingTop="6"
118                         toolTip="Show in tabs"
119                         enabled="{editorStack is Accordion &amp;&amp; stack.selectedIndex==0}" />
120                 <mx:LinkButton
121                         icon="@Embed('../../../embedded/view_accordion.png')"
122                         disabledIcon="@Embed('../../../embedded/view_accordion_disabled.png')"
123                         click="setEditorStackUI(false)" id="accordionLabel" paddingTop="6"
124                         toolTip="Show in sliding windows"
125                         enabled="{editorStack is TabNavigator &amp;&amp; stack.selectedIndex==0}" />
126           </mx:HBox>
127   </mx:VBox>
128
129   <!-- Multiple selection -->
130
131   <mx:VBox id="multiplePanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
132     <potlatch2:TagGrid id="multiAdvancedTagGrid" width="100%" height="75%" />
133         <mx:HBox horizontalAlign="right" width="100%">
134           <mx:LinkButton label="Delete" click="multiAdvancedTagGrid.removeTag()" enabled="{multiAdvancedTagGrid.selectedItem != null? true : false}"/>
135           <mx:LinkButton label="Add" click="multiAdvancedTagGrid.addNewTag()" />
136         </mx:HBox>
137
138     <mx:DataGrid editable="true" width="100%" height="25%" id="multiRelationsGrid"
139         doubleClickEnabled="true"
140         itemDoubleClick="editRelation(multiRelationsGrid.selectedItem.id)"
141         doubleClick="if (event.target.parent==multiRelationsGrid) { addToRelation(); }">
142         <mx:columns>
143             <mx:DataGridColumn editable="false" dataField="description" headerText="Relation">
144                 <mx:itemRenderer>
145                     <fx:Component>
146                         <mx:Text x="4" y="0" width="100%" selectable="false" htmlText="{outerDocument.adaptHTMLDescription(data.description)}" height="20"/>
147                     </fx:Component>
148                 </mx:itemRenderer>
149             </mx:DataGridColumn>
150             <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
151             <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
152                 <mx:itemEditor><fx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></fx:Component></mx:itemEditor>
153             </mx:DataGridColumn>
154                         <mx:DataGridColumn width="40" minWidth="40" editable="false">
155                                 <mx:itemRenderer>
156                                         <fx:Component>
157                             <mx:HBox horizontalAlign="center" verticalAlign="middle">
158                                                         <mx:PopUpButton arrowButtonWidth="12" paddingLeft="0" paddingRight="0" width="12" height="12" 
159                                                                         open="{outerDocument.updateRelationMenu(event);}" 
160                                                                         creationComplete="{outerDocument.createRelationMenu(PopUpButton(event.target));}"/>
161                                                         <mx:Image source="@Embed('../../../embedded/delete_small.svg')"
162                                                                   click='event.stopPropagation();outerDocument.removeFromRelation(data.id);'
163                                                                   buttonMode="true" useHandCursor="true" width="12" height="12" />
164                                                 </mx:HBox>
165                                         </fx:Component>
166                                 </mx:itemRenderer>
167                         </mx:DataGridColumn>
168         </mx:columns>
169     </mx:DataGrid>
170     <mx:HBox horizontalAlign="right" width="100%">
171       <mx:LinkButton label="Remove from" click="removeFromRelation(multiRelationsGrid.selectedItem.id)"
172                       enabled="{multiRelationsGrid.selectedItem != null? true : false}"/>
173       <mx:LinkButton label="Add to" click="addToRelation()"/>
174     </mx:HBox>
175
176   </mx:VBox>
177
178   <!-- Multiple selection but items cannot be edited -->
179
180   <mx:VBox id="multipleInvalidPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
181         <mx:Text id="multipleInvalidPanelText" text="You have selected multiple items." width="100%" styleName="helpInfo" />
182   </mx:VBox>
183
184   <!-- Generic marker panel -->
185
186   <mx:VBox id="markerPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
187     <sidepanel:MarkerPanel id="markerPanelContents" width="100%"/>
188   </mx:VBox>
189
190   <!-- Bug editing panel -->
191
192   <mx:VBox id="bugPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
193     <sidepanel:BugPanel id="bugPanelContents" width="100%"/>
194   </mx:VBox>
195
196   <!-- Background layer selection -->
197
198   <mx:VBox id="backgroundPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
199     <sidepanel:BackgroundPanel id="backgroundPanelContents" width="100%"/>
200   </mx:VBox>
201
202   <!-- merge tags from background layer -->
203
204   <mx:VBox id="backgroundMergePanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
205     <sidepanel:BackgroundMergePanel id="backgroundMergePanelContents" width="100%" />
206   </mx:VBox>
207
208 </mx:ViewStack>
209
210   <fx:Script><![CDATA[
211       import net.systemeD.halcyon.connection.*;
212       import net.systemeD.halcyon.MapPaint;
213       import net.systemeD.potlatch2.EditController;
214       import net.systemeD.potlatch2.mapfeatures.*;
215       import net.systemeD.potlatch2.history.HistoryDialog;
216       import net.systemeD.potlatch2.mapfeatures.editors.*;
217       import net.systemeD.potlatch2.utils.*;
218       import net.systemeD.controls.CollapsiblePanel;
219
220       import mx.collections.*;
221       import mx.containers.VBox;
222       import mx.containers.HBox;
223       import mx.containers.TabNavigator;
224       import mx.containers.Accordion;
225       import mx.events.*;
226       import mx.core.*;
227       import mx.managers.PopUpManager;
228       import mx.controls.Menu;
229       import mx.controls.Alert;
230       import flash.geom.Point;
231       import flash.net.*;
232       import mx.events.DragEvent;
233       import mx.managers.DragManager;
234       import mx.core.DragSource;
235       import mx.controls.TabBar;
236       import spark.components.Form;
237       import spark.layouts.FormLayout;
238 //    import flexlib.containers.SuperTabNavigator;
239
240       [Bindable] [Embed(source="../../../embedded/tab_basic.png"       )] private var tabIconBasic:Class;
241       [Bindable] [Embed(source="../../../embedded/tab_address.png"     )] private var tabIconAddress:Class;
242       [Bindable] [Embed(source="../../../embedded/tab_cycle.png"       )] private var tabIconCycle:Class;
243       [Bindable] [Embed(source="../../../embedded/tab_details.png"     )] private var tabIconDetails:Class;
244       [Bindable] [Embed(source="../../../embedded/tab_restrictions.png")] private var tabIconRestrictions:Class;
245       [Bindable] [Embed(source="../../../embedded/tab_transport.png"   )] private var tabIconTransport:Class;
246       [Bindable] [Embed(source="../../../embedded/tab_walk.png"        )] private var tabIconWalk:Class;
247       private var tabIcons:Object= { Basic:tabIconBasic, Details:tabIconDetails, Address:tabIconAddress, Walk:tabIconWalk, Cycle:tabIconCycle, 
248                                          Transport:tabIconTransport, Restrictions:tabIconRestrictions};
249
250       private var editorStackTabNavigator:TabNavigator;
251       private var editorStackAccordion:Accordion;
252       [Bindable] private var editorStack:Container;
253
254       public var mapFeatures:MapFeatures;
255       public var controller:EditController;
256       private var selectedEntity:Entity;
257       private var connection:Connection;
258       private var currentCategorySelector:CategorySelector;
259       private var categorySelectors:Object = {};        // hash of categorySelectors for each limitType
260       private var categorySelectorEntity:Entity;        // entity used to draw the most recent categorySelector
261       private var categorySelectorLimitType:String;     // limit type used to draw the most recent categorySelector
262       private var feature:Feature = null;
263
264       private var rowData:Object;               // relation membership reference, needed so it's accessible from relation actions menu
265
266           public function setEntity(entities:Array, layer:MapPaint=null):void {
267                 UIComponent.suspendBackgroundProcessing();
268                 connection=null;
269
270                 var firstSelected:Entity=null;
271                 if (entities.length==1) { firstSelected=entities[0]; }
272
273                 if (selectedEntity!=firstSelected && selectedEntity!=null) {
274                         selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
275                         selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
276                         selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
277                         if (selectedEntity is EntityCollection) EntityCollection(selectedEntity).releaseListeners();
278                 }
279
280                 if (entities.length==0) {
281                         // Nothing selected, so show drag-and-drop panel
282                         sidebar.selectedChild = dndPanel;
283                         selectedEntity=null;
284
285                 } else if (entities.length==1) {
286                         // Single entity selected, so show tag panel
287                         if (firstSelected!=null && selectedEntity!=firstSelected) { 
288                                 firstSelected.addEventListener(Connection.TAG_CHANGED, tagChanged, false, 0, true);
289                         }
290                         selectedEntity=firstSelected;
291                         connection=firstSelected.connection;
292                         if (advancedID!=null) { setupAdvanced(firstSelected); }
293                         if (firstSelected is Relation) { stack.addChild(membersVBox); }
294             if (selectedEntity is Marker && connection is BugConnection) {
295               bugPanelContents.init(selectedEntity, BugConnection(connection));
296               sidebar.selectedChild = bugPanel;
297             } else if (selectedEntity is Marker) {
298               markerPanelContents.init(selectedEntity, layer);
299               sidebar.selectedChild = markerPanel;
300             } else if (connection is SnapshotConnection) {
301               backgroundPanelContents.init(selectedEntity);
302               sidebar.selectedChild = backgroundPanel;
303             } else {
304               refreshFeatureIcon();
305               initialiseEditors();
306               sidebar.selectedChild = tagsPanel;
307             }
308
309         } else if (entities.length==2
310                       && xor(entities[0].connection is SnapshotConnection, entities[1].connection is SnapshotConnection)
311                       && xor(!controller.map.getLayerForEntity(entities[0]).isBackground, !controller.map.getLayerForEntity(entities[1]).isBackground) ) {
312             backgroundMergePanelContents.init(entities);
313             sidebar.selectedChild = backgroundMergePanel;
314                         // ** FIXME: do we need to set selectedEntity here?
315
316                 } else if(isMultipleEditable(entities)) {
317                         selectedEntity = new EntityCollection(entities);
318                         selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged, false, 0, true);
319             sidebar.selectedChild = multiplePanel;
320                         setupMultiAdvanced(selectedEntity);
321                         connection=entities[0].connection;
322                         
323                 } else {
324                         //The selection contains elements which can't be edited all together.
325                         sidebar.selectedChild = multipleInvalidPanel;
326                         selectedEntity=null;
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           var oldEntity:Entity = categorySelectorEntity;
338
339           feature = selectedEntity == null ? null : mapFeatures.findMatchingFeature(selectedEntity);
340           if (oldFeature==feature && 
341               categorySelectorEntity==selectedEntity && 
342               categorySelectorLimitType==limitType(selectedEntity)) {
343               updateCategoryImageAndText(selectedEntity,feature);
344               return;
345           }
346
347           categorySelectorEntity=selectedEntity;
348           categorySelectorLimitType=limitType(selectedEntity);
349           if ( oldFeature != null ) { oldFeature.removeEventListener("imageChanged", featureImageChanged); }
350           if ( feature != null )    { feature.addEventListener("imageChanged", featureImageChanged); }
351                   setCategorySelector(selectedEntity, feature);
352       }
353
354       private function featureImageChanged(event:Event):void {
355           setCategorySelector(selectedEntity, feature);
356       }
357
358
359       /** Set the icon, categorySelector and help text for the current entity. */
360       private function setCategorySelector(entity:Entity, feature:Feature):void {
361                         // Remove the "user has selected something" event listener from previous categorySelector,
362                         // and make it invisible because Flex is crap at updating click areas otherwise
363                         if (currentCategorySelector) { 
364                                 currentCategorySelector.removeEventListener("selectedType", changeFeatureType);
365                                 currentCategorySelector.visible=false;
366                         }
367                         
368                         // Have we cached the categorySelector for this limitType? If not, create one
369                         var lt:String=limitType(entity);
370                         if (!categorySelectors[lt]) {
371                                 categorySelectors[lt]=new CategorySelector();
372                                 categorySelectors[lt].setLimitTypes(lt);
373                         }
374                         currentCategorySelector=categorySelectors[lt];
375                         currentCategorySelector.addEventListener("selectedType", changeFeatureType, false, 0, true);
376
377                         updateCategoryImageAndText(entity,feature);
378                         currentCategorySelector.setSelectedFeature(feature);
379
380                         // Set it as the popup, and make sure it's visible
381                         popupChange.popUp=currentCategorySelector;
382                         currentCategorySelector.visible=true;
383       }
384
385       private function updateCategoryImageAndText(entity:Entity, feature:Feature):void {
386                         if (feature) {
387                                 iconImage.source = feature.image;
388                                 iconText.htmlText = feature.htmlDetails(entity);
389                                 popupChange.label = feature.name;
390                                 helpLabel.visible = feature.hasHelpURL();
391                                 setSummary('');
392                         } else {
393                                 iconImage.source = null;
394                                 popupChange.label = "unknown";
395                                 helpLabel.visible = false;
396                                 if (entity==null) {
397                                         iconText.htmlText = "<i>Nothing selected</i>";
398                                         setSummary('');
399                                 } else if (entity.hasTags() || entity.parentRelations.length>0) {
400                                         iconText.htmlText = "<b>Not recognised</b><br/><font size='10pt'>Try looking at the tags under the advanced properties</font>";
401                                         setSummary(tagSummary(entity));
402                                 } else {
403                                         iconText.htmlText = "<b>No tags set</b><br/><font size='10pt'>Please use the menu below to define what this "+entity.getType()+" is</font>";
404                                         setSummary('');
405                                 }
406                         }
407           }
408
409         /** Construct an HTML string that summarises the tags and relation memberships of an object. */
410         private function tagSummary(entity:Entity):String {
411                 // Process tags
412                 var tags:Object=entity.getTagsCopy();
413                 var len:uint=entity.getTagList().length;
414                 var expl:Array=[];
415                 var t:String="none";
416                 if (tags['name']) {
417                         expl.push("<b>"+tags['name']+"</b>"); delete tags['name']; len--;
418                 }
419                 for (var k:String in tags) {
420                         if (nounKeys.indexOf(k)>-1) {
421                                 expl.push("<b>"+k+"</b>="+tags[k]); len--;
422                         }
423                 }
424                 if (expl.length) {
425                         switch (len) {
426                                 case 1:         expl.push("and 1 other tag"); break;
427                                 case 0:         break;
428                                 default:        expl.push("and "+len+" other tags"); break;
429                         }
430                         t=expl.join('; ');
431                 } else if (len>0) {
432                         t=entity.getTagList().toString();
433                 }
434
435                 // Process relations
436                 expl=[];
437                 for each (var rel:Relation in entity.parentRelations) {
438                         tags=rel.getTagsHash();
439                         if (tags['type'] && tags['name']) { expl.push("<b>"+tags['type']+"</b> ("+tags['name']+")"); }
440                         else if (tags['type']) { expl.push("<b>"+tags['type']+"</b>"); }
441                         else if (tags['name']) { expl.push(tags['name']); }
442                         else if (tags['ref' ]) { expl.push(tags['ref']); }
443                         else { expl.push('unknown'); }
444                 }
445
446                 // Assemble complete string
447                 return "<p>Tags: "+t+(expl.length ? "<br>Relations: "+expl.join('; ') : '')+" <b>(<a href='event:openAdvanced'>edit</a>)</b></p>";
448         }
449         
450         /** List of 'noun' keys (i.e. those that define the type of the object, rather than its properties). FIXME: should be defined in a config file. */
451         private static var nounKeys:Array=['amenity','barrier','boundary','building','construction','highway','historic','landuse','leisure',
452                                            'man_made','natural','office','place','power','railway','service','shop','tourism','traffic_calming','waterway'];
453
454         private function setSummary(text:String):void {
455                 featureSummary.htmlText=text;
456                 summaryContainer.visible=(text!='');
457         }
458         
459           private function isMultipleEditable(entities:Array):Boolean {
460                 for each(var entity:Entity in entities) {
461                         if(!(entity is Node || entity is Way))
462                                 return false;
463                 }
464                 return true;
465           }
466
467       private function limitType(entity:Entity):String {
468           if      (entity is Node    ) return "point";
469           else if (entity is Way     ) return Way(entity).isArea() ? "area" : "line";
470           else if (entity is Relation) return "relation";
471           return null;
472       }
473
474       private var tabComponents:Object = {};
475       private var subpanelComponents:Object = {};
476
477       private function initialiseEditors():void {
478                 editorStack.removeAllChildren();
479                 if ( selectedEntity == null || feature == null )
480                         return;
481
482                 var basicEditorBox:VBox = createEditorBox();
483                 basicEditorBox.label = "Basic";
484                 basicEditorBox.icon=tabIconBasic;
485                 editorStack.addChild(basicEditorBox);
486
487                 var tabs:Object = {};
488                 var tabList:Array = [];
489                 tabComponents = {};
490                 var subpanels:Object = {};
491                 subpanelComponents = {};
492
493                 // First create the tabs
494                 for each (var factory:EditorFactory in feature.editors) {
495                         var category:String = factory.category;
496                         if (category!='') {
497                                 var tab:VBox = tabs[category];
498                                 if ( tab == null) {
499                                         tab = createEditorBox();
500                                         tab.label = category;
501                                         if (tabIcons[category]) tab.icon=tabIcons[category];
502                                         tabs[category] = tab;
503                                         tabList.push(tab);      
504                                 }
505                         }
506                 }
507
508                 // Put the tabs on-screen in order
509                 tabList.sort(sortCategories,16);
510                 for each (tab in tabList) {
511                         editorStack.addChild(tab);
512                         tabComponents[tab] = [];
513                 }
514
515                 // Then add the individual editors to them
516                 for each (factory in feature.editors) {
517
518                         // Add to basic editor box first
519                         if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
520                                 var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
521                                 if (editor) Form(basicEditorBox.getChildByName("form")).addElement(UIComponent(editor));
522                         }
523
524                         // Then prepare to add to category panel
525                         category=factory.category;
526                         if (factory.category=='') continue;
527                         var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
528                         if (!catEditor) continue;
529                         tab=tabs[category];
530                         
531                         // Create subcategory panel if needed
532                         if (factory.subcategory) {
533                                 var subcategory:String = factory.subcategory;
534                                 if (!subpanels[category]) { subpanels[category]={}; }
535                                 var subpanel:CollapsiblePanel = subpanels[category][subcategory];
536                                 if (!subpanel) {
537                                         subpanel=new CollapsiblePanel(false);
538                                         subpanel.percentWidth=100;
539                                         subpanel.styleName="subcategoryPanel";
540                                         subpanel.title=subcategory;
541                                         subpanels[category][subcategory]=subpanel;
542                                         addConstrainedForm(subpanel);
543                                         tabComponents[tab].push(subpanel);
544                                 }
545                                 Form(subpanel.getChildByName("form")).addElement(UIComponent(catEditor));
546                         } else {
547                                 tabComponents[tab].push(catEditor);
548                         }
549                 }
550       }
551
552         // ** FIXME: Order probably shouldn't be hard-coded, but configurable
553         private static var categoryOrder:Array=["Restrictions","Transport","Cycle","Walk","Address","Details"]; // reverse order
554         private function sortCategories(a:VBox,b:VBox):int {
555                 var a1:int=categoryOrder.indexOf(a.label);
556                 var a2:int=categoryOrder.indexOf(b.label);
557                 if (a1<a2) { return 1; }
558                 else if (a1>a2) { return -1; }
559                 return 0;
560         }
561         
562         private function createEditorBox():VBox {
563                 var box:VBox = new VBox();
564                 box.percentWidth = 100;
565                 box.percentHeight = 100;
566                 box.styleName = "dndEditorContainer";
567                 addConstrainedForm(box);
568                 return box;
569         }
570         
571         private function addConstrainedForm(parentObject:DisplayObjectContainer):void {
572                 var form:Form = new Form();
573                 form.name = "form";
574                 form.percentWidth=100;
575                 form.addEventListener(mx.events.ResizeEvent.RESIZE, formResizeHandler, false, 0, true);
576                 parentObject.addChild(form);
577                 if (parentObject.width>0) form.maxWidth=parentObject.width;
578         }
579         
580         private function formResizeHandler(e:Event):void {
581                 var form:Form=Form(e.target);
582                 if (form.parent.width>0) form.maxWidth=form.parent.width;
583         }
584
585         private function ensureEditorsPopulated(tab:VBox):void {
586                 var components:Array = tabComponents[tab];
587                 var form:Form=Form(tab.getChildByName("form"));
588                 if ( components == null || tab == null || form.numElements >= components.length ) return;
589                 for each (var component:DisplayObject in components ) {
590                         form.addElement(UIComponent(component));
591                 }
592         }
593
594         private function initEditorStackUIs():void {
595                 editorStackTabNavigator = new TabNavigator();
596                 editorStackTabNavigator.creationPolicy="auto";
597                 editorStackTabNavigator.percentWidth=100;
598                 editorStackTabNavigator.percentHeight=100;
599                 editorStackTabNavigator.styleName="dndStackTab";
600
601                 editorStackAccordion = new Accordion();
602                 editorStackAccordion.percentWidth=100;
603                 editorStackAccordion.percentHeight=100;
604                 editorStackAccordion.creationPolicy="auto";
605                 editorStackAccordion.styleName="dndStackAccordion";
606                 /* FIXME: the accordion icons should be right-aligned. See:
607                 http://www.kristoferjoseph.com/blog/2008/11/06/positioning-the-flex-accordion-header-icon
608                 http://blog.flexexamples.com/2007/09/13/changing-text-alignment-in-an-flex-accordion-header/
609                 */
610
611                 setEditorStackUI(true);
612         }
613
614         private function setEditorStackUI(isTabbed:Boolean):void {
615                 var children:Array=[]; var i:uint;
616
617                 if (editorStack) {
618                         // blank existing component
619                         editorStack.removeEventListener("change",editorStackUIChange);
620                         editorStack.removeEventListener("updateComplete",editorStackUIUpdate);
621                         editorStack.removeAllChildren();
622                         editorContainer.removeChildAt(1);
623                 }
624
625                 // replace with new component
626                 editorStack = (isTabbed ? editorStackTabNavigator : editorStackAccordion) as Container;
627                 editorContainer.addChild(editorStack);
628
629                 // re-add children and listeners
630                 initialiseEditors();
631                 editorStack.addEventListener("change",editorStackUIChange);
632                 editorStack.addEventListener("updateComplete",editorStackUIUpdate);
633         }
634
635         private function editorStackUIChange(event:Event):void {
636                 ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox);
637         }
638
639         private function editorStackUIUpdate(event:Event):void {
640                 if (editorStack is TabNavigator) {
641                         var e:TabNavigator = editorStack as TabNavigator;
642                         if (e.selectedIndex<0) { return; }
643                         for (var i:uint=0; i<e.numChildren; i++) {
644                                 e.getTabAt(i).selected=(i==e.selectedIndex);
645                         }
646                 }
647         }
648
649
650         public function togglePanel():void {
651                 if (stack.selectedChild==editorContainer && selectedEntity!=null) {
652                         stack.selectedChild=advancedContainer;
653                 } else if (stack.selectedChild!=editorContainer) {
654                         stack.selectedChild=editorContainer;
655                 }
656         }
657
658         public function selectAdvancedPanel():void {
659                 checkAdvanced();
660                 stack.selectedChild=advancedContainer;
661         }
662
663       private function checkAdvanced():void {
664           if ( selectedEntity != null )
665              setupAdvanced(selectedEntity);
666       }
667
668       private var listeningToRelations:Array = [];
669
670       private function setupAdvanced(entity:Entity):void {
671                 if (!advancedTagGrid) advancedContainer.createComponentsFromDescriptors();      // if Flex hasn't created it, force it
672                 advancedTagGrid.init(entity);
673
674                 if ( entity == null ) {
675                         advancedID.htmlText = "";
676                 } else {
677                         var entityText:String = "xx";
678                         if      ( entity is Node     ) entityText = "Node";
679                         else if ( entity is Way      ) entityText = "Way";
680                         else if ( entity is Relation ) entityText = "Relation";
681                         advancedID.htmlText = entityText+": <b>"+entity.id+"</b> "+(entity.status ? entity.status : '');
682                 }
683
684                 removeRelationListeners();
685
686                 if ( entity == null ) {
687                         relationsGrid.dataProvider = null;
688                 } else {
689                         resetRelationsGrid(entity);
690                         entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
691                         entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
692                 }
693       }
694
695           private function setupMultiAdvanced(entity:Entity):void {
696                 multiAdvancedTagGrid.init(entity);
697                 resetRelationsGrid(entity);
698                 entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation, false, 0, true);
699                 entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation, false, 0, true);
700       }
701
702           public function addNewTag():void {
703                 if (sidebar.selectedChild==multiplePanel) { multiAdvancedTagGrid.addNewTag(); }
704                 else if (stack.selectedChild==advancedContainer) { advancedTagGrid.addNewTag(); }
705           }
706
707       private function addedToRelation(event:RelationMemberEvent):void {
708          resetRelationsGrid(selectedEntity);
709          refreshFeatureIcon();
710       }
711
712       private function removedFromRelation(event:RelationMemberEvent):void {
713          resetRelationsGrid(selectedEntity);
714          refreshFeatureIcon();
715       }
716
717       private function removeRelationListeners():void {
718           for each( var rel:Relation in listeningToRelations ) {
719               rel.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
720               rel.removeEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
721               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
722           }
723           listeningToRelations = [];
724           if (relationsGrid) relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
725           if (multiRelationsGrid) multiRelationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
726       }
727
728       private function resetRelationsGrid(entity:Entity):void {
729           removeRelationListeners();
730
731           var instance:DataGrid=relationsGrid;
732           if (entity is EntityCollection) instance=multiRelationsGrid;
733           var memberships:Array = entity.getRelationMemberships();
734           for each (var m:Object in memberships) {
735               m.relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
736               m.relation.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
737               m.relation.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
738               listeningToRelations.push(m.relation);
739           }
740           instance.dataProvider = memberships;
741           instance.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
742       }
743
744       private function relationRoleChanged(event:DataGridEvent):void {
745                 if (event.dataField != 'role') { return; }      // shouldn't really happen
746
747                 var relations:Array=event.currentTarget.dataProvider.toArray();
748                 var props:Object=relations[event.rowIndex];
749
750                 var relation:Relation=props['relation'];
751                 var newRole:String=event.itemRenderer.data['role'];
752
753                 if (selectedEntity is EntityCollection) {
754                         if (newRole==EntityCollection.DIFFERENT) return;
755                         for each (var entity:Entity in EntityCollection(selectedEntity).entities) {
756                                 var indexes:Array=relation.findEntityMemberIndexes(entity);
757                                 for each (var index:int in indexes) {
758                                         relation.setMember(index, new RelationMember(entity,newRole), MainUndoStack.getGlobalStack().addAction);
759                                 }
760                         }
761                 } else {
762                         relation.setMember(props['index'], new RelationMember(selectedEntity,newRole), MainUndoStack.getGlobalStack().addAction);
763                 }
764       }
765
766       private function relationTagChanged(event:TagEvent):void {
767           resetRelationsGrid(selectedEntity);
768           refreshFeatureIcon();
769       }
770
771       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
772           resetRelationsGrid(selectedEntity);
773       }
774
775       private function checkMembers():void {
776           if (selectedEntity is Relation) {
777             setupMembers(selectedEntity as Relation);
778           }
779       }
780
781       private function setupMembers(rel:Relation):void {
782           var members:Array = [];
783           for (var i:int=0 ; i<rel.length; i++) {
784             var props:Object = {};
785             var member:RelationMember = rel.getMember(i);
786             props["id"] = member.entity.id;
787             props["type"] = member.entity.getType();
788             props["role"] = member.role;
789
790             members.push(props);
791           }
792           membersGrid.dataProvider = members;
793           membersGrid.dataProvider.addEventListener('collectionChange', membersChange);
794       }
795
796       private function membersChange(event:Event):void {
797           // Dropping all the members and re-adding them isn't exactly optimal
798           // but is at least robust for any kind of change.
799           // Figuring out a better way is someone else's FIXME
800
801           var rel:Relation = selectedEntity as Relation;
802           var action:CompositeUndoableAction = new CompositeUndoableAction("Rearrange relation members for "+rel);
803
804           // drop members
805           for (var i:int=rel.length-1 ; i>=0; i--) {
806             rel.removeMemberByIndex(i, action.push);
807           }
808
809           // add members in new order
810           for each(var memberObject:Object in membersGrid.dataProvider) {
811             var e:Entity;
812             var id:Number = memberObject.id;
813                         switch (memberObject.type) {
814                                 case 'node':            e = connection.getNode(id); break;
815                 case 'way':                     e = connection.getWay(id); break;
816                                 case 'relation':        e = connection.getRelation(id); break;
817             }
818             rel.appendMember(new RelationMember(e, memberObject.role), action.push);
819           }
820           MainUndoStack.getGlobalStack().addAction(action);
821       }
822
823       private function editRelation(id:Number):void {
824           var panel:RelationEditorPanel = RelationEditorPanel(
825               PopUpManager.createPopUp(Application(FlexGlobals.topLevelApplication), RelationEditorPanel, true));
826           panel.setRelation(connection.getRelation(id));
827           PopUpManager.centerPopUp(panel);
828       }
829
830         /** Create relation actions menu */
831
832         public function createRelationMenu(button:PopUpButton):void {
833                 var menu:Menu = new Menu(); 
834                 var dp:Object = [ {label: "Select all members"}, 
835                                                   {label: "Deselect all members"}, 
836                                                   {label: "Add selection to this relation", enabled: false},
837                                                   {label: "Delete relation"} ]; 
838                 menu.dataProvider = dp; 
839                 menu.addEventListener("itemClick", selectRelationMenu); 
840                 button.popUp = menu;
841         }
842
843         /** Enable 'add selection to...' entry only if some of the selection isn't in the relation.
844             Called each time the menu is clicked. */
845         
846         public function updateRelationMenu(event:Event):void {
847                 rowData=event.target.parent.data;       // this makes it accessible from selectRelationMenu
848                 var menu:Menu = Menu(event.target.popUp);
849                 var enable:Boolean = false;
850                 if (selectedEntity != null && selectedEntity is EntityCollection) {
851                         // Enable only if some entities aren't a member of the relation
852                         enable=!rowData.universal;
853                 }
854                 if (enable==menu.dataProvider[2].enabled) return;
855                 menu.dataProvider[2].enabled=enable;
856                 menu.invalidateList();
857         }
858
859         /** Do the action selected in the relation actions menu */
860
861         public function selectRelationMenu(event:MenuEvent):void {
862                 var rel:Relation=rowData.relation;
863                 var entities:Array;
864                 var controller:EditController=FlexGlobals.topLevelApplication.theController;
865                 switch (event.index) {
866                         case 0: // Select all members
867                                 entities=selectedEntity.entities.concat(rel.memberEntities);
868                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return arr.indexOf(e) == i } );      // remove duplicates
869                                 // ** FIXME: This is a really horrible way of changing the controller state
870                                 controller.setState(controller.findStateForSelection(entities));
871                                 break;
872
873                         case 1: // Deselect all members
874                                 entities=selectedEntity.entities;
875                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return !e.hasParent(rel) } );
876                                 controller.setState(controller.findStateForSelection(entities));
877                                 break;
878
879                         case 2: // Add selection to this relation
880                                 var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
881                                 for each (var entity:Entity in selectedEntity.entities) {
882                                         if (!entity.hasParent(rel)) {
883                                                 rel.appendMember(new RelationMember(entity,''), undo.push);
884                                         }
885                                 }
886                                 MainUndoStack.getGlobalStack().addAction(undo);
887                                 break;
888                         
889                         case 3: // Delete relation
890                                 var warning:String="This relation has # members. Deleting it will affect all of them and erase this $. Are you really sure?";
891                                 warning=warning.replace("#",rel.length).replace("$",rel.getRelationType());
892                                 Alert.show(warning,"Are you sure?",Alert.YES | Alert.CANCEL,null,
893                                         function(event:CloseEvent):void { 
894                                                 if (event.detail==Alert.CANCEL) return;
895                                                 rel.remove(MainUndoStack.getGlobalStack().addAction);
896                                         } , null, Alert.CANCEL);
897                                 break;
898                 }
899         }
900
901       private function tagChanged(event:TagEvent):void {
902           refreshFeatureIcon();
903       }
904
905       public function loadFeatures():void {
906           mapFeatures = MapFeatures.getInstance();
907           stack.removeChild(membersVBox); // remove by default, will be added if relation
908       }
909
910       /** Open up a new browser page, showing the help page as defined in Map Features XML file .*/
911       public function openDescription():void {
912           if ( feature != null && feature.hasHelpURL() )
913               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
914       }
915
916       /** Slightly poshify the description by making it HTML. 
917           In theory we could have embedded images here, but htmlText is completely broken. **/
918       public function adaptHTMLDescription(text:String):String {
919           text=text.replace(/^route (\w+) /,"<b>$1</b> ");
920           text=text.replace(/ncn (\d+)/,"<font color='#FF0000'>$1</font>");
921           text=text.replace(/rcn (\d+)/,"<font color='#00CCCC'>$1</font>");
922           text=text.replace(/lcn (\d+)/,"<font color='#0000FF'>$1</font>");
923           return text;
924       }
925
926       public function addToRelation():void {
927           new RelationSelectPanel().init(selectedEntity,new Object());
928       }
929
930       public function removeFromRelation(id:Number, index:int=-1):void {
931                 var rel:Relation=connection.getRelation(id);
932                 if (index>-1) {
933                         rel.removeMemberByIndex(index, MainUndoStack.getGlobalStack().addAction);
934                 } else if (selectedEntity is EntityCollection) {
935                         var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
936                         for each (var e:Entity in EntityCollection(selectedEntity).entities) rel.removeMember(e,undo.push);
937                         MainUndoStack.getGlobalStack().addAction(undo);
938                 }
939       }
940
941       public function changeFeatureType(event:Event):void {
942           if ( selectedEntity == null )
943               return;
944
945           UIComponent.suspendBackgroundProcessing();
946           var newFeature:Feature = currentCategorySelector.selectedType;
947           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
948           var action:CompositeUndoableAction = new CompositeUndoableAction(
949                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
950                   selectedEntity.suspend();
951           
952           // build a list of tags that are editable in new feature
953           var editableTags:Array = new Array();
954           for each( var editor:EditorFactory in newFeature.editors ) {
955               if ( editor is SingleTagEditorFactory ) {
956                   var singleTagEditor:SingleTagEditorFactory = editor as SingleTagEditorFactory;
957                   editableTags.push(singleTagEditor.key);
958               }
959           }
960
961           // remove tags from the current feature
962           if ( feature != null ) {
963               for each( var oldtag:Object in feature.tags ) {
964                   if ( editableTags.indexOf(oldtag["k"]) < 0 ) {
965                       selectedEntity.setTag(oldtag["k"], null, action.push);
966                   }
967               }
968           }
969
970           // set tags for new feature
971           if ( newFeature != null ) {
972               for each( var newtag:Object in newFeature.tags ) {
973                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
974               }
975           }
976
977                   selectedEntity.resume();
978           undoStack(action);
979           popupChange.close();
980           initialiseEditors();
981           UIComponent.resumeBackgroundProcessing();
982       }
983
984   ]]></fx:Script>
985 </mx:VBox>
986