Display the name of the POI when mouse-overing on the drag and drop 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%">
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)"/>
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       }
323             
324       private function resetRelationsGrid(entity:Entity):void {
325           removeRelationListeners();
326           var relations:Array = [];
327           for each( var rel:Relation in entity.parentRelations ) {
328               for each( var memberIndex:int in rel.findEntityMemberIndexes(entity)) {
329                   var props:Object = {};
330                   props["relation"] = rel;
331                   props["id"] = rel.id;
332                   props["index"] = memberIndex;
333                   props["role"] = rel.getMember(memberIndex).role;
334                   props["description"] = rel.getDescription();
335                   props["id_idx"] = rel.id + "/"+memberIndex;
336
337                   relations.push(props);
338               }
339               
340               rel.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
341               rel.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
342               rel.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
343               listeningToRelations.push(rel);
344           }
345           relationsGrid.dataProvider = relations;
346       }
347       
348       private function relationTagChanged(event:TagEvent):void {
349           resetRelationsGrid(selectedEntity);
350       }
351
352       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
353           resetRelationsGrid(selectedEntity);
354       }
355       
356       private function checkMembers():void {
357           if (selectedEntity is Relation) {
358             setupMembers(selectedEntity as Relation);
359           }
360       }
361       
362       private function setupMembers(rel:Relation):void {
363           var members:Array = [];
364           for (var i:int=0 ; i<rel.length; i++) {
365             var props:Object = {};
366             var member:RelationMember = rel.getMember(i);
367             props["id"] = member.entity.id;
368             props["type"] = member.entity.getType();
369             props["role"] = member.role;
370             
371             members.push(props);
372           }
373           membersGrid.dataProvider = members;
374           membersGrid.dataProvider.addEventListener('collectionChange', membersChange); 
375       }
376       
377       private function membersChange(event:Event):void {
378           // Dropping all the members and re-adding them isn't exactly optimal
379           // but is at least robust for any kind of change.
380           // Figuring out a better way is someone else's FIXME
381           
382           var conn:Connection = Connection.getConnectionInstance();
383           var rel:Relation = selectedEntity as Relation
384           
385           // drop members
386           trace("Dropping "+rel.length+" members");
387           for (var i:int=rel.length-1 ; i>=0; i--) {
388             rel.removeMemberByIndex(i);
389           }
390           
391           // add members in new order
392           for each(var memberObject:Object in membersGrid.dataProvider) {
393             var e:Entity;
394             var id:int = memberObject.id;
395             if(memberObject.type == 'node') {
396               e = conn.getNode(id);
397             } else if (memberObject.type == 'way') {
398               e = conn.getWay(id);
399             } else if (memberObject.type == 'relation') {
400               e = conn.getRelation(id);
401             }
402             rel.appendMember(new RelationMember(e, memberObject.role));
403             trace("added member "+memberObject.type+" "+id+" in role "+memberObject.role);
404           }
405           trace("complete: relation "+rel.id+" now has "+rel.length+" members");
406       }
407       
408       private function editRelation(id:uint):void {
409           trace("edit relation "+id);
410           var panel:RelationEditorPanel = RelationEditorPanel(
411               PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
412           panel.setRelation(Connection.getConnectionInstance().getRelation(id));
413           PopUpManager.centerPopUp(panel);
414       }
415       
416       private function tagChanged(event:TagEvent):void {
417           refreshFeatureIcon();
418           
419           if ( tagDataProvider != null ) {
420               // check to see if the key is already in our list
421               var exists:Boolean = false;
422               var tag:Tag = null;
423               var i:uint;
424               for ( i = 0; i < tagDataProvider.length && !exists; i++ ) {
425                   tag = Tag(tagDataProvider.getItemAt(i));
426                   exists = tag.key == event.key;
427               }
428               if ( !exists ) {
429                   tag = new Tag(selectedEntity, event.key, event.newValue);
430                   tagDataProvider.addItem(tag);
431                   tagDataProvider.refresh();
432               } else {
433                   if ( event.newValue == null ) {
434                       tagDataProvider.removeItemAt(i-1);
435                       tagDataProvider.refresh();
436                   } else {
437                       tagDataProvider.itemUpdated(tag, "value");
438                   }
439               }
440           }
441       }
442
443       public function loadFeatures():void {
444           mapFeatures = MapFeatures.getInstance();
445           stack.removeChild(membersVBox); // remove by default, will be added if relation
446       }
447
448       public function openDescription():void {
449           trace("open description here");
450           if ( feature != null && feature.hasHelpURL() )
451               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
452       }
453
454       public function addNewTag():void {
455           var newKey:String = "(new tag)";
456           var newTag:Tag = new Tag(selectedEntity, newKey, "(new value)");
457           tagDataProvider.addItem(newTag);
458           advancedTagGrid.editedItemPosition = {rowIndex: tagDataProvider.getItemIndex(newTag), columnIndex: 0};
459       }
460
461       public function removeTag():void {
462           var k:String = advancedTagGrid.selectedItem.key;
463           selectedEntity.setTag(k, null, MainUndoStack.getGlobalStack().addAction);
464       }
465       
466       public function addToRelation():void {
467           new RelationSelectPanel().init(selectedEntity);        
468       }
469       
470       public function removeFromRelation(id:Number, index:int):void {
471           Connection.getConnectionInstance().getRelation(id).removeMemberByIndex(index);
472       }
473       
474       public function initFeatureBox():void {
475           tw = new CategorySelector();
476           tw.addEventListener("selectedType", changeFeatureType);
477           popupChange.popUp = tw;
478       }
479       
480       public function changeFeatureType(event:Event):void {
481           if ( selectedEntity == null )
482               return;
483
484           var newFeature:Feature = tw.selectedType;
485           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
486           var action:CompositeUndoableAction = new CompositeUndoableAction(
487                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
488
489           // remove tags from the current feature
490           if ( feature != null ) {
491               for each( var oldtag:Object in feature.tags ) {
492                   selectedEntity.setTag(oldtag["k"], null, action.push);
493               }
494           }
495           
496           // set tags for new feature
497           if ( newFeature != null ) {
498               for each( var newtag:Object in newFeature.tags ) {
499                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
500               }
501           }
502           
503           undoStack(action);
504           popupChange.close();
505       }
506       
507       private function dragPOI(event:MouseEvent, tags:Array):void {
508           // Get the drag initiator component from the event object.
509           var dragInitiator:Image = event.currentTarget as Image;
510           var dragSource:DragSource = new DragSource();
511           dragSource.addData(tags, 'tags');
512           
513           var dragProxy:Image = new Image();
514           dragProxy.source = event.currentTarget.source;
515           
516           DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
517       }
518   ]]></mx:Script>
519 </mx:VBox>
520