Allow users to load traces that aren't theirs
[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     import net.systemeD.halcyon.Globals;
11
12         public class Connection extends EventDispatcher {
13
14                 public var name:String;
15                 public var statusFetcher:StatusFetcher;
16         protected var apiBaseURL:String;
17         protected var policyURL:String;
18         protected var params:Object;
19
20                 public function Connection(cname:String,api:String,policy:String,initparams:Object=null) {
21                         initparams = (initparams!=null ? initparams:{});
22                         name=cname;
23                         apiBaseURL=api;
24                         policyURL=policy;
25                         params=initparams;
26                 }
27
28         public function getParam(name:String, defaultValue:String):String {
29                         if (params[name]) return params[name];
30                         if (Globals.vars.flashvars[name]) return Globals.vars.flashvars[name];  // REFACTOR - given the profusion of connections, should this be removed?
31                         return defaultValue;
32         }
33
34         public function get apiBase():String {
35             return apiBaseURL;
36         }
37
38         public function get serverName():String {
39             return getParam("serverName", "Localhost");
40         }
41
42                 public function getEnvironment(responder:Responder):void {}
43
44         // connection events
45         public static var LOAD_STARTED:String = "load_started";
46         public static var LOAD_COMPLETED:String = "load_completed";
47         public static var SAVE_STARTED:String = "save_started";
48         public static var SAVE_COMPLETED:String = "save_completed";
49         public static var DATA_DIRTY:String = "data_dirty";
50         public static var DATA_CLEAN:String = "data_clean";
51         public static var NEW_CHANGESET:String = "new_changeset";
52         public static var NEW_CHANGESET_ERROR:String = "new_changeset_error";
53         public static var NEW_NODE:String = "new_node";
54         public static var NEW_WAY:String = "new_way";
55         public static var NEW_RELATION:String = "new_relation";
56         public static var NEW_POI:String = "new_poi";
57         public static var NEW_MARKER:String = "new_marker";
58         public static var NODE_RENUMBERED:String = "node_renumbered";
59         public static var WAY_RENUMBERED:String = "way_renumbered";
60         public static var RELATION_RENUMBERED:String = "relation_renumbered";
61         public static var TAG_CHANGED:String = "tag_changed";
62         public static var STATUS_CHANGED:String = "status_changed";
63         public static var NODE_MOVED:String = "node_moved";
64         public static var NODE_ALTERED:String = "node_altered";
65         public static var WAY_NODE_ADDED:String = "way_node_added";
66         public static var WAY_NODE_REMOVED:String = "way_node_removed";
67         public static var WAY_REORDERED:String = "way_reordered";
68         public static var ENTITY_DRAGGED:String = "entity_dragged";
69                 public static var NODE_DELETED:String = "node_deleted";
70                 public static var WAY_DELETED:String = "way_deleted";
71                 public static var RELATION_DELETED:String = "relation_deleted";
72                 public static var RELATION_MEMBER_ADDED:String = "relation_member_added";
73                 public static var RELATION_MEMBER_REMOVED:String = "relation_member_deleted";
74                 public static var ADDED_TO_RELATION:String = "added_to_relation";
75                 public static var REMOVED_FROM_RELATION:String = "removed_from_relation";
76                 public static var SUSPEND_REDRAW:String = "suspend_redraw";
77                 public static var RESUME_REDRAW:String = "resume_redraw";
78         public static var TRACES_LOADED:String = "traces_loaded";
79
80         // store the data we download
81         private var negativeID:Number = -1;
82         private var nodes:Object = {};
83         private var ways:Object = {};
84         private var relations:Object = {};
85         private var markers:Object = {};
86         private var pois:Array = [];
87         private var changeset:Changeset = null;
88                 private var changesetUpdated:Number;
89                 private var modified:Boolean = false;
90                 public var nodecount:int=0;
91                 public var waycount:int=0;
92                 public var relationcount:int=0;
93         private var traces:Array = [];
94         private var nodePositions:Object = {};
95         protected var traces_loaded:Boolean = false;
96                 private var loadedBboxes:Array = [];
97
98                 /** maximum number of ways to keep in memory before purging */
99                 protected const MAXWAYS:uint=3000;
100
101         protected function get nextNegative():Number {
102             return negativeID--;
103         }
104
105         protected function setNode(node:Node, queue:Boolean):void {
106                         if (!nodes[node.id]) { nodecount++; }
107             nodes[node.id] = node;
108             addDupe(node);
109             if (node.loaded) { sendEvent(new EntityEvent(NEW_NODE, node),queue); }
110         }
111
112         protected function setWay(way:Way, queue:Boolean):void {
113                         if (!ways[way.id] && way.loaded) { waycount++; }
114             ways[way.id] = way;
115             if (way.loaded) { sendEvent(new EntityEvent(NEW_WAY, way),queue); }
116         }
117
118         protected function setRelation(relation:Relation, queue:Boolean):void {
119                         if (!relations[relation.id]) { relationcount++; }
120             relations[relation.id] = relation;
121             if (relation.loaded) { sendEvent(new EntityEvent(NEW_RELATION, relation),queue); }
122         }
123
124                 protected function setOrUpdateNode(newNode:Node, queue:Boolean):void {
125                 if (nodes[newNode.id]) {
126                                 var wasDeleted:Boolean=nodes[newNode.id].isDeleted();
127                                 nodes[newNode.id].update(newNode.version, newNode.getTagsHash(), true, newNode.parentsLoaded, newNode.lat, newNode.lon, newNode.uid, newNode.timestamp);
128                                 if (wasDeleted) sendEvent(new EntityEvent(NEW_NODE, nodes[newNode.id]), false);
129                         } else {
130                                 setNode(newNode, queue);
131                         }
132                 }
133
134                 protected function renumberNode(oldID:Number, newID:Number, version:uint):void {
135                         var node:Node=nodes[oldID];
136                         if (oldID!=newID) { removeDupe(node); }
137                         node.renumber(newID, version);
138                         if (oldID==newID) return;                                       // if only a version change, return
139                         nodes[newID]=node;
140                         addDupe(node);
141                         if (node.loaded) { sendEvent(new EntityRenumberedEvent(NODE_RENUMBERED, node, oldID),false); }
142                         delete nodes[oldID];
143                 }
144
145                 protected function renumberWay(oldID:Number, newID:Number, version:uint):void {
146                         var way:Way=ways[oldID];
147                         way.renumber(newID, version);
148                         if (oldID==newID) return;
149                         ways[newID]=way;
150                         if (way.loaded) { sendEvent(new EntityRenumberedEvent(WAY_RENUMBERED, way, oldID),false); }
151                         delete ways[oldID];
152                 }
153
154                 protected function renumberRelation(oldID:Number, newID:Number, version:uint):void {
155                         var relation:Relation=relations[oldID];
156                         relation.renumber(newID, version);
157                         if (oldID==newID) return;
158                         relations[newID] = relation;
159                         if (relation.loaded) { sendEvent(new EntityRenumberedEvent(RELATION_RENUMBERED, relation, oldID),false); }
160                         delete relations[oldID];
161                 }
162
163
164                 public function sendEvent(e:*,queue:Boolean):void {
165                         // queue is only used for AMFConnection
166                         dispatchEvent(e);
167                 }
168
169         public function registerPOI(node:Node):void {
170             if ( pois.indexOf(node) < 0 ) {
171                 pois.push(node);
172                 sendEvent(new EntityEvent(NEW_POI, node),false);
173             }
174         }
175
176         public function unregisterPOI(node:Node):void {
177             var index:uint = pois.indexOf(node);
178             if ( index >= 0 ) {
179                 pois.splice(index,1);
180             }
181         }
182
183         public function getNode(id:Number):Node {
184             return nodes[id];
185         }
186
187         public function getWay(id:Number):Way {
188             return ways[id];
189         }
190
191         public function getRelation(id:Number):Relation {
192             return relations[id];
193         }
194
195         public function getMarker(id:Number):Marker {
196             return markers[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(this, nextNegative, 0, tags, true, lat, lon);
271             performCreate(new CreateEntityAction(node, setNode));
272             return node;
273         }
274
275         public function createWay(tags:Object, nodes:Array, performCreate:Function):Way {
276             var way:Way = new Way(this, nextNegative, 0, tags, true, nodes.concat());
277             performCreate(new CreateEntityAction(way, setWay));
278             return way;
279         }
280
281         public function createRelation(tags:Object, members:Array, performCreate:Function):Relation {
282             var relation:Relation = new Relation(this, nextNegative, 0, tags, true, members.concat());
283             performCreate(new CreateEntityAction(relation, setRelation));
284             return relation;
285         }
286
287         /** Create a new marker. This can't be done as part of a Composite Action. */
288         // REFACTOR  This needs renaming and/or refactoring to behave more similarly to n/w/r
289         public function createMarker(tags:Object,lat:Number,lon:Number,id:Number=NaN):Marker {
290             if (!id) {
291               id = negativeID;
292               negativeID--;
293             }
294             var marker:Marker = markers[id];
295             if (marker == null) {
296               marker = new Marker(this, id, 0, tags, true, lat, lon);
297               markers[id]=marker;
298               sendEvent(new EntityEvent(NEW_MARKER, marker),false);
299             }
300             return marker;
301         }
302
303         public function getAllNodeIDs():Array {
304             var list:Array = [];
305             for each (var node:Node in nodes)
306                 list.push(node.id);
307             return list;
308         }
309
310         public function getAllWayIDs():Array {
311             var list:Array = [];
312             for each (var way:Way in ways)
313                 list.push(way.id);
314             return list;
315         }
316
317         public function getAllRelationIDs():Array {
318             var list:Array = [];
319             for each (var relation:Relation in relations)
320                 list.push(relation.id);
321             return list;
322         }
323
324                 public function getAllLoadedEntities():Array {
325                         var list:Array = []; var entity:Entity;
326                         for each (entity in relations) { if (entity.loaded && !entity.deleted) list.push(entity); }
327                         for each (entity in ways     ) { if (entity.loaded && !entity.deleted) list.push(entity); }
328                         for each (entity in nodes    ) { if (entity.loaded && !entity.deleted) list.push(entity); }
329                         return list;
330                 }
331
332         /** Returns all available relations that match all of {k1: [v1,v2,...], k2: [v1...] ...} 
333         * where p1 is an array [v1, v2, v3...] */
334         public function getMatchingRelationIDs(match:Object):Array {
335             var list:Array = [];
336             for each (var relation:Relation in relations) {
337                 var ok: Boolean = true;
338                                 if (relation.deleted) { continue; }
339                                 for (var k:String in match) {
340                                         var v:String = relation.getTagsHash()[k];
341                                         if (!v || match[k].indexOf(v) < 0) { 
342                                            ok = false; break;  
343                                         }
344                                 }
345                                 if (ok) { list.push(relation.id); }
346                         }
347             return list;
348         }
349
350                 public function getObjectsByBbox(left:Number, right:Number, top:Number, bottom:Number):Object {
351                         var o:Object = { poisInside: [], poisOutside: [], waysInside: [], waysOutside: [],
352                               markersInside: [], markersOutside: [] };
353                         for each (var way:Way in ways) {
354                                 if (way.within(left,right,top,bottom)) { o.waysInside.push(way); }
355                                                                   else { o.waysOutside.push(way); }
356                         }
357                         for each (var poi:Node in pois) {
358                                 if (poi.within(left,right,top,bottom)) { o.poisInside.push(poi); }
359                                                                   else { o.poisOutside.push(poi); }
360                         }
361             for each (var marker:Marker in markers) {
362                 if (marker.within(left,right,top,bottom)) { o.markersInside.push(marker); }
363                                                      else { o.markersOutside.push(marker); }
364             }
365                         return o;
366                 }
367
368                 public function purgeOutside(left:Number, right:Number, top:Number, bottom:Number):void {
369                         for each (var way:Way in ways) {
370                                 if (!way.within(left,right,top,bottom) && !way.isDirty && !way.locked && !way.hasLockedNodes()) {
371                                         killWayWithNodes(way.id);
372                                 }
373                         }
374                         for each (var poi:Node in pois) {
375                                 if (!poi.within(left,right,top,bottom) && !poi.isDirty && !poi.locked) {
376                                         killNode(poi.id);
377                                 }
378                         }
379                         // ** should purge relations too, if none of their members are on-screen
380                 }
381
382                 public function markDirty():void {
383             if (!modified) { dispatchEvent(new Event(DATA_DIRTY)); }
384                         modified=true;
385                 }
386                 public function markClean():void {
387             if (modified) { dispatchEvent(new Event(DATA_CLEAN)); }
388                         modified=false;
389                 }
390                 public function get isDirty():Boolean {
391                         return modified;
392                 }
393
394                 // Keep track of the bboxes we've loaded
395
396                 /** Has the data within this bbox already been loaded? */
397                 protected function isBboxLoaded(left:Number,right:Number,top:Number,bottom:Number):Boolean {
398                         var l:Number,r:Number,t:Number,b:Number;
399                         for each (var box:Array in loadedBboxes) {
400                                 l=box[0]; r=box[1]; t=box[2]; b=box[3];
401                                 if (left>=l && left<=r && right>=l && right<=r && top>=b && top<=t && bottom>=b && bottom<=t) {
402                                         return true;
403                                 }
404                         }
405                         return false;
406                 }
407                 /** Mark that bbox is loaded */
408                 protected function markBboxLoaded(left:Number,right:Number,top:Number,bottom:Number):void {
409                         if (isBboxLoaded(left,right,top,bottom)) return;
410                         loadedBboxes.push([left,right,top,bottom]);
411                 }
412                 /** Purge all data if number of ways exceeds limit */
413                 public function purgeIfFull(left:Number,right:Number,top:Number,bottom:Number):void {
414                         if (waycount<=MAXWAYS) return;
415                         purgeOutside(left,right,top,bottom);
416                         loadedBboxes=[[left,right,top,bottom]];
417                 }
418
419                 // Changeset tracking
420
421         protected function setActiveChangeset(changeset:Changeset):void {
422             this.changeset = changeset;
423                         changesetUpdated = new Date().getTime();
424             sendEvent(new EntityEvent(NEW_CHANGESET, changeset),false);
425         }
426
427                 protected function freshenActiveChangeset():void {
428                         changesetUpdated = new Date().getTime();
429                 }
430                 
431                 protected function closeActiveChangeset():void {
432                         changeset = null;
433                 }
434         
435         public function getActiveChangeset():Changeset {
436                         if (changeset && (new Date().getTime()) > (changesetUpdated+58*60*1000)) {
437                                 closeActiveChangeset();
438                         }
439             return changeset;
440         }
441
442         public function addTrace(t:Object):void {
443             traces.push(t);
444         }
445
446         protected function clearTraces():void {
447             traces = [];
448         }
449
450                 public function findTrace(id:int):Trace {
451                         for each (var t:Trace in traces) {
452                                 if (t.id == id) return t;
453                         }
454                         return null;
455                 }
456
457         public function getTraces():Array {
458             return traces;
459         }
460
461         public function addDupe(node:Node):void {
462             if (getNode(node.id) != node) { return; } // make sure it's on this connection
463             var a:String = node.lat+","+node.lon;
464             if(!nodePositions[a]) {
465               nodePositions[a] = [];
466             }
467             nodePositions[a].push(node);
468             if (nodePositions[a].length > 1) { // don't redraw if it's the only node in town
469               for each (var n:Node in nodePositions[a]) {
470                 n.dispatchEvent(new Event(Connection.NODE_ALTERED));
471               }
472             }
473         }
474
475         public function removeDupe(node:Node):void {
476             if (getNode(node.id) != node) { return; } // make sure it's on this connection
477             var a:String = node.lat+","+node.lon;
478             var redraw:Boolean=node.isDupe();
479             var dupes:Array = [];
480             for each (var dupe:Node in nodePositions[a]) {
481               if (dupe!=node) { dupes.push(dupe); }
482             }
483             nodePositions[a] = dupes;
484             for each (var n:Node in nodePositions[a]) { // redraw any nodes remaining
485               n.dispatchEvent(new Event(Connection.NODE_ALTERED));
486             }
487             if (redraw) { node.dispatchEvent(new Event(Connection.NODE_ALTERED)); } //redraw the one being moved
488         }
489
490         public function nodesAtPosition(lat:Number, lon:Number):uint {
491             if (nodePositions[lat+","+lon]) {
492               return nodePositions[lat+","+lon].length;
493             }
494             return 0;
495         }
496
497         public function getNodesAtPosition(lat:Number, lon:Number):Array {
498             if (nodePositions[lat+","+lon]) {
499               return nodePositions[lat+","+lon];
500             }
501             return [];
502         }
503
504                 public function identicalNode(node:Node):Node {
505                         for each (var dupe:Node in nodePositions[node.lat+","+node.lon]) {
506                                 if (node.lat==dupe.lat && node.lon==dupe.lon && node.sameTags(dupe)) return dupe;
507                         }
508                         return null;
509                 }
510
511                 // Error-handling
512                 
513                 protected function throwConflictError(entity:Entity,serverVersion:uint,message:String):void {
514                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
515                                 message: "An item you edited has been changed by another mapper. Download their version and try again? (The server said: "+message+")",
516                                 yes: function():void { revertBeforeUpload(entity) },
517                                 no: cancelUpload }));
518                         // ** FIXME: this should also offer the choice of 'overwrite?'
519                 }
520                 protected function throwAlreadyDeletedError(entity:Entity,message:String):void {
521                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
522                                 message: "You tried to delete something that's already been deleted. Forget it and try again? (The server said: "+message+")",
523                                 yes: function():void { deleteBeforeUpload(entity) },
524                                 no: cancelUpload }));
525                 }
526                 protected function throwInUseError(entity:Entity,message:String):void {
527                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
528                                 message: "You tried to delete something that's since been used elsewhere. Restore it and try again? (The server said: "+message+")",
529                                 yes: function():void { revertBeforeUpload(entity) },
530                                 no: cancelUpload }));
531                 }
532                 protected function throwEntityError(entity:Entity,message:String):void {
533                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
534                                 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.",
535                                 ok: function():void { goToEntity(entity) } }));
536                 }
537                 protected function throwChangesetError(message:String):void {
538                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
539                                 message: "The changeset in which you're saving changes is no longer valid. Start a new one and retry? (The server said: "+message+")",
540                                 yes: retryUploadWithNewChangeset,
541                                 no: cancelUpload }));
542                 }
543                 protected function throwBugError(message:String):void {
544                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
545                                 message: "An unexpected error occurred, probably due to a bug in Potlatch 2. Do you want to retry? (The server said: "+message+")",
546                                 yes: retryUpload,
547                                 no: cancelUpload }));
548                 }
549                 protected function throwServerError(message:String):void {
550                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
551                                 message: "A server error occurred. Do you want to retry? (The server said: "+message+")",
552                                 yes: retryUpload,
553                                 no: cancelUpload }));
554                 }
555
556                 public function retryUpload(e:Event=null):void { 
557                         removeEventListener(LOAD_COMPLETED,retryUpload);
558                         uploadChanges(); 
559                 }
560                 public function cancelUpload():void {
561                         return;
562                 }
563                 public function retryUploadWithNewChangeset():void { 
564                         // ** FIXME: we need to move the create-changeset-then-upload logic out of SaveDialog
565                 }
566                 public function goToEntity(entity:Entity):void { 
567                         dispatchEvent(new AttentionEvent(AttentionEvent.ATTENTION, entity));
568                 }
569                 public function revertBeforeUpload(entity:Entity):void { 
570                         addEventListener(LOAD_COMPLETED,retryUpload);
571                         loadEntity(entity);
572                 }
573                 public function deleteBeforeUpload(entity:Entity):void {
574             var a:CompositeUndoableAction = new CompositeUndoableAction("Delete refs");            
575             entity.remove(a.push);
576             a.doAction();
577                         killEntity(entity);
578                         uploadChanges();
579                 }
580
581         // these are functions that the Connection implementation is expected to
582         // provide. This class has some generic helpers for the implementation.
583                 public function loadBbox(left:Number, right:Number,
584                                                                 top:Number, bottom:Number):void {
585             }
586             public function loadEntityByID(type:String, id:Number):void {}
587             public function setAuthToken(id:Object):void {}
588         public function setAccessToken(key:String, secret:String):void {}
589             public function createChangeset(tags:Object):void {}
590                 public function closeChangeset():void {}
591         public function uploadChanges():* {}
592         public function fetchUserTraces(refresh:Boolean=false):void {}
593         public function fetchTrace(id:Number, callback:Function):void {}
594         public function hasAccessToken():Boolean { return false; }
595
596                 public function loadEntity(entity:Entity):void {
597                         loadEntityByID(entity.getType(),entity.id);
598                 }
599
600     }
601
602 }
603