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