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