Provide a new 'View data' button in the upload dialogue.
[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               trace("new marker");
297               marker = new Marker(this, id, 0, tags, true, lat, lon);
298               markers[id]=marker;
299               sendEvent(new EntityEvent(NEW_MARKER, marker),false);
300             }
301             return marker;
302         }
303
304         public function getAllNodeIDs():Array {
305             var list:Array = [];
306             for each (var node:Node in nodes)
307                 list.push(node.id);
308             return list;
309         }
310
311         public function getAllWayIDs():Array {
312             var list:Array = [];
313             for each (var way:Way in ways)
314                 list.push(way.id);
315             return list;
316         }
317
318         public function getAllRelationIDs():Array {
319             var list:Array = [];
320             for each (var relation:Relation in relations)
321                 list.push(relation.id);
322             return list;
323         }
324
325                 public function getAllLoadedEntities():Array {
326                         var list:Array = []; var entity:Entity;
327                         for each (entity in relations) { if (entity.loaded && !entity.deleted) list.push(entity); }
328                         for each (entity in ways     ) { if (entity.loaded && !entity.deleted) list.push(entity); }
329                         for each (entity in nodes    ) { if (entity.loaded && !entity.deleted) list.push(entity); }
330                         return list;
331                 }
332
333         /** Returns all available relations that match all of {k1: [v1,v2,...], k2: [v1...] ...} 
334         * where p1 is an array [v1, v2, v3...] */
335         public function getMatchingRelationIDs(match:Object):Array {
336             var list:Array = [];
337             for each (var relation:Relation in relations) {
338                 var ok: Boolean = true;
339                                 if (relation.deleted) { continue; }
340                                 for (var k:String in match) {
341                                         var v:String = relation.getTagsHash()[k];
342                                         if (!v || match[k].indexOf(v) < 0) { 
343                                            ok = false; break;  
344                                         }
345                                 }
346                                 if (ok) { list.push(relation.id); }
347                         }
348             return list;
349         }
350
351                 public function getObjectsByBbox(left:Number, right:Number, top:Number, bottom:Number):Object {
352                         var o:Object = { poisInside: [], poisOutside: [], waysInside: [], waysOutside: [],
353                               markersInside: [], markersOutside: [] };
354                         for each (var way:Way in ways) {
355                                 if (way.within(left,right,top,bottom)) { o.waysInside.push(way); }
356                                                                   else { o.waysOutside.push(way); }
357                         }
358                         for each (var poi:Node in pois) {
359                                 if (poi.within(left,right,top,bottom)) { o.poisInside.push(poi); }
360                                                                   else { o.poisOutside.push(poi); }
361                         }
362             for each (var marker:Marker in markers) {
363                 if (marker.within(left,right,top,bottom)) { o.markersInside.push(marker); }
364                                                      else { o.markersOutside.push(marker); }
365             }
366                         return o;
367                 }
368
369                 public function purgeOutside(left:Number, right:Number, top:Number, bottom:Number):void {
370                         for each (var way:Way in ways) {
371                                 if (!way.within(left,right,top,bottom) && !way.isDirty && !way.locked && !way.hasLockedNodes()) {
372                                         killWayWithNodes(way.id);
373                                 }
374                         }
375                         for each (var poi:Node in pois) {
376                                 if (!poi.within(left,right,top,bottom) && !poi.isDirty && !poi.locked) {
377                                         killNode(poi.id);
378                                 }
379                         }
380                         // ** should purge relations too, if none of their members are on-screen
381                 }
382
383                 public function markDirty():void {
384             if (!modified) { dispatchEvent(new Event(DATA_DIRTY)); }
385                         modified=true;
386                 }
387                 public function markClean():void {
388             if (modified) { dispatchEvent(new Event(DATA_CLEAN)); }
389                         modified=false;
390                 }
391                 public function get isDirty():Boolean {
392                         return modified;
393                 }
394
395                 // Keep track of the bboxes we've loaded
396
397                 /** Has the data within this bbox already been loaded? */
398                 protected function isBboxLoaded(left:Number,right:Number,top:Number,bottom:Number):Boolean {
399                         var l:Number,r:Number,t:Number,b:Number;
400                         for each (var box:Array in loadedBboxes) {
401                                 l=box[0]; r=box[1]; t=box[2]; b=box[3];
402                                 if (left>=l && left<=r && right>=l && right<=r && top>=b && top<=t && bottom>=b && bottom<=t) {
403                                         return true;
404                                 }
405                         }
406                         return false;
407                 }
408                 /** Mark that bbox is loaded */
409                 protected function markBboxLoaded(left:Number,right:Number,top:Number,bottom:Number):void {
410                         if (isBboxLoaded(left,right,top,bottom)) return;
411                         loadedBboxes.push([left,right,top,bottom]);
412                 }
413                 /** Purge all data if number of ways exceeds limit */
414                 public function purgeIfFull(left:Number,right:Number,top:Number,bottom:Number):void {
415                         if (waycount<=MAXWAYS) return;
416                         purgeOutside(left,right,top,bottom);
417                         loadedBboxes=[[left,right,top,bottom]];
418                 }
419
420                 // Changeset tracking
421
422         protected function setActiveChangeset(changeset:Changeset):void {
423             this.changeset = changeset;
424                         changesetUpdated = new Date().getTime();
425             sendEvent(new EntityEvent(NEW_CHANGESET, changeset),false);
426         }
427
428                 protected function freshenActiveChangeset():void {
429                         changesetUpdated = new Date().getTime();
430                 }
431                 
432                 protected function closeActiveChangeset():void {
433                         changeset = null;
434                 }
435         
436         public function getActiveChangeset():Changeset {
437                         if (changeset && (new Date().getTime()) > (changesetUpdated+58*60*1000)) {
438                                 closeActiveChangeset();
439                         }
440             return changeset;
441         }
442
443         protected function addTrace(t:Object):void {
444             traces.push(t);
445         }
446
447         protected function clearTraces():void {
448             traces = [];
449         }
450
451         public function getTraces():Array {
452             return traces;
453         }
454
455         public function addDupe(node:Node):void {
456             if (getNode(node.id) != node) { return; } // make sure it's on this connection
457             var a:String = node.lat+","+node.lon;
458             if(!nodePositions[a]) {
459               nodePositions[a] = [];
460             }
461             nodePositions[a].push(node);
462             if (nodePositions[a].length > 1) { // don't redraw if it's the only node in town
463               for each (var n:Node in nodePositions[a]) {
464                 n.dispatchEvent(new Event(Connection.NODE_ALTERED));
465               }
466             }
467         }
468
469         public function removeDupe(node:Node):void {
470             if (getNode(node.id) != node) { return; } // make sure it's on this connection
471             var a:String = node.lat+","+node.lon;
472             var redraw:Boolean=node.isDupe();
473             var dupes:Array = [];
474             for each (var dupe:Node in nodePositions[a]) {
475               if (dupe!=node) { dupes.push(dupe); }
476             }
477             nodePositions[a] = dupes;
478             for each (var n:Node in nodePositions[a]) { // redraw any nodes remaining
479               n.dispatchEvent(new Event(Connection.NODE_ALTERED));
480             }
481             if (redraw) { node.dispatchEvent(new Event(Connection.NODE_ALTERED)); } //redraw the one being moved
482         }
483
484         public function nodesAtPosition(lat:Number, lon:Number):uint {
485             if (nodePositions[lat+","+lon]) {
486               return nodePositions[lat+","+lon].length;
487             }
488             return 0;
489         }
490
491         public function getNodesAtPosition(lat:Number, lon:Number):Array {
492             if (nodePositions[lat+","+lon]) {
493               return nodePositions[lat+","+lon];
494             }
495             return [];
496         }
497
498                 public function identicalNode(node:Node):Node {
499                         for each (var dupe:Node in nodePositions[node.lat+","+node.lon]) {
500                                 if (node.lat==dupe.lat && node.lon==dupe.lon && node.sameTags(dupe)) return dupe;
501                         }
502                         return null;
503                 }
504
505                 // Error-handling
506                 
507                 protected function throwConflictError(entity:Entity,serverVersion:uint,message:String):void {
508                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
509                                 message: "An item you edited has been changed by another mapper. Download their version and try again? (The server said: "+message+")",
510                                 yes: function():void { revertBeforeUpload(entity) },
511                                 no: cancelUpload }));
512                         // ** FIXME: this should also offer the choice of 'overwrite?'
513                 }
514                 protected function throwAlreadyDeletedError(entity:Entity,message:String):void {
515                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
516                                 message: "You tried to delete something that's already been deleted. Forget it and try again? (The server said: "+message+")",
517                                 yes: function():void { deleteBeforeUpload(entity) },
518                                 no: cancelUpload }));
519                 }
520                 protected function throwInUseError(entity:Entity,message:String):void {
521                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
522                                 message: "You tried to delete something that's since been used elsewhere. Restore it and try again? (The server said: "+message+")",
523                                 yes: function():void { revertBeforeUpload(entity) },
524                                 no: cancelUpload }));
525                 }
526                 protected function throwEntityError(entity:Entity,message:String):void {
527                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
528                                 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.",
529                                 ok: function():void { goToEntity(entity) } }));
530                 }
531                 protected function throwChangesetError(message:String):void {
532                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
533                                 message: "The changeset in which you're saving changes is no longer valid. Start a new one and retry? (The server said: "+message+")",
534                                 yes: retryUploadWithNewChangeset,
535                                 no: cancelUpload }));
536                 }
537                 protected function throwBugError(message:String):void {
538                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
539                                 message: "An unexpected error occurred, probably due to a bug in Potlatch 2. Do you want to retry? (The server said: "+message+")",
540                                 yes: retryUpload,
541                                 no: cancelUpload }));
542                 }
543                 protected function throwServerError(message:String):void {
544                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
545                                 message: "A server error occurred. Do you want to retry? (The server said: "+message+")",
546                                 yes: retryUpload,
547                                 no: cancelUpload }));
548                 }
549
550                 public function retryUpload(e:Event=null):void { 
551                         removeEventListener(LOAD_COMPLETED,retryUpload);
552                         uploadChanges(); 
553                 }
554                 public function cancelUpload():void {
555                         return;
556                 }
557                 public function retryUploadWithNewChangeset():void { 
558                         // ** FIXME: we need to move the create-changeset-then-upload logic out of SaveDialog
559                 }
560                 public function goToEntity(entity:Entity):void { 
561                         dispatchEvent(new AttentionEvent(AttentionEvent.ATTENTION, entity));
562                 }
563                 public function revertBeforeUpload(entity:Entity):void { 
564                         addEventListener(LOAD_COMPLETED,retryUpload);
565                         loadEntity(entity);
566                 }
567                 public function deleteBeforeUpload(entity:Entity):void {
568             var a:CompositeUndoableAction = new CompositeUndoableAction("Delete refs");            
569             entity.remove(a.push);
570             a.doAction();
571                         killEntity(entity);
572                         uploadChanges();
573                 }
574
575         // these are functions that the Connection implementation is expected to
576         // provide. This class has some generic helpers for the implementation.
577                 public function loadBbox(left:Number, right:Number,
578                                                                 top:Number, bottom:Number):void {
579             }
580             public function loadEntityByID(type:String, id:Number):void {}
581             public function setAuthToken(id:Object):void {}
582         public function setAccessToken(key:String, secret:String):void {}
583             public function createChangeset(tags:Object):void {}
584                 public function closeChangeset():void {}
585         public function uploadChanges():* {}
586         public function fetchUserTraces(refresh:Boolean=false):void {}
587         public function fetchTrace(id:Number, callback:Function):void {}
588         public function hasAccessToken():Boolean { return false; }
589
590                 public function loadEntity(entity:Entity):void {
591                         loadEntityByID(entity.getType(),entity.id);
592                 }
593
594     }
595
596 }
597