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