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