Add support for relations to match multiple tags. Turned out to be a bit more involve...
[potlatch2.git] / net / systemeD / halcyon / connection / Connection.as
1 package net.systemeD.halcyon.connection {
2
3     import flash.events.Event;
4     import flash.events.EventDispatcher;
5     import flash.net.*;
6     
7     import net.systemeD.halcyon.AttentionEvent;
8     import net.systemeD.halcyon.MapEvent;
9     import net.systemeD.halcyon.connection.actions.*;
10
11         public class Connection extends EventDispatcher {
12
13         private static var connectionInstance:Connection = null;
14
15         protected static var policyURL:String;
16         protected static var apiBaseURL:String;
17         protected static var params:Object;
18
19         public static function getConnection(initparams:Object=null):Connection {
20             if ( connectionInstance == null ) {
21             
22                 params = initparams == null ? new Object() : initparams;
23                 policyURL = getParam("policy", "http://127.0.0.1:3000/api/crossdomain.xml");
24                 apiBaseURL = getParam("api", "http://127.0.0.1:3000/api/0.6/");
25                 var connectType:String = getParam("connection", "XML");
26                 
27                 if ( connectType == "XML" )
28                     connectionInstance = new XMLConnection();
29                 else if ( connectType == "OSM" )
30                     connectionInstance = new OSMConnection();
31                 else
32                     connectionInstance = new AMFConnection();
33             }
34             return connectionInstance;
35         }
36
37         public static function getParam(name:String, defaultValue:String):String {
38             return params[name] == null ? defaultValue : params[name];
39         }
40
41         public function get apiBase():String {
42             return apiBaseURL;
43         }
44
45         public static function get serverName():String {
46             return getParam("serverName", "Localhost");
47         }
48                 
49                 public static function getConnectionInstance():Connection {
50             return connectionInstance;
51                 }
52
53                 public function getEnvironment(responder:Responder):void {}
54
55         // connection events
56         public static var LOAD_STARTED:String = "load_started";
57         public static var LOAD_COMPLETED:String = "load_completed";
58         public static var SAVE_STARTED:String = "save_started";
59         public static var SAVE_COMPLETED:String = "save_completed";
60         public static var DATA_DIRTY:String = "data_dirty";
61         public static var DATA_CLEAN:String = "data_clean";
62         public static var NEW_CHANGESET:String = "new_changeset";
63         public static var NEW_CHANGESET_ERROR:String = "new_changeset_error";
64         public static var NEW_NODE:String = "new_node";
65         public static var NEW_WAY:String = "new_way";
66         public static var NEW_RELATION:String = "new_relation";
67         public static var NEW_POI:String = "new_poi";
68         public static var NODE_RENUMBERED:String = "node_renumbered";
69         public static var WAY_RENUMBERED:String = "way_renumbered";
70         public static var RELATION_RENUMBERED:String = "relation_renumbered";
71         public static var TAG_CHANGED:String = "tag_change";
72         public static var NODE_MOVED:String = "node_moved";
73         public static var NODE_ALTERED:String = "node_altered";
74         public static var WAY_NODE_ADDED:String = "way_node_added";
75         public static var WAY_NODE_REMOVED:String = "way_node_removed";
76         public static var WAY_REORDERED:String = "way_reordered";
77         public static var ENTITY_DRAGGED:String = "entity_dragged";
78                 public static var NODE_DELETED:String = "node_deleted";
79                 public static var WAY_DELETED:String = "way_deleted";
80                 public static var RELATION_DELETED:String = "relation_deleted";
81                 public static var RELATION_MEMBER_ADDED:String = "relation_member_added";
82                 public static var RELATION_MEMBER_REMOVED:String = "relation_member_deleted";
83                 public static var ADDED_TO_RELATION:String = "added_to_relation";
84                 public static var REMOVED_FROM_RELATION:String = "removed_from_relation";
85                 public static var SUSPEND_REDRAW:String = "suspend_redraw";
86                 public static var RESUME_REDRAW:String = "resume_redraw";
87         public static var TRACES_LOADED:String = "traces_loaded";
88
89         // store the data we download
90         private var negativeID:Number = -1;
91         private var nodes:Object = {};
92         private var ways:Object = {};
93         private var relations:Object = {};
94         private var pois:Array = [];
95         private var changeset:Changeset = null;
96                 private var changesetUpdated:Number;
97                 private var modified:Boolean = false;
98                 public var nodecount:int=0;
99                 public var waycount:int=0;
100                 public var relationcount:int=0;
101         private var traces:Array = [];
102         private var nodePositions:Object = {};
103         protected var traces_loaded:Boolean = false;
104
105         protected function get nextNegative():Number {
106             return negativeID--;
107         }
108
109         protected function setNode(node:Node, queue:Boolean):void {
110                         if (!nodes[node.id]) { nodecount++; }
111             nodes[node.id] = node;
112             addDupe(node);
113             if (node.loaded) { sendEvent(new EntityEvent(NEW_NODE, node),queue); }
114         }
115
116         protected function setWay(way:Way, queue:Boolean):void {
117                         if (!ways[way.id] && way.loaded) { waycount++; }
118             ways[way.id] = way;
119             if (way.loaded) { sendEvent(new EntityEvent(NEW_WAY, way),queue); }
120         }
121
122         protected function setRelation(relation:Relation, queue:Boolean):void {
123                         if (!relations[relation.id]) { relationcount++; }
124             relations[relation.id] = relation;
125             if (relation.loaded) { sendEvent(new EntityEvent(NEW_RELATION, relation),queue); }
126         }
127
128                 protected function setOrUpdateNode(newNode:Node, queue:Boolean):void {
129                 if (nodes[newNode.id]) {
130                                 var wasDeleted:Boolean=nodes[newNode.id].isDeleted();
131                                 nodes[newNode.id].update(newNode.version, newNode.getTagsHash(), true, newNode.parentsLoaded, newNode.lat, newNode.lon, newNode.uid, newNode.timestamp);
132                                 if (wasDeleted) sendEvent(new EntityEvent(NEW_NODE, nodes[newNode.id]), false);
133                         } else {
134                                 setNode(newNode, queue);
135                         }
136                 }
137
138                 protected function renumberNode(oldID:Number, newID:Number, version:uint):void {
139                         var node:Node=nodes[oldID];
140                         if (oldID!=newID) { removeDupe(node); }
141                         node.renumber(newID, version);
142                         if (oldID==newID) return;                                       // if only a version change, return
143                         nodes[newID]=node;
144                         addDupe(node);
145                         if (node.loaded) { sendEvent(new EntityRenumberedEvent(NODE_RENUMBERED, node, oldID),false); }
146                         delete nodes[oldID];
147                 }
148
149                 protected function renumberWay(oldID:Number, newID:Number, version:uint):void {
150                         var way:Way=ways[oldID];
151                         way.renumber(newID, version);
152                         if (oldID==newID) return;
153                         ways[newID]=way;
154                         if (way.loaded) { sendEvent(new EntityRenumberedEvent(WAY_RENUMBERED, way, oldID),false); }
155                         delete ways[oldID];
156                 }
157
158                 protected function renumberRelation(oldID:Number, newID:Number, version:uint):void {
159                         var relation:Relation=relations[oldID];
160                         relation.renumber(newID, version);
161                         if (oldID==newID) return;
162                         relations[newID] = relation;
163                         if (relation.loaded) { sendEvent(new EntityRenumberedEvent(RELATION_RENUMBERED, relation, oldID),false); }
164                         delete relations[oldID];
165                 }
166
167
168                 public function sendEvent(e:*,queue:Boolean):void {
169                         // queue is only used for AMFConnection
170                         dispatchEvent(e);
171                 }
172
173         public function registerPOI(node:Node):void {
174             if ( pois.indexOf(node) < 0 ) {
175                 pois.push(node);
176                 sendEvent(new EntityEvent(NEW_POI, node),false);
177             }
178         }
179
180         public function unregisterPOI(node:Node):void {
181             var index:uint = pois.indexOf(node);
182             if ( index >= 0 ) {
183                 pois.splice(index,1);
184             }
185         }
186
187         public function getNode(id:Number):Node {
188             return nodes[id];
189         }
190
191         public function getWay(id:Number):Way {
192             return ways[id];
193         }
194
195         public function getRelation(id:Number):Relation {
196             return relations[id];
197         }
198
199                 protected function findEntity(type:String, id:*):Entity {
200                         var i:Number=Number(id);
201                         switch (type.toLowerCase()) {
202                                 case 'node':     return getNode(id);
203                                 case 'way':      return getWay(id);
204                                 case 'relation': return getRelation(id);
205                                 default:         return null;
206                         }
207                 }
208
209                 // Remove data from Connection
210                 // These functions are used only internally to stop redundant data hanging around
211                 // (either because it's been deleted on the server, or because we have panned away
212                 //  and need to reduce memory usage)
213
214                 protected function killNode(id:Number):void {
215                         if (!nodes[id]) return;
216             nodes[id].dispatchEvent(new EntityEvent(Connection.NODE_DELETED, nodes[id]));
217                         removeDupe(nodes[id]);
218                         if (nodes[id].parentRelations.length>0) {
219                                 nodes[id].nullify();
220                         } else {
221                                 delete nodes[id];
222                         }
223                         nodecount--;
224                 }
225
226                 protected function killWay(id:Number):void {
227                         if (!ways[id]) return;
228             ways[id].dispatchEvent(new EntityEvent(Connection.WAY_DELETED, ways[id]));
229                         if (ways[id].parentRelations.length>0) {
230                                 ways[id].nullify();
231                         } else {
232                                 delete ways[id];
233                         }
234                         waycount--;
235                 }
236
237                 protected function killRelation(id:Number):void {
238                         if (!relations[id]) return;
239             relations[id].dispatchEvent(new EntityEvent(Connection.RELATION_DELETED, relations[id]));
240                         if (relations[id].parentRelations.length>0) {
241                                 relations[id].nullify();
242                         } else {
243                                 delete relations[id];
244                         }
245                         relationcount--;
246                 }
247
248                 protected function killWayWithNodes(id:Number):void {
249                         var way:Way=ways[id];
250                         var node:Node;
251                         for (var i:uint=0; i<way.length; i++) {
252                                 node=way.getNode(i);
253                                 if (node.isDirty) { continue; }
254                                 if (node.parentWays.length>1) {
255                                         node.removeParent(way);
256                                 } else {
257                                         killNode(node.id);
258                                 }
259                         }
260                         killWay(id);
261                 }
262                 
263                 protected function killEntity(entity:Entity):void {
264                         if (entity is Way) { killWay(entity.id); }
265                         else if (entity is Node) { killNode(entity.id); }
266                         else if (entity is Relation) { killRelation(entity.id); }
267                 }
268
269         public function createNode(tags:Object, lat:Number, lon:Number, performCreate:Function):Node {
270             var node:Node = new Node(nextNegative, 0, tags, true, lat, lon);
271             performCreate(new CreateEntityAction(node, setNode));
272                         //markDirty();
273             return node;
274         }
275
276         public function createWay(tags:Object, nodes:Array, performCreate:Function):Way {
277             var way:Way = new Way(nextNegative, 0, tags, true, nodes.concat());
278             performCreate(new CreateEntityAction(way, setWay));
279                         //markDirty();
280             return way;
281         }
282
283         public function createRelation(tags:Object, members:Array, performCreate:Function):Relation {
284             var relation:Relation = new Relation(nextNegative, 0, tags, true, members.concat());
285             performCreate(new CreateEntityAction(relation, setRelation));
286                         //markDirty();
287             return relation;
288         }
289
290         public function getAllNodeIDs():Array {
291             var list:Array = [];
292             for each (var node:Node in nodes)
293                 list.push(node.id);
294             return list;
295         }
296
297         public function getAllWayIDs():Array {
298             var list:Array = [];
299             for each (var way:Way in ways)
300                 list.push(way.id);
301             return list;
302         }
303
304         public function getAllRelationIDs():Array {
305             var list:Array = [];
306             for each (var relation:Relation in relations)
307                 list.push(relation.id);
308             return list;
309         }
310
311         /** Returns all available relations that match all of {k1: [v1,v2,...], k2: [v1...] ...} 
312         * where p1 is an array [v1, v2, v3...] */
313         public function getMatchingRelationIDs(match:Object):Array {
314             var list:Array = [];
315             for each (var relation:Relation in relations) {
316                 var ok: Boolean = true;
317                                 if (relation.deleted) { continue; }
318                                 for (var k:String in match) {
319                                         var v:String = relation.getTagsHash()[k];
320                                         if (!v || match[k].indexOf(v) < 0) { 
321                                            ok = false; break;  
322                                         }
323                                 }
324                                 if (ok) { list.push(relation.id); }
325                         }
326             return list;
327         }
328
329                 public function getObjectsByBbox(left:Number, right:Number, top:Number, bottom:Number):Object {
330                         var o:Object = { poisInside: [], poisOutside: [], waysInside: [], waysOutside: [] };
331                         for each (var way:Way in ways) {
332                                 if (way.within(left,right,top,bottom)) { o.waysInside.push(way); }
333                                                                   else { o.waysOutside.push(way); }
334                         }
335                         for each (var poi:Node in pois) {
336                                 if (poi.within(left,right,top,bottom)) { o.poisInside.push(poi); }
337                                                                   else { o.poisOutside.push(poi); }
338                         }
339                         return o;
340                 }
341
342                 public function purgeOutside(left:Number, right:Number, top:Number, bottom:Number):void {
343                         for each (var way:Way in ways) {
344                                 if (!way.within(left,right,top,bottom) && !way.isDirty && !way.locked && !way.hasLockedNodes()) {
345                                         killWayWithNodes(way.id);
346                                 }
347                         }
348                         for each (var poi:Node in pois) {
349                                 if (!poi.within(left,right,top,bottom) && !poi.isDirty && !poi.locked) {
350                                         killNode(poi.id);
351                                 }
352                         }
353                         // ** should purge relations too, if none of their members are on-screen
354                 }
355
356                 public function markDirty():void {
357             if (!modified) { dispatchEvent(new Event(DATA_DIRTY)); }
358                         modified=true;
359                 }
360                 public function markClean():void {
361             if (modified) { dispatchEvent(new Event(DATA_CLEAN)); }
362                         modified=false;
363                 }
364                 public function get isDirty():Boolean {
365                         return modified;
366                 }
367
368                 // Changeset tracking
369
370         protected function setActiveChangeset(changeset:Changeset):void {
371             this.changeset = changeset;
372                         changesetUpdated = new Date().getTime();
373             sendEvent(new EntityEvent(NEW_CHANGESET, changeset),false);
374         }
375
376                 protected function freshenActiveChangeset():void {
377                         changesetUpdated = new Date().getTime();
378                 }
379                 
380                 protected function closeActiveChangeset():void {
381                         changeset = null;
382                 }
383         
384         public function getActiveChangeset():Changeset {
385                         if (changeset && (new Date().getTime()) > (changesetUpdated+58*60*1000)) {
386                                 closeActiveChangeset();
387                         }
388             return changeset;
389         }
390
391         protected function addTrace(t:Object):void {
392             traces.push(t);
393         }
394
395         protected function clearTraces():void {
396             traces = [];
397         }
398
399         public function getTraces():Array {
400             return traces;
401         }
402
403         public function addDupe(node:Node):void {
404             if (getNode(node.id) != node) { return; } // make sure it's on this connection
405             var a:String = node.lat+","+node.lon;
406             if(!nodePositions[a]) {
407               nodePositions[a] = [];
408             }
409             nodePositions[a].push(node);
410             if (nodePositions[a].length > 1) { // don't redraw if it's the only node in town
411               for each (var n:Node in nodePositions[a]) {
412                 n.dispatchEvent(new Event(Connection.NODE_ALTERED));
413               }
414             }
415         }
416
417         public function removeDupe(node:Node):void {
418             if (getNode(node.id) != node) { return; } // make sure it's on this connection
419             var a:String = node.lat+","+node.lon;
420             var redraw:Boolean=node.isDupe();
421             var dupes:Array = [];
422             for each (var dupe:Node in nodePositions[a]) {
423               if (dupe!=node) { dupes.push(dupe); }
424             }
425             nodePositions[a] = dupes;
426             for each (var n:Node in nodePositions[a]) { // redraw any nodes remaining
427               n.dispatchEvent(new Event(Connection.NODE_ALTERED));
428             }
429             if (redraw) { node.dispatchEvent(new Event(Connection.NODE_ALTERED)); } //redraw the one being moved
430         }
431
432         public function nodesAtPosition(lat:Number, lon:Number):uint {
433             if (nodePositions[lat+","+lon]) {
434               return nodePositions[lat+","+lon].length;
435             }
436             return 0;
437         }
438
439         public function getNodesAtPosition(lat:Number, lon:Number):Array {
440             if (nodePositions[lat+","+lon]) {
441               return nodePositions[lat+","+lon];
442             }
443             return [];
444         }
445
446                 // Error-handling
447                 
448                 protected function throwConflictError(entity:Entity,serverVersion:uint,message:String):void {
449                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
450                                 message: "An item you edited has been changed by another mapper. Download their version and try again? (The server said: "+message+")",
451                                 yes: function():void { revertBeforeUpload(entity) },
452                                 no: cancelUpload }));
453                         // ** FIXME: this should also offer the choice of 'overwrite?'
454                 }
455                 protected function throwAlreadyDeletedError(entity:Entity,message:String):void {
456                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
457                                 message: "You tried to delete something that's already been deleted. Forget it and try again? (The server said: "+message+")",
458                                 yes: function():void { deleteBeforeUpload(entity) },
459                                 no: cancelUpload }));
460                 }
461                 protected function throwInUseError(entity:Entity,message:String):void {
462                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
463                                 message: "You tried to delete something that's since been used elsewhere. Restore it and try again? (The server said: "+message+")",
464                                 yes: function():void { revertBeforeUpload(entity) },
465                                 no: cancelUpload }));
466                 }
467                 protected function throwEntityError(entity:Entity,message:String):void {
468                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
469                                 message: "There is a problem with your changes which needs to be fixed before you can save: "+message+". Click 'OK' to see the offending item.",
470                                 ok: function():void { goToEntity(entity) } }));
471                 }
472                 protected function throwChangesetError(message:String):void {
473                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
474                                 message: "The changeset in which you're saving changes is no longer valid. Start a new one and retry? (The server said: "+message+")",
475                                 yes: retryUploadWithNewChangeset,
476                                 no: cancelUpload }));
477                 }
478                 protected function throwBugError(message:String):void {
479                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
480                                 message: "An unexpected error occurred, probably due to a bug in Potlatch 2. Do you want to retry? (The server said: "+message+")",
481                                 yes: retryUpload,
482                                 no: cancelUpload }));
483                 }
484                 protected function throwServerError(message:String):void {
485                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
486                                 message: "A server error occurred. Do you want to retry? (The server said: "+message+")",
487                                 yes: retryUpload,
488                                 no: cancelUpload }));
489                 }
490
491                 public function retryUpload(e:Event=null):void { 
492                         removeEventListener(LOAD_COMPLETED,retryUpload);
493                         uploadChanges(); 
494                 }
495                 public function cancelUpload():void {
496                         return;
497                 }
498                 public function retryUploadWithNewChangeset():void { 
499                         // ** FIXME: we need to move the create-changeset-then-upload logic out of SaveDialog
500                 }
501                 public function goToEntity(entity:Entity):void { 
502                         dispatchEvent(new AttentionEvent(AttentionEvent.ATTENTION, entity));
503                 }
504                 public function revertBeforeUpload(entity:Entity):void { 
505                         addEventListener(LOAD_COMPLETED,retryUpload);
506                         loadEntity(entity);
507                 }
508                 public function deleteBeforeUpload(entity:Entity):void {
509             var a:CompositeUndoableAction = new CompositeUndoableAction("Delete refs");            
510             entity.remove(a.push);
511             a.doAction();
512                         killEntity(entity);
513                         uploadChanges();
514                 }
515
516         // these are functions that the Connection implementation is expected to
517         // provide. This class has some generic helpers for the implementation.
518                 public function loadBbox(left:Number, right:Number,
519                                                                 top:Number, bottom:Number):void {
520             }
521             public function loadEntity(entity:Entity):void {}
522             public function setAuthToken(id:Object):void {}
523         public function setAccessToken(key:String, secret:String):void {}
524             public function createChangeset(tags:Object):void {}
525                 public function closeChangeset():void {}
526             public function uploadChanges():void {}
527         public function fetchUserTraces(refresh:Boolean=false):void {}
528         public function fetchTrace(id:Number, callback:Function):void {}
529         public function hasAccessToken():Boolean { return false; }
530     }
531
532 }
533