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