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