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