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