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