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