bugfix
[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           if (selectedEntity == null) {
148             sidebar.selectedChild = dndPanel;
149           } else {
150             initialiseEditors();
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               setFeatureIcon(selectedEntity, feature);
167           } else {
168               blankFeatureIcon(selectedEntity);
169           }
170       }
171
172       private function featureImageChanged(event:Event):void {
173           setFeatureIcon(selectedEntity, feature);
174       }
175       
176       private function setFeatureIcon(entity:Entity, feature:Feature):void {
177           //blankFeatureIcon(entity);
178           
179           iconImage.source = feature.image;
180
181           var txt:String = feature.htmlDetails(entity);
182           iconText.htmlText = txt;
183           popupChange.label = feature.name;
184           setLimitTypes(entity);
185           tw.setSelectedFeature(feature);
186           helpLabel.visible = feature.hasHelpURL();
187       }
188       
189       private function setLimitTypes(entity:Entity):void {
190           var type:String = null;
191           if ( entity is Node )
192               type = "point";
193           else if ( entity is Way )
194               type = Way(entity).isArea() ? "area" : "line";
195           else if ( entity is Relation )
196               type = "relation";
197           tw.setLimitTypes(type);
198       }
199
200       private function blankFeatureIcon(entity:Entity):void {
201           iconImage.source = null;
202                   if (entity == null) { 
203                         iconText.htmlText = "<i>Nothing selected</i>";
204                   } else if (entity.hasTags()) {
205                         iconText.htmlText = "<b>Not recognised</b><br/>Try looking at the tags under the advanced properties";
206                   } else {
207                         iconText.htmlText = "<b>No tags set</b><br/>Use the menu above to say what this "+entity.getType()+" is";
208           }
209           popupChange.label = "unknown";
210           setLimitTypes(entity);
211           tw.setSelectedFeature(null);
212           helpLabel.visible = false;
213       }
214
215       private var tabComponents:Object = {};
216       
217       private function initialiseEditors():void {
218           editorStack.removeAllChildren();
219           if ( selectedEntity == null || feature == null )
220               return;
221           
222           var editorBox:VBox = createEditorBox();
223           editorBox.label = "Basic";
224           editorStack.addChild(editorBox);
225           
226           var tabs:Object = {};
227           tabComponents = {};
228           
229           for each (var factory:EditorFactory in feature.editors) {
230               if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
231                   var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
232                   if ( editor != null )
233                       editorBox.addChild(editor);
234               }
235               var category:String = factory.category;
236               var tab:VBox = tabs[category];
237               if ( tab == null ) {
238                   tab = createEditorBox();
239                   tab.label = category;
240                   editorStack.addChild(tab);
241                   tabs[category] = tab;
242                   tabComponents[tab] = [];
243               }
244               var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
245               if ( catEditor != null )
246                   tabComponents[tab].push(catEditor);
247               //    tab.addChild(catEditor);
248           }
249       }
250       
251       private function createEditorBox():VBox {
252           var box:VBox = new VBox();
253           box.percentWidth = 100;
254           box.percentHeight = 100;
255           return box;
256       }
257
258       private function ensureEditorsPopulated(tab:VBox):void {
259           var components:Array = tabComponents[tab];
260           if ( components == null || tab == null || tab.numChildren >= components.length )
261               return;
262           for each (var component:DisplayObject in components ) {
263               tab.addChild(component);
264           }
265       }
266
267         private function tabSelected():void {
268                 if (editorStack.selectedIndex<0) { return; }
269                 // This fixes a Flex TabNavigator bug where the tab would be selected, but not actually skinned properly
270                 for (var i:uint=0; i<editorStack.numChildren; i++) {
271                         editorStack.getTabAt(i).selected=(i==editorStack.selectedIndex);
272                 }
273         }
274       
275       private function checkAdvanced():void {
276           if ( selectedEntity != null )
277              setupAdvanced(selectedEntity);
278       }
279
280       private var listeningToRelations:Array = [];
281       
282       private function setupAdvanced(entity:Entity):void {
283           if ( tagDataProvider == null ) {
284               tagDataProvider = new ArrayCollection();
285               advancedTagGrid.dataProvider = tagDataProvider;
286           }
287
288           tagDataProvider.removeAll();
289           
290           if ( entity == null ) {
291               advancedID.htmlText = "";
292           } else {
293               var entityText:String = "xx";
294               if ( entity is Node ) entityText = "Node";
295               else if ( entity is Way ) entityText = "Way";
296               else if ( entity is Relation ) entityText = "Relation";
297               advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
298
299               var tags:Array = entity.getTagArray();
300               tags.sortOn("key");
301               for each(var tag:Tag in tags)
302                   tagDataProvider.addItem(tag);
303           }
304                     
305           removeRelationListeners();
306           if ( selectedEntity != null ) {
307               selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
308               selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
309           }
310           
311           if ( entity == null ) {
312               relationsGrid.dataProvider = null;
313           } else {
314               resetRelationsGrid(entity);
315               entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
316               entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
317           }
318       }
319       
320       private function addedToRelation(event:RelationMemberEvent):void {
321          resetRelationsGrid(selectedEntity);
322       }
323
324       private function removedFromRelation(event:RelationMemberEvent):void {
325          resetRelationsGrid(selectedEntity);
326       }
327
328       private function removeRelationListeners():void {
329           for each( var rel:Relation in listeningToRelations ) {
330               rel.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
331               rel.removeEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
332               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
333           }
334           listeningToRelations = [];
335           relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
336       }
337             
338       private function resetRelationsGrid(entity:Entity):void {
339           removeRelationListeners();
340           var relations:Array = [];
341           for each( var rel:Relation in entity.parentRelations ) {
342               for each( var memberIndex:int in rel.findEntityMemberIndexes(entity)) {
343                   var props:Object = {};
344                   props["relation"] = rel;
345                   props["id"] = rel.id;
346                   props["index"] = memberIndex;
347                   props["role"] = rel.getMember(memberIndex).role;
348                   props["description"] = rel.getDescription();
349                   props["id_idx"] = rel.id + "/"+memberIndex;
350
351                   relations.push(props);
352               }
353               
354               rel.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
355               rel.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
356               rel.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
357               listeningToRelations.push(rel);
358           }
359           relationsGrid.dataProvider = relations;
360           relationsGrid.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
361       }
362       
363       private function relationRoleChanged(event:DataGridEvent):void {
364                 if (event.dataField != 'role') { return; }      // shouldn't really happen
365
366                 var relations:Array=event.currentTarget.dataProvider.toArray();
367                 var props:Object=relations[event.rowIndex];
368
369                 var relation:Relation=props['relation'];
370                 var index:uint=props['index'];
371                 var newRole:String=event.itemRenderer.data['role'];
372
373                 relation.setMember(index, new RelationMember(selectedEntity,newRole));
374       }
375
376       private function relationTagChanged(event:TagEvent):void {
377           resetRelationsGrid(selectedEntity);
378       }
379
380       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
381           resetRelationsGrid(selectedEntity);
382       }
383       
384       private function checkMembers():void {
385           if (selectedEntity is Relation) {
386             setupMembers(selectedEntity as Relation);
387           }
388       }
389       
390       private function setupMembers(rel:Relation):void {
391           var members:Array = [];
392           for (var i:int=0 ; i<rel.length; i++) {
393             var props:Object = {};
394             var member:RelationMember = rel.getMember(i);
395             props["id"] = member.entity.id;
396             props["type"] = member.entity.getType();
397             props["role"] = member.role;
398             
399             members.push(props);
400           }
401           membersGrid.dataProvider = members;
402           membersGrid.dataProvider.addEventListener('collectionChange', membersChange); 
403       }
404       
405       private function membersChange(event:Event):void {
406           // Dropping all the members and re-adding them isn't exactly optimal
407           // but is at least robust for any kind of change.
408           // Figuring out a better way is someone else's FIXME
409           
410           var conn:Connection = Connection.getConnectionInstance();
411           var rel:Relation = selectedEntity as Relation
412           
413           // drop members
414           trace("Dropping "+rel.length+" members");
415           for (var i:int=rel.length-1 ; i>=0; i--) {
416             rel.removeMemberByIndex(i);
417           }
418           
419           // add members in new order
420           for each(var memberObject:Object in membersGrid.dataProvider) {
421             var e:Entity;
422             var id:Number = memberObject.id;
423             if(memberObject.type == 'node') {
424               e = conn.getNode(id);
425             } else if (memberObject.type == 'way') {
426               e = conn.getWay(id);
427             } else if (memberObject.type == 'relation') {
428               e = conn.getRelation(id);
429             }
430             rel.appendMember(new RelationMember(e, memberObject.role));
431             trace("added member "+memberObject.type+" "+id+" in role "+memberObject.role);
432           }
433           trace("complete: relation "+rel.id+" now has "+rel.length+" members");
434       }
435       
436       private function editRelation(id:Number):void {
437           var panel:RelationEditorPanel = RelationEditorPanel(
438               PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
439           panel.setRelation(Connection.getConnectionInstance().getRelation(id));
440           PopUpManager.centerPopUp(panel);
441       }
442       
443       private function tagChanged(event:TagEvent):void {
444           refreshFeatureIcon();
445           
446           if ( tagDataProvider != null ) {
447               // check to see if the key is already in our list
448               var exists:Boolean = false;
449               var tag:Tag = null;
450               var i:uint;
451               for ( i = 0; i < tagDataProvider.length && !exists; i++ ) {
452                   tag = Tag(tagDataProvider.getItemAt(i));
453                   exists = tag.key == event.key;
454               }
455               if ( !exists ) {
456                   tag = new Tag(selectedEntity, event.key, event.newValue);
457                   tagDataProvider.addItem(tag);
458                   tagDataProvider.refresh();
459               } else {
460                   if ( event.newValue == null ) {
461                       tagDataProvider.removeItemAt(i-1);
462                       tagDataProvider.refresh();
463                   } else {
464                       tagDataProvider.itemUpdated(tag, "value");
465                   }
466               }
467           }
468       }
469
470       public function loadFeatures():void {
471           mapFeatures = MapFeatures.getInstance();
472           stack.removeChild(membersVBox); // remove by default, will be added if relation
473       }
474
475       public function openDescription():void {
476           trace("open description here");
477           if ( feature != null && feature.hasHelpURL() )
478               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
479       }
480
481       public function addNewTag():void {
482           var newKey:String = "(new tag)";
483           var newTag:Tag = new Tag(selectedEntity, newKey, "(new value)");
484           tagDataProvider.addItem(newTag);
485           advancedTagGrid.editedItemPosition = {rowIndex: tagDataProvider.getItemIndex(newTag), columnIndex: 0};
486       }
487
488       public function removeTag():void {
489           var k:String = advancedTagGrid.selectedItem.key;
490           selectedEntity.setTag(k, null, MainUndoStack.getGlobalStack().addAction);
491       }
492       
493       public function addToRelation():void {
494           new RelationSelectPanel().init(selectedEntity,new Object());
495       }
496       
497       public function removeFromRelation(id:Number, index:int):void {
498           Connection.getConnectionInstance().getRelation(id).removeMemberByIndex(index);
499       }
500       
501       public function initFeatureBox():void {
502           tw = new CategorySelector();
503           tw.addEventListener("selectedType", changeFeatureType);
504           popupChange.popUp = tw;
505       }
506       
507       public function changeFeatureType(event:Event):void {
508           if ( selectedEntity == null )
509               return;
510
511           var newFeature:Feature = tw.selectedType;
512           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
513           var action:CompositeUndoableAction = new CompositeUndoableAction(
514                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
515                   selectedEntity.suspend();
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                   selectedEntity.resume();
532           undoStack(action);
533           popupChange.close();
534           initialiseEditors();
535       }
536       
537       private function dragPOI(event:MouseEvent, tags:Array):void {
538           // Get the drag initiator component from the event object.
539           var dragInitiator:Image = event.currentTarget as Image;
540           var dragSource:DragSource = new DragSource();
541           dragSource.addData(tags, 'tags');
542           
543           var dragProxy:Image = new Image();
544           dragProxy.source = event.currentTarget.source;
545           
546           DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
547       }
548   ]]></mx:Script>
549 </mx:VBox>
550