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