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