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