New RuleChain object to replace previous nested array within StyleChooser
[potlatch2.git] / net / systemeD / halcyon / styleparser / RuleSet.as
1 package net.systemeD.halcyon.styleparser {
2
3         import flash.events.*;
4         import flash.net.*;
5         import net.systemeD.halcyon.ExtendedLoader;
6         import net.systemeD.halcyon.ExtendedURLLoader;
7         import net.systemeD.halcyon.DebugURLRequest;
8     import net.systemeD.halcyon.connection.Entity;
9
10     import net.systemeD.halcyon.connection.*;
11         
12         /** A complete stylesheet, as loaded from a MapCSS file. It contains all selectors, declarations, 
13                 and embedded images.                                                                                                                                                            </p><p>
14                 
15                 The RuleSet class has two principal methods: getStyles, which calculates the styles that apply
16                 to an entity (returned as a StyleList); and parse, which parses a MapCSS stylesheet into
17                 a complete RuleSet. */
18
19         public class RuleSet {
20
21                 /** Is the RuleSet fully loaded and available for use? */
22                 public var loaded:Boolean=false; 
23                 /** Hash of loaded images. Hash key is filename, value is BitmapData for the image. */
24                 public var images:Object=new Object();
25                 /** Hash of image widths. Hash key is filename, value is pixel width. */
26                 public var imageWidths:Object=new Object();     
27                 private var redrawCallback:Function=null;       // function to call when CSS loaded
28                 private var iconCallback:Function=null;         // function to call when all icons loaded
29                 private var iconsToLoad:uint=0;                         // number of icons left to load (fire iconCallback when ==0)
30                 private var evalsToLoad:uint=0;                         // number of evals left to load (fire redrawCallback when ==0)
31
32                 private var minscale:uint;
33                 private var maxscale:uint;
34                 public var choosers:Array;
35                 public var evals:Array;
36
37                 private static const WHITESPACE:RegExp  =/^ \s+ /sx;
38                 private static const COMMENT:RegExp             =/^ \/\* .+? \*\/ \s* /sx;      /* */
39                 private static const CLASS:RegExp               =/^ ([\.:]\w+) \s* /sx;
40                 private static const NOT_CLASS:RegExp   =/^ !([\.:]\w+) \s* /sx;
41                 private static const ZOOM:RegExp                =/^ \| \s* z([\d\-]+) \s* /isx;
42                 private static const GROUP:RegExp               =/^ , \s* /isx;
43                 private static const CONDITION:RegExp   =/^ \[(.+?)\] \s* /sx;
44                 private static const OBJECT:RegExp              =/^ (\w+) \s* /sx;
45                 private static const DECLARATION:RegExp =/^ \{(.+?)\} \s* /sx;
46                 private static const SUBPART:RegExp             =/^ ::(\S+) \s* /sx;
47                 private static const UNKNOWN:RegExp             =/^ (\S+) \s* /sx;
48
49                 private static const ZOOM_MINMAX:RegExp =/^ (\d+)\-(\d+) $/sx;
50                 private static const ZOOM_MIN:RegExp    =/^ (\d+)\-      $/sx;
51                 private static const ZOOM_MAX:RegExp    =/^      \-(\d+) $/sx;
52                 private static const ZOOM_SINGLE:RegExp =/^        (\d+) $/sx;
53
54                 private static const CONDITION_TRUE:RegExp      =/^ \s* ([:\w]+) \s* = \s* yes \s*  $/isx;
55                 private static const CONDITION_FALSE:RegExp     =/^ \s* ([:\w]+) \s* = \s* no  \s*  $/isx;
56                 private static const CONDITION_SET:RegExp       =/^ \s* ([:\w]+) \s* $/sx;
57                 private static const CONDITION_UNSET:RegExp     =/^ \s* !([:\w]+) \s* $/sx;
58                 private static const CONDITION_EQ:RegExp        =/^ \s* ([:\w]+) \s* =  \s* (.+) \s* $/sx;
59                 private static const CONDITION_NE:RegExp        =/^ \s* ([:\w]+) \s* != \s* (.+) \s* $/sx;
60                 private static const CONDITION_GT:RegExp        =/^ \s* ([:\w]+) \s* >  \s* (.+) \s* $/sx;
61                 private static const CONDITION_GE:RegExp        =/^ \s* ([:\w]+) \s* >= \s* (.+) \s* $/sx;
62                 private static const CONDITION_LT:RegExp        =/^ \s* ([:\w]+) \s* <  \s* (.+) \s* $/sx;
63                 private static const CONDITION_LE:RegExp        =/^ \s* ([:\w]+) \s* <= \s* (.+) \s* $/sx;
64                 private static const CONDITION_REGEX:RegExp     =/^ \s* ([:\w]+) \s* =~\/ \s* (.+) \/ \s* $/sx;
65
66                 private static const ASSIGNMENT_EVAL:RegExp     =/^ \s* (\S+) \s* \:      \s* eval \s* \( \s* ' (.+?) ' \s* \) \s* $/isx;
67                 private static const ASSIGNMENT:RegExp          =/^ \s* (\S+) \s* \:      \s*          (.+?) \s*                   $/sx;
68                 private static const SET_TAG_EVAL:RegExp        =/^ \s* set \s+(\S+)\s* = \s* eval \s* \( \s* ' (.+?) ' \s* \) \s* $/isx;
69                 private static const SET_TAG:RegExp                     =/^ \s* set \s+(\S+)\s* = \s*          (.+?) \s*                   $/isx;
70                 private static const SET_TAG_TRUE:RegExp        =/^ \s* set \s+(\S+)\s* $/isx;
71                 private static const EXIT:RegExp                        =/^ \s* exit \s* $/isx;
72
73                 private static const oZOOM:uint=2;
74                 private static const oGROUP:uint=3;
75                 private static const oCONDITION:uint=4;
76                 private static const oOBJECT:uint=5;
77                 private static const oDECLARATION:uint=6;
78
79                 private static const DASH:RegExp=/\-/g;
80                 private static const COLOR:RegExp=/color$/;
81                 private static const BOLD:RegExp=/^bold$/i;
82                 private static const ITALIC:RegExp=/^italic|oblique$/i;
83                 private static const UNDERLINE:RegExp=/^underline$/i;
84                 private static const CAPS:RegExp=/^uppercase$/i;
85                 private static const CENTER:RegExp=/^center$/i;
86                 private static const FALSE:RegExp=/^(no|false|0)$/i;
87
88                 private static const HEX:RegExp=/^#([0-9a-f]+)$/i;
89                 private static const CSSCOLORS:Object = {
90                         aliceblue:0xf0f8ff,
91                         antiquewhite:0xfaebd7,
92                         aqua:0x00ffff,
93                         aquamarine:0x7fffd4,
94                         azure:0xf0ffff,
95                         beige:0xf5f5dc,
96                         bisque:0xffe4c4,
97                         black:0x000000,
98                         blanchedalmond:0xffebcd,
99                         blue:0x0000ff,
100                         blueviolet:0x8a2be2,
101                         brown:0xa52a2a,
102                         burlywood:0xdeb887,
103                         cadetblue:0x5f9ea0,
104                         chartreuse:0x7fff00,
105                         chocolate:0xd2691e,
106                         coral:0xff7f50,
107                         cornflowerblue:0x6495ed,
108                         cornsilk:0xfff8dc,
109                         crimson:0xdc143c,
110                         cyan:0x00ffff,
111                         darkblue:0x00008b,
112                         darkcyan:0x008b8b,
113                         darkgoldenrod:0xb8860b,
114                         darkgray:0xa9a9a9,
115                         darkgreen:0x006400,
116                         darkkhaki:0xbdb76b,
117                         darkmagenta:0x8b008b,
118                         darkolivegreen:0x556b2f,
119                         darkorange:0xff8c00,
120                         darkorchid:0x9932cc,
121                         darkred:0x8b0000,
122                         darksalmon:0xe9967a,
123                         darkseagreen:0x8fbc8f,
124                         darkslateblue:0x483d8b,
125                         darkslategray:0x2f4f4f,
126                         darkturquoise:0x00ced1,
127                         darkviolet:0x9400d3,
128                         deeppink:0xff1493,
129                         deepskyblue:0x00bfff,
130                         dimgray:0x696969,
131                         dodgerblue:0x1e90ff,
132                         firebrick:0xb22222,
133                         floralwhite:0xfffaf0,
134                         forestgreen:0x228b22,
135                         fuchsia:0xff00ff,
136                         gainsboro:0xdcdcdc,
137                         ghostwhite:0xf8f8ff,
138                         gold:0xffd700,
139                         goldenrod:0xdaa520,
140                         gray:0x808080,
141                         green:0x008000,
142                         greenyellow:0xadff2f,
143                         honeydew:0xf0fff0,
144                         hotpink:0xff69b4,
145                         indianred :0xcd5c5c,
146                         indigo :0x4b0082,
147                         ivory:0xfffff0,
148                         khaki:0xf0e68c,
149                         lavender:0xe6e6fa,
150                         lavenderblush:0xfff0f5,
151                         lawngreen:0x7cfc00,
152                         lemonchiffon:0xfffacd,
153                         lightblue:0xadd8e6,
154                         lightcoral:0xf08080,
155                         lightcyan:0xe0ffff,
156                         lightgoldenrodyellow:0xfafad2,
157                         lightgrey:0xd3d3d3,
158                         lightgreen:0x90ee90,
159                         lightpink:0xffb6c1,
160                         lightsalmon:0xffa07a,
161                         lightseagreen:0x20b2aa,
162                         lightskyblue:0x87cefa,
163                         lightslategray:0x778899,
164                         lightsteelblue:0xb0c4de,
165                         lightyellow:0xffffe0,
166                         lime:0x00ff00,
167                         limegreen:0x32cd32,
168                         linen:0xfaf0e6,
169                         magenta:0xff00ff,
170                         maroon:0x800000,
171                         mediumaquamarine:0x66cdaa,
172                         mediumblue:0x0000cd,
173                         mediumorchid:0xba55d3,
174                         mediumpurple:0x9370d8,
175                         mediumseagreen:0x3cb371,
176                         mediumslateblue:0x7b68ee,
177                         mediumspringgreen:0x00fa9a,
178                         mediumturquoise:0x48d1cc,
179                         mediumvioletred:0xc71585,
180                         midnightblue:0x191970,
181                         mintcream:0xf5fffa,
182                         mistyrose:0xffe4e1,
183                         moccasin:0xffe4b5,
184                         navajowhite:0xffdead,
185                         navy:0x000080,
186                         oldlace:0xfdf5e6,
187                         olive:0x808000,
188                         olivedrab:0x6b8e23,
189                         orange:0xffa500,
190                         orangered:0xff4500,
191                         orchid:0xda70d6,
192                         palegoldenrod:0xeee8aa,
193                         palegreen:0x98fb98,
194                         paleturquoise:0xafeeee,
195                         palevioletred:0xd87093,
196                         papayawhip:0xffefd5,
197                         peachpuff:0xffdab9,
198                         peru:0xcd853f,
199                         pink:0xffc0cb,
200                         plum:0xdda0dd,
201                         powderblue:0xb0e0e6,
202                         purple:0x800080,
203                         red:0xff0000,
204                         rosybrown:0xbc8f8f,
205                         royalblue:0x4169e1,
206                         saddlebrown:0x8b4513,
207                         salmon:0xfa8072,
208                         sandybrown:0xf4a460,
209                         seagreen:0x2e8b57,
210                         seashell:0xfff5ee,
211                         sienna:0xa0522d,
212                         silver:0xc0c0c0,
213                         skyblue:0x87ceeb,
214                         slateblue:0x6a5acd,
215                         slategray:0x708090,
216                         snow:0xfffafa,
217                         springgreen:0x00ff7f,
218                         steelblue:0x4682b4,
219                         tan:0xd2b48c,
220                         teal:0x008080,
221                         thistle:0xd8bfd8,
222                         tomato:0xff6347,
223                         turquoise:0x40e0d0,
224                         violet:0xee82ee,
225                         wheat:0xf5deb3,
226                         white:0xffffff,
227                         whitesmoke:0xf5f5f5,
228                         yellow:0xffff00,
229                         yellowgreen:0x9acd32 };
230
231                 /** Constructor */
232
233                 public function RuleSet(mins:uint,maxs:uint,redrawCall:Function=null,iconLoadedCallback:Function=null):void {
234                         minscale = mins;
235                         maxscale = maxs;
236                         redrawCallback = redrawCall;
237                         iconCallback = iconLoadedCallback;
238                 }
239
240                 /** Create a StyleList for an Entity, by creating a blank StyleList, then running each StyleChooser over it.
241                         @see net.systemeD.halcyon.styleparser.StyleList */
242
243                 public function getStyles(obj:Entity, tags:Object, zoom:uint):StyleList {
244                         var sl:StyleList=new StyleList();
245                         for each (var sc:StyleChooser in choosers) {
246                                 sc.updateStyles(obj,tags,sl,imageWidths,zoom);
247                         }
248                         return sl;
249                 }
250
251                 // ---------------------------------------------------------------------------------------------------------
252                 // Loading stylesheet
253
254         /** Load and then parse a MapCSS stylesheet. Usually you will supply a filename, but you can also pass 
255                         a complete stylesheet in the string parameter. (Any string containing space characters will be 
256                         assumed to be a stylesheet rather than a filename.) */
257
258                 public function loadFromCSS(str:String):void {
259                         if (str.match(/[\s\n\r\t]/)!=null) { parseCSS(str); loaded=true; redrawCallback(); return; }
260
261                         var cssLoader:NestedCSSLoader=new NestedCSSLoader();
262                         cssLoader.addEventListener(Event.COMPLETE, doParseCSS);
263                         cssLoader.load(str);
264                 }
265
266                 private function doParseCSS(e:Event):void {
267                         parseCSS(e.target.css);
268                 }
269
270                 private function parseCSS(str:String):void {
271                         parse(str);
272                         loaded=true;
273                         if (evals.length==0) { redrawCallback(); }
274                         loadImages();
275                 }
276
277
278                 /// ------------------------------------------------------------------------------------------------
279                 /** Load all images referenced in the RuleSet (for example, icons or bitmap fills).
280                         FIXME: if an image is referenced twice, it'll be requested twice. */
281                 
282                 private function loadImages():void {
283                         var filename:String;
284                         for each (var chooser:StyleChooser in choosers) {
285                                 for each (var style:Style in chooser.styles) {
286                                         if      (style is PointStyle  && PointStyle(style).icon_image   ) { filename=PointStyle(style).icon_image; }
287                                         else if (style is ShapeStyle  && ShapeStyle(style).fill_image   ) { filename=ShapeStyle(style).fill_image; }
288                                         else if (style is ShieldStyle && ShieldStyle(style).shield_image) { filename=ShieldStyle(style).shield_image; }
289                                         else { continue; }
290                                         if (filename=='square' || filename=='circle') { continue; }
291                                 
292                                         iconsToLoad++;
293                                         var request:DebugURLRequest=new DebugURLRequest(filename);
294                                         var loader:ExtendedURLLoader=new ExtendedURLLoader();
295                                         loader.dataFormat=URLLoaderDataFormat.BINARY;
296                                         loader.info['filename']=filename;
297                                         loader.addEventListener(Event.COMPLETE,                                         loadedImage,                            false, 0, true);
298                                         loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,            httpStatusHandler,                      false, 0, true);
299                                         loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,      onImageLoadSecurityError,       false, 0, true);
300                                         loader.addEventListener(IOErrorEvent.IO_ERROR,                          onImageLoadioError,                     false, 0, true);
301                                         loader.load(request.request);
302                                 }
303                         }
304                 }
305
306                 private function loadedImage(event:Event):void {
307                         var fn:String=event.target.info['filename'];
308                         images[fn]=event.target.data; if (images[fn].length==0) return;
309
310                         var loader:ExtendedLoader = new ExtendedLoader();
311                         loader.info['filename']=fn;
312                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, measureWidth);
313                         loader.loadBytes(images[fn]);
314                 }
315                 
316                 private function measureWidth(event:Event):void {
317                         var fn:String=event.target.loader.info['filename'];
318                         imageWidths[fn]=event.target.width;
319                         // ** do we need to explicitly remove the loader object now?
320
321                         oneLessImageToLoad();
322                 }
323
324         private function oneLessImageToLoad():void {
325             iconsToLoad--;
326             if (iconsToLoad<=0 && iconCallback!=null) { iconCallback(); }
327         }
328
329         private function onImageLoadioError ( event:IOErrorEvent ):void {
330             trace("ioerrorevent: "+event.target.info['filename']);
331             oneLessImageToLoad();
332         }
333
334         private function onImageLoadSecurityError ( event:SecurityErrorEvent ):void {
335             trace("securityerrorevent: "+event.target.info['filename']);
336             oneLessImageToLoad();
337         }
338
339                 private function httpStatusHandler( event:HTTPStatusEvent ):void { }
340                 private function securityErrorHandler( event:SecurityErrorEvent ):void { trace("securityerrorevent"); }
341                 private function ioErrorHandler( event:IOErrorEvent ):void { trace("ioerrorevent"); }
342
343                 // ------------------------------------------------------------------------------------------------
344                 // Parse CSS
345
346                 /** Parse a MapCSS stylesheet into a set of StyleChoosers. The parser is regular expression-based 
347                         and runs sequentially through the file from start to end. */
348                 public function parse(css:String):void {
349                         var previous:uint=0;                                    // what was the previous CSS word?
350                         var sc:StyleChooser=new StyleChooser(); // currently being assembled
351                         choosers=new Array();
352                         evals=new Array();
353
354                         var o:Object=new Object();
355                         while (css.length>0) {
356
357                                 // CSS comment
358                                 if ((o=COMMENT.exec(css))) {
359                                         css=css.replace(COMMENT,'');
360
361                                 // Whitespace (probably only at beginning of file)
362                                 } else if ((o=WHITESPACE.exec(css))) {
363                                         css=css.replace(WHITESPACE,'');
364
365                                 // Class - .motorway, .builtup, :hover
366                                 } else if ((o=CLASS.exec(css))) {
367                                         if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
368
369                                         css=css.replace(CLASS,'');
370                                         sc.currentChain.addConditionToLast(new Condition('set',o[1]));
371                                         previous=oCONDITION;
372
373                                 // Not class - !.motorway, !.builtup, !:hover
374                                 } else if ((o=NOT_CLASS.exec(css))) {
375                                         if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
376
377                                         css=css.replace(NOT_CLASS,'');
378                                         sc.currentChain.addConditionToLast(new Condition('unset',o[1]));
379                                         previous=oCONDITION;
380
381                                 // Zoom
382                                 } else if ((o=ZOOM.exec(css))) {
383                                         if (previous!=oOBJECT && previous!=oCONDITION) { sc.currentChain.addRule(); }
384
385                                         css=css.replace(ZOOM,'');
386                                         var z:Array=parseZoom(o[1]);
387                                         sc.currentChain.addZoomToLast(z[0],z[1]);
388                                         sc.zoomSpecific=true;
389                                         previous=oZOOM;
390
391                                 // Grouping - just a comma
392                                 } else if ((o=GROUP.exec(css))) {
393                                         css=css.replace(GROUP,'');
394                                         sc.newRuleChain();
395                                         previous=oGROUP;
396
397                                 // Condition - [highway=primary]
398                                 } else if ((o=CONDITION.exec(css))) {
399                                         if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
400                                         if (previous!=oOBJECT && previous!=oZOOM && previous!=oCONDITION) { sc.currentChain.addRule(); }
401                                         css=css.replace(CONDITION,'');
402                                         sc.currentChain.addConditionToLast(parseCondition(o[1]) as Condition);
403                                         previous=oCONDITION;
404
405                                 // Object - way, node, relation
406                                 } else if ((o=OBJECT.exec(css))) {
407                                         if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
408
409                                         css=css.replace(OBJECT,'');
410                                         sc.currentChain.addRule(o[1]);
411                                         previous=oOBJECT;
412
413                                 // Declaration - {...}
414                                 } else if ((o=DECLARATION.exec(css))) {
415                                         css=css.replace(DECLARATION,'');
416                                         sc.addStyles(parseDeclaration(o[1]));
417                                         previous=oDECLARATION;
418                                 
419                                 // Unknown pattern
420                                 } else if ((o=UNKNOWN.exec(css))) {
421                                         css=css.replace(UNKNOWN,'');
422                                         trace("unknown: "+o[1]);
423                                         // ** do some debugging with o[1]
424
425                                 } else {
426                                         trace("choked on "+css);
427                                         return;
428                                 }
429                         }
430                         if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
431                 }
432                 
433                 private function saveChooser(sc:StyleChooser):void {
434                         choosers.push(sc);
435                 };
436                 
437                 private function saveEval(expr:String):Eval {
438                         evalsToLoad++;
439                         var e:Eval=new Eval(expr);
440                         e.addEventListener("swf_loaded",evalLoaded, false, 0, true);
441                         evals.push(e);
442                         return e;
443                 }
444                 
445                 private function evalLoaded(e:Event):void {
446                         evalsToLoad--;
447                         if (evalsToLoad==0) { redrawCallback(); }
448                 }
449
450                 // Parse declaration string into list of styles
451
452                 private function parseDeclaration(s:String):Array {
453                         var styles:Array=[];
454                         var t:Object=new Object();
455                         var o:Object=new Object();
456                         var a:String, k:String, v:*;
457
458                         // Create styles\10
459                         var ss:ShapeStyle =new ShapeStyle() ;
460                         var ps:PointStyle =new PointStyle() ; 
461                         var ts:TextStyle  =new TextStyle()  ; 
462                         var hs:ShieldStyle=new ShieldStyle(); 
463                         var xs:InstructionStyle=new InstructionStyle(); 
464
465                         for each (a in s.split(';')) {
466                                 if ((o=ASSIGNMENT_EVAL.exec(a)))   { t[o[1].replace(DASH,'_')]=saveEval(o[2]); }
467                                 else if ((o=ASSIGNMENT.exec(a)))   { t[o[1].replace(DASH,'_')]=o[2]; }
468                                 else if ((o=SET_TAG_EVAL.exec(a))) { xs.addSetTag(o[1],saveEval(o[2])); }
469                                 else if ((o=SET_TAG.exec(a)))      { xs.addSetTag(o[1],o[2]); }
470                                 else if ((o=SET_TAG_TRUE.exec(a))) { xs.addSetTag(o[1],true); }
471                                 else if ((o=EXIT.exec(a))) { xs.setPropertyFromString('breaker',true); }
472                         }
473
474                         // Find sublayer
475                         var sub:uint=5;
476                         if (t['z_index']) { sub=Number(t['z_index']); delete t['z_index']; }
477                         ss.sublayer=ps.sublayer=ts.sublayer=hs.sublayer=sub;
478                         xs.sublayer=10;
479                         
480                         // Find "interactive" property - it's true unless explicitly set false.
481                         var inter:Boolean=true;
482                         if (t['interactive']) { inter=t['interactive'].match(FALSE) ? false : true; delete t['interactive']; }
483                         ss.interactive=ps.interactive=ts.interactive=hs.interactive=xs.interactive=inter;
484
485                         // Munge special values
486                         if (t['font_weight']    ) { t['font_bold'  ]    = t['font_weight'    ].match(BOLD  )    ? true : false; delete t['font_weight']; }
487                         if (t['font_style']     ) { t['font_italic']    = t['font_style'     ].match(ITALIC)    ? true : false; delete t['font_style']; }
488                         if (t['text_decoration']) { t['font_underline'] = t['text_decoration'].match(UNDERLINE) ? true : false; delete t['text_decoration']; }
489                         if (t['text_position']  ) { t['text_center']    = t['text_position'  ].match(CENTER)    ? true : false; delete t['text_position']; }
490                         if (t['text_transform']) {
491                                 // ** needs other transformations, e.g. lower-case, sentence-case
492                                 if (t['text_transform'].match(CAPS)) { t['font_caps']=true; } else { t['font_caps']=false; }
493                                 delete t['text_transform'];
494                         }
495
496                         // ** Do compound settings (e.g. line: 5px dotted blue;)
497
498                         // Assign each property to the appropriate style
499                         for (a in t) {
500                                 // Parse properties
501                                 // ** also do units, e.g. px/pt/m
502                                 if (a.match(COLOR)) { v = parseCSSColor(t[a]); }
503                                                else { v = t[a]; }
504                                 
505                                 // Set in styles
506                                 if      (ss.hasOwnProperty(a)) { ss.setPropertyFromString(a,v); }
507                                 else if (ps.hasOwnProperty(a)) { ps.setPropertyFromString(a,v); }
508                                 else if (ts.hasOwnProperty(a)) { ts.setPropertyFromString(a,v); }
509                                 else if (hs.hasOwnProperty(a)) { hs.setPropertyFromString(a,v); }
510                         }
511
512                         // Add each style to list
513                         if (ss.edited) { styles.push(ss); }
514                         if (ps.edited) { styles.push(ps); }
515                         if (ts.edited) { styles.push(ts); }
516                         if (hs.edited) { styles.push(hs); }
517                         if (xs.edited) { styles.push(xs); }
518                         return styles;
519                 }
520                 
521                 private function parseZoom(s:String):Array {
522                         var o:Object=new Object();
523                         if ((o=ZOOM_MINMAX.exec(s))) { return [o[1],o[2]]; }
524                         else if ((o=ZOOM_MIN.exec(s))) { return [o[1],maxscale]; }
525                         else if ((o=ZOOM_MAX.exec(s))) { return [minscale,o[1]]; }
526                         else if ((o=ZOOM_SINGLE.exec(s))) { return [o[1],o[1]]; }
527                         return null;
528                 }
529
530                 private function parseCondition(s:String):Object {
531                         var o:Object=new Object();
532                         if      ((o=CONDITION_TRUE.exec(s)))  { return new Condition('true'     ,o[1]); }
533                         else if ((o=CONDITION_FALSE.exec(s))) { return new Condition('false',o[1]); }
534                         else if ((o=CONDITION_SET.exec(s)))   { return new Condition('set'      ,o[1]); }
535                         else if ((o=CONDITION_UNSET.exec(s))) { return new Condition('unset',o[1]); }
536                         else if ((o=CONDITION_NE.exec(s)))    { return new Condition('ne'       ,o[1],o[2]); }
537                         else if ((o=CONDITION_GT.exec(s)))    { return new Condition('>'        ,o[1],o[2]); }
538                         else if ((o=CONDITION_GE.exec(s)))    { return new Condition('>='       ,o[1],o[2]); }
539                         else if ((o=CONDITION_LT.exec(s)))    { return new Condition('<'        ,o[1],o[2]); }
540                         else if ((o=CONDITION_LE.exec(s)))    { return new Condition('<='       ,o[1],o[2]); }
541                         else if ((o=CONDITION_REGEX.exec(s))) { return new Condition('regex',o[1],o[2]); }
542                         else if ((o=CONDITION_EQ.exec(s)))    { return new Condition('eq'       ,o[1],o[2]); }
543                         return null;
544                 }
545
546         /** Convert a colour string from CSS colour name ("blue"), short hex ("#abc") or long hex ("#a0b0c0"), 
547                         to an integer. 
548                         
549                 @default 0 */
550
551         public static function parseCSSColor(colorStr:String):uint {
552             colorStr = colorStr.toLowerCase();
553             if (CSSCOLORS[colorStr]) {
554                 return CSSCOLORS[colorStr];
555             } else {
556                 var match:Object = HEX.exec(colorStr);
557                 if ( match ) { 
558                   if ( match[1].length == 3) {
559                     // repeat digits. #abc => 0xaabbcc
560                     return Number("0x"+match[1].charAt(0)+match[1].charAt(0)+
561                                        match[1].charAt(1)+match[1].charAt(1)+
562                                        match[1].charAt(2)+match[1].charAt(2));
563                   } else if ( match[1].length == 6) {
564                     return Number("0x"+match[1]);
565                   } else {
566                     return Number("0x000000"); //as good as any
567                   }
568                 }
569             }
570             return 0;
571         }
572         }
573 }