ec8de9f2df7f2c0b3e1560f7c54378489b5cae93
[potlatch2.git] / net / systemeD / halcyon / connection / Connection.as
1 package net.systemeD.halcyon.connection {
2
3     import flash.net.*;
4
5     import flash.events.EventDispatcher;
6     import flash.events.Event;
7         import net.systemeD.halcyon.Globals;
8         import net.systemeD.halcyon.connection.actions.*;
9         import net.systemeD.halcyon.MapEvent;
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         public function getMatchingRelationIDs(match:Object):Array {
312             var list:Array = [];
313                         var ok:Boolean;
314             for each (var relation:Relation in relations) {
315                                 ok=true;
316                                 if (relation.deleted) { ok=false; }
317                                 for (var k:String in match) {
318                                         if (!relation.getTagsHash()[k] || relation.getTagsHash()[k]!=match[k]) { ok=false; }
319                                 }
320                                 if (ok) { list.push(relation.id); }
321                         }
322             return list;
323         }
324
325                 public function getObjectsByBbox(left:Number, right:Number, top:Number, bottom:Number):Object {
326                         var o:Object = { poisInside: [], poisOutside: [], waysInside: [], waysOutside: [] };
327                         for each (var way:Way in ways) {
328                                 if (way.within(left,right,top,bottom)) { o.waysInside.push(way); }
329                                                                   else { o.waysOutside.push(way); }
330                         }
331                         for each (var poi:Node in pois) {
332                                 if (poi.within(left,right,top,bottom)) { o.poisInside.push(poi); }
333                                                                   else { o.poisOutside.push(poi); }
334                         }
335                         return o;
336                 }
337
338                 public function purgeOutside(left:Number, right:Number, top:Number, bottom:Number):void {
339                         for each (var way:Way in ways) {
340                                 if (!way.within(left,right,top,bottom) && !way.isDirty && !way.locked && !way.hasLockedNodes()) {
341                                         killWayWithNodes(way.id);
342                                 }
343                         }
344                         for each (var poi:Node in pois) {
345                                 if (!poi.within(left,right,top,bottom) && !poi.isDirty && !poi.locked) {
346                                         killNode(poi.id);
347                                 }
348                         }
349                         // ** should purge relations too, if none of their members are on-screen
350                 }
351
352                 public function markDirty():void {
353             if (!modified) { dispatchEvent(new Event(DATA_DIRTY)); }
354                         modified=true;
355                 }
356                 public function markClean():void {
357             if (modified) { dispatchEvent(new Event(DATA_CLEAN)); }
358                         modified=false;
359                 }
360                 public function get isDirty():Boolean {
361                         return modified;
362                 }
363
364                 // Changeset tracking
365
366         protected function setActiveChangeset(changeset:Changeset):void {
367             this.changeset = changeset;
368                         changesetUpdated = new Date().getTime();
369             sendEvent(new EntityEvent(NEW_CHANGESET, changeset),false);
370         }
371
372                 protected function freshenActiveChangeset():void {
373                         changesetUpdated = new Date().getTime();
374                 }
375                 
376                 protected function closeActiveChangeset():void {
377                         changeset = null;
378                 }
379         
380         public function getActiveChangeset():Changeset {
381                         if (changeset && (new Date().getTime()) > (changesetUpdated+58*60*1000)) {
382                                 closeActiveChangeset();
383                         }
384             return changeset;
385         }
386
387         protected function addTrace(t:Object):void {
388             traces.push(t);
389         }
390
391         protected function clearTraces():void {
392             traces = [];
393         }
394
395         public function getTraces():Array {
396             return traces;
397         }
398
399         public function addDupe(node:Node):void {
400             if (getNode(node.id) != node) { return; } // make sure it's on this connection
401             var a:String = node.lat+","+node.lon;
402             if(!nodePositions[a]) {
403               nodePositions[a] = [];
404             }
405             nodePositions[a].push(node);
406             if (nodePositions[a].length > 1) { // don't redraw if it's the only node in town
407               for each (var n:Node in nodePositions[a]) {
408                 n.dispatchEvent(new Event(Connection.NODE_ALTERED));
409               }
410             }
411         }
412
413         public function removeDupe(node:Node):void {
414             if (getNode(node.id) != node) { return; } // make sure it's on this connection
415             var a:String = node.lat+","+node.lon;
416             var redraw:Boolean=node.isDupe();
417             var dupes:Array = [];
418             for each (var dupe:Node in nodePositions[a]) {
419               if (dupe!=node) { dupes.push(dupe); }
420             }
421             nodePositions[a] = dupes;
422             for each (var n:Node in nodePositions[a]) { // redraw any nodes remaining
423               n.dispatchEvent(new Event(Connection.NODE_ALTERED));
424             }
425             if (redraw) { node.dispatchEvent(new Event(Connection.NODE_ALTERED)); } //redraw the one being moved
426         }
427
428         public function nodesAtPosition(lat:Number, lon:Number):uint {
429             if (nodePositions[lat+","+lon]) {
430               return nodePositions[lat+","+lon].length;
431             }
432             return 0;
433         }
434
435         public function getNodesAtPosition(lat:Number, lon:Number):Array {
436             if (nodePositions[lat+","+lon]) {
437               return nodePositions[lat+","+lon];
438             }
439             return [];
440         }
441
442                 // Error-handling
443                 
444                 protected function throwConflictError(entity:Entity,serverVersion:uint,message:String):void {
445                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
446                                 message: "An item you edited has been changed by another mapper. Download their version and try again? (The server said: "+message+")",
447                                 yes: function():void { revertBeforeUpload(entity) },
448                                 no: cancelUpload }));
449                         // ** FIXME: this should also offer the choice of 'overwrite?'
450                 }
451                 protected function throwAlreadyDeletedError(entity:Entity,message:String):void {
452                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
453                                 message: "You tried to delete something that's already been deleted. Forget it and try again? (The server said: "+message+")",
454                                 yes: function():void { deleteBeforeUpload(entity) },
455                                 no: cancelUpload }));
456                 }
457                 protected function throwInUseError(entity:Entity,message:String):void {
458                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
459                                 message: "You tried to delete something that's since been used elsewhere. Restore it and try again? (The server said: "+message+")",
460                                 yes: function():void { revertBeforeUpload(entity) },
461                                 no: cancelUpload }));
462                 }
463                 protected function throwEntityError(entity:Entity,message:String):void {
464                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
465                                 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.",
466                                 ok: function():void { goToEntity(entity) } }));
467                 }
468                 protected function throwChangesetError(message:String):void {
469                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
470                                 message: "The changeset in which you're saving changes is no longer valid. Start a new one and retry? (The server said: "+message+")",
471                                 yes: retryUploadWithNewChangeset,
472                                 no: cancelUpload }));
473                 }
474                 protected function throwBugError(message:String):void {
475                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
476                                 message: "An unexpected error occurred, probably due to a bug in Potlatch 2. Do you want to retry? (The server said: "+message+")",
477                                 yes: retryUpload,
478                                 no: cancelUpload }));
479                 }
480                 protected function throwServerError(message:String):void {
481                         dispatchEvent(new MapEvent(MapEvent.ERROR, {
482                                 message: "A server error occurred. Do you want to retry? (The server said: "+message+")",
483                                 yes: retryUpload,
484                                 no: cancelUpload }));
485                 }
486
487                 public function retryUpload():void { uploadChanges(); }
488                 public function cancelUpload():void { return; }
489                 public function retryUploadWithNewChangeset():void { 
490                         // ** FIXME: we need to move the create-changeset-then-upload logic out of SaveDialog
491                 }
492                 public function goToEntity(entity:Entity):void { 
493                         dispatchEvent(new MapEvent(MapEvent.ATTENTION, { entity: entity }));
494                 }
495                 public function revertBeforeUpload(entity:Entity):void { 
496                         // ** FIXME: implement a 'revert entity' method, then retry upload on successful download
497                 }
498                 public function deleteBeforeUpload(entity:Entity):void {
499             var a:CompositeUndoableAction = new CompositeUndoableAction("Delete refs");            
500             entity.remove(a.push);
501             a.doAction();
502                         killEntity(entity);
503                         uploadChanges();
504                 }
505
506         // these are functions that the Connection implementation is expected to
507         // provide. This class has some generic helpers for the implementation.
508                 public function loadBbox(left:Number, right:Number,
509                                                                 top:Number, bottom:Number):void {
510             }
511             
512             public function setAuthToken(id:Object):void {}
513         public function setAccessToken(key:String, secret:String):void {}
514             public function createChangeset(tags:Object):void {}
515                 public function closeChangeset():void {}
516             public function uploadChanges():void {}
517         public function fetchUserTraces(refresh:Boolean=false):void {}
518         public function fetchTrace(id:Number, callback:Function):void {}
519         public function hasAccessToken():Boolean { return false; }
520     }
521
522 }
523