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