Make wayuis, nodeuis and markeruis private
[potlatch2.git] / net / systemeD / halcyon / MapPaint.as
1 package net.systemeD.halcyon {
2
3         import flash.display.Sprite;
4         import flash.display.DisplayObject;
5         import net.systemeD.halcyon.NodeUI;
6         import net.systemeD.halcyon.WayUI;
7         import net.systemeD.halcyon.connection.*;
8         import net.systemeD.halcyon.connection.actions.CreatePOIAction;
9         import net.systemeD.halcyon.styleparser.RuleSet;
10
11         /** Manages the drawing of map entities, allocating their sprites etc. */
12         public class MapPaint extends Sprite {
13                 
14                 /** Parent Map - required for finding out bounds and scale */
15                 public var map:Map;
16
17                 /** Source data for this MapPaint layer */
18                 public var connection:Connection;
19
20                 /** Lowest OSM layer that can be displayed */
21                 public var minlayer:int;
22                 /** Highest OSM layer that can be displayed */
23                 public var maxlayer:int;
24                 /** The MapCSS rules used for drawing entities. */
25                 public var ruleset:RuleSet;                                             
26                 /** WayUI objects attached to Way entities that are currently visible. */
27                 private var wayuis:Object=new Object();
28                 /** NodeUI objects attached to POI/tagged node entities that are currently visible. */
29                 private var nodeuis:Object=new Object();
30                 /** MarkerUI objects attached to Marker entities that are currently visible. */
31         private var markeruis:Object=new Object();
32         /** Is this a background layer or the core paint object? */
33                 public var isBackground:Boolean = true;
34                 /** Hash of index->position */
35                 public var sublayerIndex:Object={};
36
37         /** The url of the style in use */
38         public var style:String = '';
39
40                 private const VERYBIG:Number=Math.pow(2,16);
41                 private static const NO_LAYER:int=-99999;               // same as NodeUI
42
43                 // Set up layering
44
45                 /** Creates paint sprites and hit sprites for all layers in range. This object ends up with a series of child sprites
46                  * as follows: p0,p1,p2..px, h0,h1,h2..hx where p are "paint sprites" and "h" are "hit sprites". There is one of each type for each layer.
47                  * <p>Each paint sprite has 4 child sprites (fill, casing, stroke, names). Each hit sprite has 2 child sprites (way hit tests, node hit tests).</p>  
48                  * <p>Thus if layers range from -5 to +5, there will be 11 top level paint sprites followed by 11 top level hit sprites.</p>
49                  * 
50                  * @param map The Map this is attached to. (Required for finding out bounds and scale.)
51                  * @param connection The Connection containing the data for this layer.
52                  * @param minlayer The lowest OSM layer to display.
53                  * @param maxlayer The highest OSM layer to display.
54                  * */ 
55                 public function MapPaint(map:Map, connection:Connection, styleurl:String, minlayer:int, maxlayer:int) {
56                         mouseEnabled=false;
57
58                         this.map=map;
59                         this.connection=connection;
60                         this.minlayer=minlayer;
61                         this.maxlayer=maxlayer;
62                         sublayerIndex[1]=0;
63                         var s:Sprite, l:int;
64
65                         // Set up stylesheet
66                         setStyle(styleurl);
67
68                         // Listen for changes on this Connection
69             connection.addEventListener(Connection.NEW_WAY, newWayCreatedListener);
70             connection.addEventListener(Connection.NEW_POI, newPOICreatedListener);
71             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumberedListener);
72             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumberedListener);
73             connection.addEventListener(Connection.NEW_MARKER, newMarkerCreatedListener);
74
75                         // Add paint sprites
76                         for (l=minlayer; l<=maxlayer; l++) {                    // each layer (10 is +5, 0 is -5)
77                                 s = getPaintSprite();                                           //      |
78                                 s.addChild(getPaintSprite());                           //      | 0 fill
79                                 s.addChild(getPaintSprite());                           //      | 1 casing
80                                 var t:Sprite = getPaintSprite();                        //      | 2 stroke
81                                 t.addChild(getPaintSprite());                           //      |  | sublayer
82                                 s.addChild(t);                                                          //      |  |
83                                 s.addChild(getPaintSprite());                           //      | 3 names
84                                 addChild(s);                                                            //      |
85                         }
86                         
87                         // Add hit sprites
88                         for (l=minlayer; l<=maxlayer; l++) {                    // each layer (21 is +5, 11 is -5)
89                                 s = getHitSprite();                                                     //      |
90                                 s.addChild(getHitSprite());                                     //      | 0 way hit tests
91                                 s.addChild(getHitSprite());                                     //      | 1 node hit tests
92                                 addChild(s);
93                         }
94                 }
95                 
96                 /** Returns the paint surface for the given layer. */
97                 public function getPaintSpriteAt(l:int):Sprite {
98                         return getChildAt(l-minlayer) as Sprite;
99                 }
100
101                 /** Returns the hit sprite for the given layer. */
102                 public function getHitSpriteAt(l:int):Sprite {
103                         return getChildAt((l-minlayer) + (maxlayer-minlayer+1)) as Sprite;
104                 }
105                 
106                 /** Is ruleset loaded? */
107                 public function get ready():Boolean {
108                         if (!ruleset) { return false; }
109                         if (!ruleset.loaded) { return false; }
110                         return true;
111                 }
112
113                 public function sublayer(layer:int,sublayer:Number):Sprite {
114                         var l:DisplayObject;
115                         var o:DisplayObject;
116                         var index:String, ix:Number;
117                         if (!sublayerIndex.hasOwnProperty(sublayer)) {
118                                 // work out which position to add at
119                                 var lowestAbove:Number=VERYBIG;
120                                 var lowestAbovePos:int=-1;
121                                 var indexLength:uint=0;
122                                 for (index in sublayerIndex) {
123                                         ix=Number(index);
124                                         if (ix>sublayer && ix<lowestAbove) {
125                                                 lowestAbove=ix;
126                                                 lowestAbovePos=sublayerIndex[index];
127                                         }
128                                         indexLength++;
129                                 }
130                                 if (lowestAbovePos==-1) { lowestAbovePos=indexLength; }
131                         
132                                 // add sprites
133                                 for (var i:int=minlayer; i<=maxlayer; i++) {
134                                         l=getChildAt(i-minlayer);
135                                         o=(l as Sprite).getChildAt(2);
136                                         (o as Sprite).addChildAt(getPaintSprite(),lowestAbovePos);
137                                 }
138                         
139                                 // update index
140                                 // (we do it in this rather indirect way because if you alter sublayerIndex directly
141                                 //      within the loop, it confuses the iterator)
142                                 var toUpdate:Array=[];
143                                 for (index in sublayerIndex) {
144                                         ix=Number(index);
145                                         if (ix>sublayer) { toUpdate.push(index); }
146                                 }
147                                 for each (index in toUpdate) { sublayerIndex[index]++; }
148                                 sublayerIndex[sublayer]=lowestAbovePos;
149                         }
150
151                         l=getChildAt(layer-minlayer);
152                         o=(l as Sprite).getChildAt(2);
153                         return ((o as Sprite).getChildAt(sublayerIndex[sublayer]) as Sprite);
154                 }
155
156         /**
157         * Update, and if necessary, create / remove UIs for the current viewport.
158         * Flags control redrawing existing entities and removing UIs from entities no longer in view.
159         *
160         * @param redraw If true, all UIs for entities on "inside" lists will be redrawn
161         * @param remove If true, all UIs for entites on "outside" lists will be removed. The purgable flag on UIs
162                         can override this, for example for selected objects.
163         * fixme? add smarter behaviour for way nodes - remove NodeUIs from way nodes off screen, create them for ones
164         * that scroll onto screen (for highlights etc)
165         */
166                 public function updateEntityUIs(redraw:Boolean, remove:Boolean):void {
167                         var way:Way, poi:Node, marker:Marker;
168                         var o:Object = connection.getObjectsByBbox(map.edge_l,map.edge_r,map.edge_t,map.edge_b);
169
170                         for each (way in o.waysInside) {
171                                 if (!wayuis[way.id]) { createWayUI(way); }
172                                 else if (redraw) { wayuis[way.id].recalculate(); wayuis[way.id].redraw(); }
173                                 else wayuis[way.id].updateHighlights();//dubious
174                         }
175
176                         if (remove) {
177                                 for each (way in o.waysOutside) {
178                                         if (wayuis[way.id] && !wayuis[way.id].purgable) {
179                                                 if (redraw) { wayuis[way.id].recalculate(); wayuis[way.id].redraw(); }
180                                         } else {
181                                                 deleteWayUI(way);
182                                         }
183                                 }
184                         }
185
186                         for each (poi in o.poisInside) {
187                                 if (!nodeuis[poi.id]) { createNodeUI(poi); }
188                                 else if (redraw) { nodeuis[poi.id].redraw(); }
189                         }
190
191                         if (remove) {
192                                 for each (poi in o.poisOutside) { 
193                                         if (nodeuis[poi.id] && !nodeuis[poi.id].purgable) {
194                                                 if (redraw) { nodeuis[poi.id].redraw(); }
195                                         } else {
196                                                 deleteNodeUI(poi);
197                                         }
198                                 }
199                         }
200
201             for each (marker in o.markersInside) {
202                 if (!markeruis[marker.id]) { createMarkerUI(marker); }
203                 else if (redraw) { markeruis[marker.id].redraw(); }
204             }
205
206             if (remove) {
207                 for each (marker in o.markersOutside) {
208                     if (markeruis[marker.id] && !markeruis[marker.id].purgable) {
209                         if (redraw) { markeruis[marker.id].redraw(); }
210                     } else {
211                         deleteMarkerUI(marker);
212                     }
213                 }
214             }
215                 }
216
217                 /** Make a UI object representing a way. */
218                 public function createWayUI(way:Way):WayUI {
219                         if (!wayuis[way.id]) {
220                                 wayuis[way.id]=new WayUI(way,this);
221                                 way.addEventListener(Connection.WAY_DELETED, wayDeleted);
222                         } else {
223                                 wayuis[way.id].redraw();
224                         }
225                         return wayuis[way.id];
226                 }
227
228                 /** Respond to event by removing the WayUI. */
229                 public function wayDeleted(event:EntityEvent):void {
230                         deleteWayUI(event.entity as Way);
231                 }
232
233                 /** Remove a way's UI object. */
234                 public function deleteWayUI(way:Way):void {
235                         way.removeEventListener(Connection.WAY_DELETED, wayDeleted);
236                         if (wayuis[way.id]) {
237                                 wayuis[way.id].redrawMultis();
238                                 wayuis[way.id].removeSprites();
239                                 wayuis[way.id].removeEventListeners();
240                                 wayuis[way.id].removeListenSprite();
241                                 delete wayuis[way.id];
242                         }
243                         for (var i:uint=0; i<way.length; i++) {
244                                 var node:Node=way.getNode(i);
245                                 if (nodeuis[node.id]) { deleteNodeUI(node); }
246                         }
247                 }
248
249                 /** Make a UI object representing a node. */
250                 public function createNodeUI(node:Node,rotation:Number=0,layer:int=NO_LAYER,stateClasses:Object=null):NodeUI {
251                         if (!nodeuis[node.id]) {
252                                 nodeuis[node.id]=new NodeUI(node,this,rotation,layer,stateClasses);
253                                 node.addEventListener(Connection.NODE_DELETED, nodeDeleted);
254                         } else {
255                                 for (var state:String in stateClasses) {
256                                         nodeuis[node.id].setStateClass(state,stateClasses[state]);
257                                 }
258                                 nodeuis[node.id].redraw();
259                         }
260                         return nodeuis[node.id];
261                 }
262
263                 /** Respond to event by deleting NodeUI. */
264                 public function nodeDeleted(event:EntityEvent):void {
265                         deleteNodeUI(event.entity as Node);
266                 }
267
268                 /** Remove a node's UI object. */
269                 public function deleteNodeUI(node:Node):void {
270                         node.removeEventListener(Connection.NODE_DELETED, nodeDeleted);
271                         if (!nodeuis[node.id]) { return; }
272                         nodeuis[node.id].removeSprites();
273                         nodeuis[node.id].removeEventListeners();
274                         nodeuis[node.id].removeListenSprite();
275                         delete nodeuis[node.id];
276                 }
277
278         /** Make a UI object representing a marker. */
279         public function createMarkerUI(marker:Marker,rotation:Number=0,layer:int=NO_LAYER,stateClasses:Object=null):MarkerUI {
280             if (!markeruis[marker.id]) {
281                 markeruis[marker.id]=new MarkerUI(marker,this,rotation,layer,stateClasses);
282                 marker.addEventListener(Connection.NODE_DELETED, markerDeleted);
283             } else {
284                 for (var state:String in stateClasses) {
285                     markeruis[marker.id].setStateClass(state,stateClasses[state]);
286                 }
287                 markeruis[marker.id].redraw();
288             }
289             return markeruis[marker.id];
290         }
291
292         /** Respond to event by deleting MarkerUI. */
293         public function markerDeleted(event:EntityEvent):void {
294             deleteMarkerUI(event.entity as Marker);
295         }
296
297         /** Remove a marker's UI object. */
298         public function deleteMarkerUI(marker:Marker):void {
299             marker.removeEventListener(Connection.NODE_DELETED, markerDeleted);
300             if (!markeruis[marker.id]) { return; }
301             markeruis[marker.id].removeSprites();
302             markeruis[marker.id].removeEventListeners();
303             markeruis[marker.id].removeListenSprite();
304             delete markeruis[marker.id];
305         }
306                 
307                 public function renumberWayUI(way:Way,oldID:Number):void {
308                         if (!wayuis[oldID]) { return; }
309                         wayuis[way.id]=wayuis[oldID];
310                         delete wayuis[oldID];
311                 }
312
313                 public function renumberNodeUI(node:Node,oldID:Number):void {
314                         if (!nodeuis[oldID]) { return; }
315                         nodeuis[node.id]=nodeuis[oldID];
316                         delete nodeuis[oldID];
317                 }
318
319                 /** Make a new sprite for painting on */
320                 private function getPaintSprite():Sprite {
321                         var s:Sprite = new Sprite();
322                         s.mouseEnabled = false;
323                         s.mouseChildren = false;
324                         return s;
325                 }
326
327                 private function getHitSprite():Sprite {
328                         var s:Sprite = new Sprite();
329                         return s;
330                 }
331
332                 /** Redraw all entities */
333                 public function redraw():void {
334                         for each (var w:WayUI in wayuis) { w.recalculate(); w.invalidateStyleList(); w.redraw(); }
335                         /* sometimes (e.g. in Map.setStyle) Mappaint.redrawPOIs() is called immediately afterwards anyway. FIXME? */
336                         for each (var p:NodeUI in nodeuis) { p.invalidateStyleList(); p.redraw(); }
337             for each (var m:MarkerUI in markeruis) { m.invalidateStyleList(); m.redraw(); }
338                 }
339
340                 /** Redraw nodes and markers only */
341                 public function redrawPOIs():void {
342                         for each (var p:NodeUI in nodeuis) { p.invalidateStyleList(); p.redraw(); }
343             for each (var m:MarkerUI in markeruis) { m.invalidateStyleList(); m.redraw(); }
344                 }
345                 
346                 /** Redraw a single entity if it exists */
347                 public function redrawEntity(e:Entity):Boolean {
348                         if      (e is Way    && wayuis[e.id]) wayuis[e.id].redraw();
349                         else if (e is Node   && nodeuis[e.id]) nodeuis[e.id].redraw();
350                         else if (e is Marker && markeruis[e.id]) markeruis[e.id].redraw();
351                         else return false;
352                         return true;
353                 }
354                 
355                 /** Switch to new MapCSS. */
356                 public function setStyle(url:String):void {
357             style = url;
358                         ruleset=new RuleSet(map.MINSCALE,map.MAXSCALE,redraw,redrawPOIs);
359                         ruleset.loadFromCSS(url);
360         }
361
362                 // ==================== Start of code moved from Map.as
363
364                 // Listeners for Connection events
365
366         private function newWayCreatedListener(event:EntityEvent):void {
367             var way:Way = event.entity as Way;
368                         if (!way.loaded || !way.within(map.edge_l, map.edge_r, map.edge_t, map.edge_b)) { return; }
369                         createWayUI(way);
370         }
371
372         private function newPOICreatedListener(event:EntityEvent):void {
373             var node:Node = event.entity as Node;
374                         if (!node.within(map.edge_l, map.edge_r, map.edge_t, map.edge_b)) { return; }
375                         createNodeUI(node);
376         }
377
378         private function newMarkerCreatedListener(event:EntityEvent):void {
379             var marker:Marker = event.entity as Marker;
380             if (!marker.within(map.edge_l, map.edge_r, map.edge_t, map.edge_b)) { return; }
381             createMarkerUI(marker);
382         }
383
384                 private function wayRenumberedListener(event:EntityRenumberedEvent):void {
385             var way:Way = event.entity as Way;
386                         renumberWayUI(way,event.oldID);
387                 }
388
389                 private function nodeRenumberedListener(event:EntityRenumberedEvent):void {
390             var node:Node = event.entity as Node;
391                         renumberNodeUI(node,event.oldID);
392                 }
393
394         /** Visually mark an entity as highlighted. */
395         public function setHighlight(entity:Entity, settings:Object):void {
396                         if      ( entity is Way  && wayuis[entity.id] ) { wayuis[entity.id].setHighlight(settings);  }
397                         else if ( entity is Node && nodeuis[entity.id]) { nodeuis[entity.id].setHighlight(settings); }
398         }
399
400         public function setHighlightOnNodes(way:Way, settings:Object):void {
401                         if (wayuis[way.id]) wayuis[way.id].setHighlightOnNodes(settings);
402         }
403
404                 public function protectWay(way:Way):void {
405                         if (wayuis[way.id]) wayuis[way.id].protectSprites();
406                 }
407
408                 public function unprotectWay(way:Way):void {
409                         if (wayuis[way.id]) wayuis[way.id].unprotectSprites();
410                 }
411                 
412                 public function limitWayDrawing(way:Way,except:Number=NaN,only:Number=NaN):void {
413                         if (!wayuis[way.id]) return;
414                         wayuis[way.id].drawExcept=except;
415                         wayuis[way.id].drawOnly  =only;
416                         wayuis[way.id].redraw();
417                 }
418
419                 /** Protect Entities and EntityUIs against purging. This prevents the currently selected items
420                    from being purged even though they're off-screen. */
421
422                 public function setPurgable(entities:Array, purgable:Boolean):void {
423                         for each (var entity:Entity in entities) {
424                                 entity.locked=!purgable;
425                                 if ( entity is Way  ) {
426                                         var way:Way=entity as Way;
427                                         if (wayuis[way.id]) { wayuis[way.id].purgable=purgable; }
428                                         for (var i:uint=0; i<way.length; i++) {
429                                                 var node:Node=way.getNode(i)
430                                                 node.locked=!purgable;
431                                                 if (nodeuis[node.id]) { nodeuis[node.id].purgable=purgable; }
432                                         }
433                                 } else if ( entity is Node && nodeuis[entity.id]) { 
434                                         nodeuis[entity.id].purgable=purgable;
435                                 }
436                         }
437                 }
438
439                 // ==================== End of code moved from Map.as
440
441                 /** Find all ways whose WayUI passes a given screen co-ordinate. */
442                 
443                 public function findWaysAtPoint(x:Number, y:Number, ignore:Way=null):Array {
444                         var ways:Array=[]; var w:Way;
445                         for each (var wayui:WayUI in wayuis) {
446                                 w=wayui.hitTest(x,y);
447                                 if (w && w!=ignore) { ways.push(w); }
448                         }
449                         return ways;
450                 }
451
452         /**
453         * Transfers an entity from this layer into another layer
454         * @param entity The entity from this layer that you want to transfer.
455         * @param target The layer to transfer to
456         *
457         * @return either the newly created entity, or null
458         */
459         public function pullThrough(entity:Entity, target:MapPaint):Entity {
460             // TODO - check the entity actually resides in this layer.
461
462             var action:CompositeUndoableAction = new CompositeUndoableAction("pull through");
463             if (entity is Way) {
464                 // copy way through to main layer
465                 // ** shouldn't do this if the nodes are already in the main layer
466                 //    (or maybe we should just match on lat/long to avoid ways in background having nodes in foreground)
467                 var oldWay:Way=Way(entity);
468                 var newWay:Way=target.connection.createWay(oldWay.getTagsCopy(), [], action.push);
469                 var nodemap:Object={};
470                 for (var i:uint=0; i<oldWay.length; i++) {
471                     oldNode = oldWay.getNode(i);
472                     var newNode:Node = nodemap[oldNode.id] ? nodemap[oldNode.id] : target.connection.createNode(
473                         oldNode.getTagsCopy(), oldNode.lat, oldNode.lon,
474                         action.push);
475                     newWay.appendNode(newNode, action.push);
476                     nodemap[oldNode.id]=newNode;
477                 }
478                 // delete this way
479                 oldWay.remove(action.push)
480                 MainUndoStack.getGlobalStack().addAction(action);
481                 return newWay;
482
483             } else if (entity is Node && !entity.hasParentWays) {
484
485                 var oldNode:Node=Node(entity);
486
487                 var newPoiAction:CreatePOIAction = new CreatePOIAction(
488                     target.connection, oldNode.getTagsCopy(), oldNode.lat, oldNode.lon);
489                 action.push(newPoiAction);
490
491                 oldNode.remove(action.push);
492
493                 MainUndoStack.getGlobalStack().addAction(action);
494                 return newPoiAction.getNode();
495             }
496             return null;
497         }
498
499         }
500 }