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