various click-handling improvements/fixes
[potlatch2.git] / net / systemeD / halcyon / WayUI.as
1 package net.systemeD.halcyon {
2
3         import flash.display.*;
4         import flash.geom.Matrix;
5         import flash.geom.Point;
6         import flash.geom.Rectangle;
7         import flash.text.AntiAliasType;
8         import flash.text.GridFitType;
9         import flash.text.TextField;
10         import flash.text.TextFormat;
11         import flash.events.*;
12         import net.systemeD.halcyon.styleparser.*;
13     import net.systemeD.halcyon.connection.*;
14
15         public class WayUI {
16         private var way:Way;
17
18                 public var pathlength:Number;                           // length of path
19                 public var patharea:Number;                                     // area of path
20                 public var centroid_x:Number;                           // centroid
21                 public var centroid_y:Number;                           //  |
22                 public var layer:int=0;                                         // map layer
23                 public var map:Map;                                                     // reference to parent map
24                 public var sprites:Array=new Array();           // instances in display list
25                 public var heading:Array=new Array();           // angle at each node
26                 private var stateClasses:Object = new Object();
27         private var hitzone:Sprite;
28         private var listenSprite:Sprite;
29
30                 public static const DEFAULT_TEXTFIELD_PARAMS:Object = {
31                         embedFonts: true,
32                         antiAliasType: AntiAliasType.ADVANCED,
33                         gridFitType: GridFitType.NONE
34                 };
35                 public var nameformat:TextFormat;
36                 
37                 private const FILLSPRITE:uint=0;
38                 private const CASINGSPRITE:uint=1;
39                 private const STROKESPRITE:uint=2;
40                 private const NAMESPRITE:uint=3;
41                 private const NODESPRITE:uint=4;
42                 private const CLICKSPRITE:uint=5;
43
44                 private const NODESIZE:uint=6;
45
46                 public function WayUI(way:Way, map:Map) {
47                         this.way = way;
48                         this.map = map;
49             init();
50             way.addEventListener(Connection.TAG_CHANGE, wayTagChanged);
51             way.addEventListener(Connection.WAY_NODE_ADDED, wayNodeAdded);
52             way.addEventListener(Connection.WAY_NODE_REMOVED, wayNodeRemoved);
53             attachNodeListeners();
54                 }
55                 
56                 private function attachNodeListeners():void {
57             for (var i:uint = 0; i < way.length; i++ ) {
58                 way.getNode(i).addEventListener(Connection.NODE_MOVED, nodeMoved);
59             }
60                 }
61                 
62                 private function wayNodeAdded(event:WayNodeEvent):void {
63                     event.node.addEventListener(Connection.NODE_MOVED, nodeMoved);
64                     redraw();
65                 }
66                     
67                 private function wayNodeRemoved(event:WayNodeEvent):void {
68                     event.node.removeEventListener(Connection.NODE_MOVED, nodeMoved);
69                     redraw();
70                 }
71                     
72         private function wayTagChanged(event:TagEvent):void {
73             redraw();
74         }
75         private function nodeMoved(event:NodeMovedEvent):void {
76             redraw();
77         }
78
79                 private function init():void {
80                         recalculate();
81                         redraw();
82                         // updateBbox(lon, lat);
83                         // ** various other stuff
84                 }
85
86                 // ------------------------------------------------------------------------------------------
87                 // Calculate length etc.
88                 // ** this could be made scale-independent - would speed up redraw
89                 
90                 public function recalculate():void {
91                         var lx:Number, ly:Number, sc:Number;
92                         var node:Node, latp:Number, lon:Number;
93                         var cx:Number=0, cy:Number=0;
94                         pathlength=0;
95                         patharea=0;
96                         
97                         lx = way.getNode(way.length-1).lon;
98                         ly = way.getNode(way.length-1).latp;
99                         for ( var i:uint = 0; i < way.length; i++ ) {
100                 node = way.getNode(i);
101                 latp = node.latp;
102                 lon  = node.lon;
103
104                                 // length and area
105                                 if ( i>0 ) { pathlength += Math.sqrt( Math.pow(lon-lx,2)+Math.pow(latp-ly,2) ); }
106                                 sc = (lx*latp-lon*ly)*map.scalefactor;
107                                 cx += (lx+lon)*sc;
108                                 cy += (ly+latp)*sc;
109                                 patharea += sc;
110                                 
111                                 // heading
112                                 if (i>0) { heading[i-1]=Math.atan2((lon-lx),(latp-ly)); }
113
114                                 lx=lon; ly=latp;
115                         }
116                         heading[way.length-1]=heading[way.length-2];
117
118                         pathlength*=map.scalefactor;
119                         patharea/=2;
120                         if (patharea!=0 && way.isArea()) {
121                                 centroid_x=map.lon2coord(cx/patharea/6);
122                                 centroid_y=map.latp2coord(cy/patharea/6);
123                         } else if (pathlength>0) {
124                                 var c:Array=pointAt(0.5);
125                                 centroid_x=c[0];
126                                 centroid_y=c[1];
127                         }
128                 }
129
130                 // ------------------------------------------------------------------------------------------
131                 // Redraw
132
133                 public function redraw():void {
134             // Copy tags object, and add states
135             var tags:Object = way.getTagsCopy();
136             for (var stateKey:String in stateClasses) {
137                 tags[":"+stateKey] = stateKey;
138             }
139                         if (way.isArea()) { tags[':area']='yes'; }
140
141                         // Remove all currently existing sprites
142                         while (sprites.length>0) {
143                                 var d:DisplayObject=sprites.pop(); d.parent.removeChild(d);
144                         }
145
146                         // Which layer?
147                         layer=5;
148                         if ( tags['layer'] )
149                 layer=Math.min(Math.max(tags['layer']+5,-5),5)+5;
150
151                         // Iterate through each sublayer, drawing any styles on that layer
152                         var sl:StyleList=map.ruleset.getStyles(this.way, tags);
153                         var drawn:Boolean;
154                         for (var sublayer:uint=0; sublayer<11; sublayer++) {
155                                 if (sl.shapeStyles[sublayer]) {
156                                         var s:ShapeStyle=sl.shapeStyles[sublayer];
157                                         var stroke:Shape, fill:Shape, casing:Shape, roadname:Sprite;
158                                         var x0:Number=map.lon2coord(way.getNode(0).lon);
159                                         var y0:Number=map.latp2coord(way.getNode(0).latp);
160
161                                         // Stroke
162                                         if (s.width)  {
163                                                 stroke=new Shape(); addToLayer(stroke,STROKESPRITE,sublayer);
164                                                 stroke.graphics.moveTo(x0,y0);
165                                                 s.applyStrokeStyle(stroke.graphics);
166                                                 if (s.dashes && s.dashes.length>0) { dashedLine(stroke.graphics,s.dashes); }
167                                                                                                           else { solidLine(stroke.graphics); }
168                                                 drawn=true;
169                                         }
170
171                                         // Fill
172                                         if (s.fill_color || s.fill_image) {
173                                                 fill=new Shape(); addToLayer(fill,FILLSPRITE);
174                                                 fill.graphics.moveTo(x0,y0);
175                                                 if (s.fill_image) { new WayBitmapFiller(this,fill.graphics,s); }
176                                                                          else { s.applyFill(fill.graphics); }
177                                                 solidLine(fill.graphics);
178                                                 fill.graphics.endFill();
179                                                 drawn=true;
180                                         }
181
182                                         // Casing
183                                         if (s.casing_width) { 
184                                                 casing=new Shape(); addToLayer(casing,CASINGSPRITE);
185                                                 casing.graphics.moveTo(x0,y0);
186                                                 s.applyCasingStyle(casing.graphics);
187                                                 if (s.casing_dashes && s.casing_dashes.length>0) { dashedLine(casing.graphics,s.casing_dashes); }
188                                                                                                                                         else { solidLine(casing.graphics); }
189                                                 drawn=true;
190                                         }
191                                 }
192                                 
193                                 if (sl.textStyles[sublayer]) {
194                                         var t:TextStyle=sl.textStyles[sublayer];
195                                         roadname=new Sprite(); addToLayer(roadname,NAMESPRITE);
196                                         nameformat = t.getTextFormat();
197                                         var a:String=tags[t.text];
198                                         if (a) {
199                                                 if (t.font_caps) { a=a.toUpperCase(); }
200                                                 if (t.text_center && centroid_x) {
201                                                         t.writeNameLabel(roadname,a,centroid_x,centroid_y);
202                                                 } else {
203                                                         writeNameOnPath(roadname,a,t.text_offset ? t.text_offset : 0);
204                                                 }
205                                                 if (t.text_halo_radius>0) { roadname.filters=t.getHaloFilter(); }
206                                         }
207                                 }
208                                 
209                                 // ** ShieldStyle to do
210                         }
211
212                         // ** draw icons
213                         // ** this looks like it needs reworking
214                         var r:Number;
215                         var highlight:Boolean=stateClasses["showNodes"] !=null;
216                         for (var i:uint = 0; i < way.length; i++) {
217                 var node:Node = way.getNode(i);
218                     if (map.pois[node.id]) {
219                                         if (map.pois[node.id].loaded) {
220                                                 map.pois[node.id].redraw(null, highlight);
221                                         }
222                                 } else if (node.hasTags()) {
223                                         sl=map.ruleset.getStyles(node,node.getTagsHash());
224                                         if (sl.hasStyles()) {
225                                                 if (i==0) { r= heading[i]; }
226                                                      else { r=(heading[i]+heading[i-1])/2; }
227                                                 map.pois[node.id]=new NodeUI(node,map,r);
228                                                 map.pois[node.id].redraw(sl);
229                                                 // ** this should be done via the registerPOI/event listener mechanism,
230                                                 //    but that needs a bit of reworking so we can pass in a styleList
231                                                 //    (otherwise we end up computing the styles twice which is expensive)
232                                         }
233                                 } else if (highlight) {
234                                         map.pois[node.id]=new NodeUI(node,map);
235                                         map.pois[node.id].redraw(null, true);
236                                 }
237                         }
238                         
239 //                      // No styles, so add a thin trace
240 //                      if (!drawn && map.showall) {
241 //                              var def:Sprite = new Sprite();
242 //                              def.graphics.lineStyle(0.5, 0x808080, 1, false, "normal");
243 //                              solidLine(def.graphics);
244 //                              addToLayer(def, STROKESPRITE, 10);
245 //                              drawn=true;
246 //                      }
247             
248 //            if ( stateClasses["showNodes"] != null ) {
249 //                var nodes:Sprite = new Sprite();
250 //                drawNodes(nodes.graphics);
251 //                addToLayer(nodes, NODESPRITE);
252 //            }
253
254                         if (!drawn) { return; }
255                         
256             // create a generic "way" hitzone sprite
257             hitzone = new Sprite();
258             hitzone.graphics.lineStyle(4, 0x000000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
259             solidLine(hitzone.graphics);
260             addToLayer(hitzone, CLICKSPRITE);
261             hitzone.visible = false;
262
263             if ( listenSprite == null ) {
264                 listenSprite = new Sprite();
265                 listenSprite.addEventListener(MouseEvent.CLICK, mouseEvent);
266                 listenSprite.addEventListener(MouseEvent.DOUBLE_CLICK, mouseEvent);
267                 listenSprite.addEventListener(MouseEvent.MOUSE_OVER, mouseEvent);
268                 listenSprite.addEventListener(MouseEvent.MOUSE_OUT, mouseEvent);
269                 listenSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseEvent);
270                 listenSprite.addEventListener(MouseEvent.MOUSE_UP, mouseEvent);
271                 listenSprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseEvent);
272             }
273             listenSprite.hitArea = hitzone;
274             addToLayer(listenSprite, CLICKSPRITE);
275             listenSprite.buttonMode = true;
276             listenSprite.mouseEnabled = true;
277
278                 }
279                 
280                 // ------------------------------------------------------------------------------------------
281                 // Drawing support functions
282
283                 private function drawNodes(g:Graphics):void {
284 // ***** these should be discreet anchorpoints (NodeUI?), not just sprites
285 //          g.lineStyle(1, 0xff0000, 1, false, "normal", CapsStyle.ROUND, JointStyle.ROUND);
286                         g.beginFill(0xFF0000);
287                         for (var i:uint = 0; i < way.length; i++) {
288                 var node:Node = way.getNode(i);
289                 var x:Number = map.lon2coord(node.lon);
290                 var y:Number = map.latp2coord(node.latp);
291                 g.moveTo(x-NODESIZE, y-NODESIZE);
292                 g.lineTo(x+NODESIZE, y-NODESIZE);
293                 g.lineTo(x+NODESIZE, y+NODESIZE);
294                 g.lineTo(x-NODESIZE, y+NODESIZE);
295                 g.lineTo(x-NODESIZE, y-NODESIZE);
296                         }
297                 }
298
299                 // Draw solid polyline
300                 
301                 public function solidLine(g:Graphics):void {
302             var node:Node = way.getNode(0);
303                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
304                         for (var i:uint = 1; i < way.length; i++) {
305                 node = way.getNode(i);
306                                 g.lineTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
307                         }
308                 }
309
310                 // Draw dashed polyline
311                 
312                 private function dashedLine(g:Graphics,dashes:Array):void {
313                         var draw:Boolean=false, dashleft:Number=0, dc:Array=new Array();
314                         var a:Number, xc:Number, yc:Number;
315                         var curx:Number, cury:Number;
316                         var dx:Number, dy:Number, segleft:Number=0;
317                         var i:int=0;
318
319             var node:Node = way.getNode(0);
320             var nextNode:Node = way.getNode(0);
321                         g.moveTo(map.lon2coord(node.lon), map.latp2coord(node.latp));
322                         while (i < way.length-1 || segleft>0) {
323                                 if (dashleft<=0) {      // should be ==0
324                                         if (dc.length==0) { dc=dashes.slice(0); }
325                                         dashleft=dc.shift();
326                                         draw=!draw;
327                                 }
328                                 if (segleft<=0) {       // should be ==0
329                     node = way.getNode(i);
330                     nextNode = way.getNode(i+1);
331                                         curx=map.lon2coord(node.lon);
332                     dx=map.lon2coord(nextNode.lon)-curx;
333                                         cury=map.latp2coord(node.latp);
334                     dy=map.latp2coord(nextNode.latp)-cury;
335                                         a=Math.atan2(dy,dx); xc=Math.cos(a); yc=Math.sin(a);
336                                         segleft=Math.sqrt(dx*dx+dy*dy);
337                                         i++;
338                                 }
339
340                                 if (segleft<=dashleft) {
341                                         // the path segment is shorter than the dash
342                                         curx+=dx; cury+=dy;
343                                         moveLine(g,curx,cury,draw);
344                                         dashleft-=segleft; segleft=0;
345                                 } else {
346                                         // the path segment is longer than the dash
347                                         curx+=dashleft*xc; dx-=dashleft*xc;
348                                         cury+=dashleft*yc; dy-=dashleft*yc;
349                                         moveLine(g,curx,cury,draw);
350                                         segleft-=dashleft; dashleft=0;
351                                 }
352                         }
353                 }
354
355                 private function moveLine(g:Graphics,x:Number,y:Number,draw:Boolean):void {
356                         if (draw) { g.lineTo(x,y); }
357                                  else { g.moveTo(x,y); }
358                 }
359
360                 
361                 // Find point partway (0-1) along a path
362                 // returns (x,y,angle)
363                 // inspired by senocular's Path.as
364                 
365                 private function pointAt(t:Number):Array {
366                         var totallen:Number = t*pathlength;
367                         var curlen:Number = 0;
368                         var dx:Number, dy:Number, seglen:Number;
369                         for (var i:int = 1; i < way.length; i++){
370                                 dx=map.lon2coord(way.getNode(i).lon)-map.lon2coord(way.getNode(i-1).lon);
371                                 dy=map.latp2coord(way.getNode(i).latp)-map.latp2coord(way.getNode(i-1).latp);
372                                 seglen=Math.sqrt(dx*dx+dy*dy);
373                                 if (totallen > curlen+seglen) { curlen+=seglen; continue; }
374                                 return new Array(map.lon2coord(way.getNode(i-1).lon)+(totallen-curlen)/seglen*dx,
375                                                                  map.latp2coord(way.getNode(i-1).latp)+(totallen-curlen)/seglen*dy,
376                                                                  Math.atan2(dy,dx));
377                         }
378                         return new Array(0, 0, 0);
379                 }
380
381                 // Draw name along path
382                 // based on code by Tom Carden
383                 
384                 private function writeNameOnPath(s:Sprite,a:String,textOffset:Number=0):void {
385
386                         // make a dummy textfield so we can measure its width
387                         var tf:TextField = new TextField();
388                         tf.defaultTextFormat = nameformat;
389                         tf.text = a;
390                         tf.width = tf.textWidth+4;
391                         tf.height = tf.textHeight+4;
392                         if (pathlength<tf.width) { return; }    // no room for text?
393
394                         var t1:Number = (pathlength/2 - tf.width/2) / pathlength; var p1:Array=pointAt(t1);
395                         var t2:Number = (pathlength/2 + tf.width/2) / pathlength; var p2:Array=pointAt(t2);
396
397                         var angleOffset:Number; // so we can do a 180ยบ if we're running backwards
398                         var offsetSign:Number;  // -1 if we're starting at t2
399                         var tStart:Number;      // t1 or t2
400
401                         // make sure text doesn't run right->left or upside down
402                         if (p1[0] < p2[0] && 
403                                 p1[2] < Math.PI/2 &&
404                                 p1[2] > -Math.PI/2) {
405                                 angleOffset = 0; offsetSign = 1; tStart = t1;
406                         } else {
407                                 angleOffset = Math.PI; offsetSign = -1; tStart = t2;
408                         } 
409
410                         // make a textfield for each char, centered on the line,
411                         // using getCharBoundaries to rotate it around its center point
412                         var chars:Array = a.split('');
413                         for (var i:int = 0; i < chars.length; i++) {
414                                 var rect:Rectangle = tf.getCharBoundaries(i);
415                                 if (rect) {
416                                         s.addChild(rotatedLetter(chars[i],
417                                                                                          tStart + offsetSign*(rect.left+rect.width/2)/pathlength,
418                                                                                          rect.width, tf.height, angleOffset, textOffset));
419                                 }
420                         }
421                 }
422
423                 private function rotatedLetter(char:String, t:Number, w:Number, h:Number, a:Number, o:Number):TextField {
424                         var tf:TextField = new TextField();
425             tf.mouseEnabled = false;
426             tf.mouseWheelEnabled = false;
427                         tf.defaultTextFormat = nameformat;
428                         tf.embedFonts = true;
429                         tf.text = char;
430                         tf.width = tf.textWidth+4;
431                         tf.height = tf.textHeight+4;
432
433                         var p:Array=pointAt(t);
434                         var matrix:Matrix = new Matrix();
435                         matrix.translate(-w/2, -h/2-o);
436                         // ** add (say) -4 to the height to move it up by 4px
437                         matrix.rotate(p[2]+a);
438                         matrix.translate(p[0], p[1]);
439                         tf.transform.matrix = matrix;
440                         return tf;
441                 }
442                 
443                 // Add object (stroke/fill/roadname) to layer sprite
444                 
445                 private function addToLayer(s:DisplayObject,t:uint,sublayer:int=-1):void {
446                         var l:DisplayObject=Map(map).getChildAt(map.WAYSPRITE+layer);
447                         var o:DisplayObject=Sprite(l).getChildAt(t);
448                         if (sublayer!=-1) { o=Sprite(o).getChildAt(sublayer); }
449                         Sprite(o).addChild(s);
450                         sprites.push(s);
451             if ( s is Sprite ) {
452                 Sprite(s).mouseEnabled = false;
453                 Sprite(s).mouseChildren = false;
454             }
455                 }
456
457                 public function getNodeAt(x:Number, y:Number):Node {
458                         for (var i:uint = 0; i < way.length; i++) {
459                 var node:Node = way.getNode(i);
460                 var nodeX:Number = map.lon2coord(node.lon);
461                 var nodeY:Number = map.latp2coord(node.latp);
462                 if ( nodeX >= x-NODESIZE && nodeX <= x+NODESIZE &&
463                      nodeY >= y-NODESIZE && nodeY <= y+NODESIZE )
464                     return node;
465             }
466             return null;
467                 }
468
469         private function mouseEvent(event:MouseEvent):void {
470             var node:Node = getNodeAt(event.localX, event.localY);
471             if ( node == null )
472                 map.entityMouseEvent(event, way);
473             else
474                 map.entityMouseEvent(event, node);
475         }
476
477         public function setHighlight(stateType:String, isOn:Boolean):void {
478             if ( isOn && stateClasses[stateType] == null ) {
479                 stateClasses[stateType] = true;
480                 redraw();
481             } else if ( !isOn && stateClasses[stateType] != null ) {
482                 delete stateClasses[stateType];
483                 redraw();
484             }
485         }
486         }
487 }