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