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