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