Drag and drop reordering of relation members
[potlatch2.git] / net / systemeD / potlatch2 / TagViewer.mxml
1 <?xml version="1.0" encoding="utf-8"?>
2 <mx:VBox
3         xmlns:mx="http://www.adobe.com/2006/mxml"
4         xmlns:flexlib="flexlib.containers.*"
5     backgroundColor="white"
6     initialize="loadFeatures()">
7
8   <mx:ViewStack id="stack" width="100%" height="100%">
9   <mx:VBox width="100%" height="100%" label="Simple">
10     <mx:HBox borderStyle="inset" verticalAlign="middle" width="100%" paddingLeft="3" id="iconContainer">
11         <mx:Image id="iconImage"/>
12         <mx:VBox width="100%" verticalGap="1">
13           <mx:PopUpButton id="popupChange" creationComplete="initFeatureBox()" openAlways="true" width="100%"/>
14           <mx:Text condenseWhite="true" width="100%" id="iconText"/>
15         </mx:VBox>
16         <mx:LinkButton label="?" click="openDescription()" id="helpLabel"/>
17     </mx:HBox>
18     <flexlib:SuperTabNavigator id="editorStack" width="100%" height="100%" paddingLeft="2" paddingRight="2"
19         allowTabSqueezing="false" minTabWidth="10" closePolicy="close_never"
20         scrollSpeed="20" change="ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox)"/>
21   </mx:VBox>
22
23   <mx:VBox width="100%" height="100%" label="Advanced" initialize="checkAdvanced()" verticalGap="1">
24     <mx:Label id="advancedID">
25       <mx:htmlText><![CDATA[<i>No Selection</i>]]></mx:htmlText>
26     </mx:Label>
27
28     <mx:DataGrid editable="true" width="100%" height="75%" id="advancedTagGrid">
29             <mx:columns>
30                 <mx:DataGridColumn editable="true" dataField="key" headerText="Key"/>
31                 <mx:DataGridColumn editable="true" dataField="value" headerText="Value"/>
32             </mx:columns>
33     </mx:DataGrid>
34
35     <mx:HBox horizontalAlign="right" width="100%">
36       <mx:LinkButton label="Delete" click="removeTag()" enabled="{advancedTagGrid.selectedItem != null? true : false}"/>
37       <mx:LinkButton label="Add" click="addNewTag()"/>
38     </mx:HBox>
39     
40     <mx:DataGrid editable="true" width="100%" height="25%" id="relationsGrid"
41         doubleClickEnabled="true"
42         itemDoubleClick="editRelation(relationsGrid.selectedItem.id)">
43         <mx:columns>
44             <mx:DataGridColumn editable="false" dataField="description" headerText="Relation"/>
45             <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
46             <mx:DataGridColumn editable="true" dataField="role" headerText="Role"/>
47         </mx:columns>
48     </mx:DataGrid>
49
50     <mx:HBox horizontalAlign="right" width="100%">
51       <mx:LinkButton label="Remove from" click="removeFromRelation(relationsGrid.selectedItem.id, relationsGrid.selectedItem.index)" 
52                       enabled="{relationsGrid.selectedItem != null? true : false}"/>
53       <mx:LinkButton label="Add to" click="addToRelation()"/>
54     </mx:HBox>
55
56   </mx:VBox>
57
58   <mx:VBox width="100%" height="100%" label="Members" id="membersVBox" initialize="checkMembers()" verticalGap="1">
59     <mx:Label id="membersText" text="Relation Members"/>
60     <mx:DataGrid editable="true" width="100%" height="100%" id="membersGrid"
61                   dragEnabled="true" dragMoveEnabled="true" dropEnabled="true">
62       <mx:columns>
63         <mx:DataGridColumn editable="false" dataField="type" headerText="Type"/>
64         <mx:DataGridColumn editable="false" dataField="id" headerText="ID"/>
65         <mx:DataGridColumn editable="true" dataField="role" headerText="Role"/>
66       </mx:columns>
67     </mx:DataGrid>
68   </mx:VBox>
69   
70   </mx:ViewStack>
71
72   <mx:LinkBar dataProvider="{stack}"/>
73
74   <mx:Script><![CDATA[
75       import net.systemeD.halcyon.connection.*;
76       import net.systemeD.potlatch2.mapfeatures.*;
77
78       import mx.collections.*;
79       import mx.containers.*;
80       import mx.events.*;
81       import mx.core.*;
82       import mx.managers.PopUpManager;
83       import flash.geom.Point;
84       import flash.net.*;
85       
86       private var mapFeatures:MapFeatures;
87       private var selectedEntity:Entity;
88       private var tagDataProvider:ArrayCollection;
89       private var tw:CategorySelector = null;
90       private var feature:Feature = null;
91
92       public function setEntity(entity:Entity):void {
93           if ( selectedEntity != entity ) {
94               if ( selectedEntity != null )
95                   selectedEntity.removeEventListener(Connection.TAG_CHANGE, tagChanged);
96               selectedEntity = entity;
97               if ( selectedEntity != null )
98                   selectedEntity.addEventListener(Connection.TAG_CHANGE, tagChanged);
99           }
100
101           if ( advancedID != null )
102               setupAdvanced(entity);
103           if (entity is Relation) {
104               stack.addChild(membersVBox);
105           }
106           refreshFeatureIcon();
107       }
108
109       private function refreshFeatureIcon():void {
110           var oldFeature:Feature = feature;
111           feature = selectedEntity == null ? null : mapFeatures.findMatchingFeature(selectedEntity);
112           if ( feature != oldFeature )
113               initialiseEditors();
114
115           if ( feature != null )
116               setFeatureIcon(selectedEntity, feature);
117           else
118               blankFeatureIcon(selectedEntity);
119       }
120
121       private function setFeatureIcon(entity:Entity, feature:Feature):void {
122           //blankFeatureIcon(entity);
123           
124           iconImage.source = feature.image;
125
126           var txt:String = feature.htmlDetails(entity);
127           iconText.htmlText = txt;
128           popupChange.label = feature.name;
129           setLimitTypes(entity);
130           tw.setSelectedFeature(feature);
131           helpLabel.visible = feature.hasHelpURL();
132       }
133       
134       private function setLimitTypes(entity:Entity):void {
135           var type:String = null;
136           if ( entity is Node )
137               type = "point";
138           else if ( entity is Way )
139               type = Way(entity).isArea() ? "area" : "line";
140           else if ( entity is Relation )
141               type = "relation";
142           tw.setLimitTypes(type);
143       }
144
145       private function blankFeatureIcon(entity:Entity):void {
146           iconImage.source = null;
147           iconText.htmlText = entity == null ?
148                "<i>Nothing selected</i>" :
149                "<b>Not recognised</b><br/>Try looking at the tags under the advanced properties";
150           popupChange.label = "unknown";
151           setLimitTypes(entity);
152           tw.setSelectedFeature(null);
153           helpLabel.visible = false;
154       }
155
156       private var tabComponents:Object = {};
157       
158       private function initialiseEditors():void {
159           editorStack.removeAllChildren();
160           if ( selectedEntity == null || feature == null )
161               return;
162           
163           var editorBox:VBox = createEditorBox();
164           editorBox.label = "Basic";
165           editorStack.addChild(editorBox);
166           
167           var tabs:Object = {};
168           tabComponents = {};
169           
170           for each (var factory:EditorFactory in feature.editors) {
171               if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
172                   var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
173                   if ( editor != null )
174                       editorBox.addChild(editor);
175               }
176               var category:String = factory.category;
177               var tab:VBox = tabs[category];
178               if ( tab == null ) {
179                   tab = createEditorBox();
180                   tab.label = category;
181                   editorStack.addChild(tab);
182                   tabs[category] = tab;
183                   tabComponents[tab] = [];
184               }
185               var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
186               if ( catEditor != null )
187                   tabComponents[tab].push(catEditor);
188               //    tab.addChild(catEditor);
189           }
190       }
191       
192       private function createEditorBox():VBox {
193           var box:VBox = new VBox();
194           box.percentWidth = 100;
195           box.percentHeight = 100;
196           return box;
197       }
198
199       private function ensureEditorsPopulated(tab:VBox):void {
200           var components:Array = tabComponents[tab];
201           if ( components == null || tab == null || tab.numChildren >= components.length )
202               return;
203           for each (var component:DisplayObject in components ) {
204               tab.addChild(component);
205           }
206       }
207       
208       private function checkAdvanced():void {
209           if ( selectedEntity != null )
210              setupAdvanced(selectedEntity);
211       }
212
213       private function setupAdvanced(entity:Entity):void {
214           if ( tagDataProvider == null ) {
215               tagDataProvider = new ArrayCollection();
216               advancedTagGrid.dataProvider = tagDataProvider;
217           }
218
219           tagDataProvider.removeAll();
220           
221           if ( entity == null ) {
222               advancedID.htmlText = "";
223           } else {
224               var entityText:String = "xx";
225               if ( entity is Node ) entityText = "Node";
226               else if ( entity is Way ) entityText = "Way";
227               else if ( entity is Relation ) entityText = "Relation";
228               advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
229
230               var tags:Array = entity.getTagArray();
231               tags.sortOn("key");
232               for each(var tag:Tag in tags)
233                   tagDataProvider.addItem(tag);
234           }
235           
236           if ( entity == null ) {
237               relationsGrid.dataProvider = null;
238           } else {
239               var relations:Array = [];
240               for each( var rel:Relation in entity.parentRelations ) {
241                   for each( var memberIndex:int in rel.findEntityMemberIndexes(entity)) {
242                     var props:Object = {};
243                     props["relation"] = rel;
244                     props["id"] = rel.id;
245                     props["index"] = memberIndex;
246                     props["role"] = rel.getMember(memberIndex).role;
247                     props["description"] = rel.getDescription();
248                     props["id_idx"] = rel.id + "/"+memberIndex;
249                     
250                     relations.push(props);
251                   }
252               }
253               relationsGrid.dataProvider = relations;
254           }
255       }
256       
257       private function checkMembers():void {
258           if (selectedEntity is Relation) {
259             setupMembers(selectedEntity as Relation);
260           }
261       }
262       
263       private function setupMembers(rel:Relation):void {
264           var members:Array = [];
265           for (var i:int=0 ; i<rel.length; i++) {
266             var props:Object = {};
267             var member:RelationMember = rel.getMember(i);
268             props["id"] = member.entity.id;
269             props["type"] = member.entity.getType();
270             props["role"] = member.role;
271             
272             members.push(props);
273           }
274           membersGrid.dataProvider = members;
275           membersGrid.dataProvider.addEventListener('collectionChange', membersChange); 
276       }
277       
278       private function membersChange(event:Event):void {
279           // Dropping all the members and re-adding them isn't exactly optimal
280           // but is at least robust for any kind of change.
281           // Figuring out a better way is someone else's FIXME
282           
283           var conn:Connection = Connection.getConnectionInstance();
284           var rel:Relation = selectedEntity as Relation
285           
286           // drop members
287           trace("Dropping "+rel.length+" members");
288           for (var i:int=rel.length-1 ; i>=0; i--) {
289             rel.removeMemberByIndex(i);
290           }
291           
292           // add members in new order
293           for each(var memberObject:Object in membersGrid.dataProvider) {
294             var e:Entity;
295             var id:int = memberObject.id;
296             if(memberObject.type == 'node') {
297               e = conn.getNode(id);
298             } else if (memberObject.type == 'way') {
299               e = conn.getWay(id);
300             } else if (memberObject.type == 'relation') {
301               e = conn.getRelation(id);
302             }
303             rel.appendMember(new RelationMember(e, memberObject.role));
304             trace("added member "+memberObject.type+" "+id+" in role "+memberObject.role);
305           }
306           trace("complete: relation "+rel.id+" now has "+rel.length+" members");
307       }
308       
309       private function editRelation(id:uint):void {
310           trace("edit relation "+id);
311           var panel:RelationEditorPanel = RelationEditorPanel(
312               PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
313           panel.setRelation(Connection.getConnectionInstance().getRelation(id));
314           PopUpManager.centerPopUp(panel);
315       }
316       
317       private function tagChanged(event:TagEvent):void {
318           refreshFeatureIcon();
319           
320           if ( tagDataProvider != null ) {
321               // check to see if the key is already in our list
322               var exists:Boolean = false;
323               var tag:Tag = null;
324               var i:uint;
325               for ( i = 0; i < tagDataProvider.length && !exists; i++ ) {
326                   tag = Tag(tagDataProvider.getItemAt(i));
327                   exists = tag.key == event.key;
328               }
329               if ( !exists ) {
330                   tag = new Tag(selectedEntity, event.key, event.newValue);
331                   tagDataProvider.addItem(tag);
332                   tagDataProvider.refresh();
333               } else {
334                   if ( event.newValue == null ) {
335                       tagDataProvider.removeItemAt(i-1);
336                       tagDataProvider.refresh();
337                   } else {
338                       tagDataProvider.itemUpdated(tag, "value");
339                   }
340               }
341           }
342       }
343
344       public function loadFeatures():void {
345           mapFeatures = MapFeatures.getInstance();
346           stack.removeChild(membersVBox); // remove by default, will be added if relation
347       }
348
349       public function openDescription():void {
350           trace("open description here");
351           if ( feature != null && feature.hasHelpURL() )
352               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
353       }
354
355       public function addNewTag():void {
356           var newKey:String = "(new tag)";
357           var newTag:Tag = new Tag(selectedEntity, newKey, "(new value)");
358           tagDataProvider.addItem(newTag);
359           advancedTagGrid.editedItemPosition = {rowIndex: tagDataProvider.getItemIndex(newTag), columnIndex: 0};
360       }
361
362       public function removeTag():void {
363           var k:String = advancedTagGrid.selectedItem.key;
364           selectedEntity.setTag(k, null);
365       }
366       
367       public function addToRelation():void {
368           new RelationSelectPanel().init(selectedEntity);        
369       }
370       
371       public function removeFromRelation(id:Number, index:int):void {
372           Connection.getConnectionInstance().getRelation(id).removeMemberByIndex(index);
373       }
374       
375       public function initFeatureBox():void {
376           tw = new CategorySelector();
377           tw.addEventListener("selectedType", changeFeatureType);
378           popupChange.popUp = tw;
379       }
380       
381       public function changeFeatureType(event:Event):void {
382           if ( selectedEntity == null )
383               return;
384
385           var newFeature:Feature = tw.selectedType;
386           
387           // remove tags from the current feature
388           if ( feature != null ) {
389               for each( var oldtag:Object in feature.tags ) {
390                   selectedEntity.setTag(oldtag["k"], null);
391               }
392           }
393           
394           // set tags for new feature
395           if ( newFeature != null ) {
396               for each( var newtag:Object in newFeature.tags ) {
397                   selectedEntity.setTag(newtag["k"], newtag["v"]);
398               }
399           }
400           
401           popupChange.close();
402       }
403   ]]></mx:Script>
404 </mx:VBox>
405