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