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