1 package net.systemeD.halcyon.styleparser {
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;
10 import net.systemeD.halcyon.connection.*;
11 import net.systemeD.halcyon.Globals;
12 // import bustin.dev.Inspector;
14 public class RuleSet {
16 public var loaded:Boolean=false; // has it loaded yet?
17 public var images:Object=new Object(); // loaded images
18 public var imageWidths:Object=new Object(); // width of each bitmap image
19 private var redrawCallback:Function=null; // function to call when CSS loaded
20 private var iconCallback:Function=null; // function to call when all icons loaded
21 private var iconsToLoad:uint=0; // number of icons left to load (fire iconCallback when ==0)
22 private var evalsToLoad:uint=0; // number of evals left to load (fire redrawCallback when ==0)
24 private var minscale:uint;
25 private var maxscale:uint;
26 public var choosers:Array;
27 public var evals:Array;
29 private static const WHITESPACE:RegExp =/^ \s+ /sx;
30 private static const COMMENT:RegExp =/^ \/\* .+? \*\/ \s* /sx; /* */
31 private static const CLASS:RegExp =/^ ([\.:]\w+) \s* /sx;
32 private static const NOT_CLASS:RegExp =/^ !([\.:]\w+) \s* /sx;
33 private static const ZOOM:RegExp =/^ \| \s* z([\d\-]+) \s* /isx;
34 private static const GROUP:RegExp =/^ , \s* /isx;
35 private static const CONDITION:RegExp =/^ \[(.+?)\] \s* /sx;
36 private static const OBJECT:RegExp =/^ (\w+) \s* /sx;
37 private static const DECLARATION:RegExp =/^ \{(.+?)\} \s* /sx;
38 private static const UNKNOWN:RegExp =/^ (\S+) \s* /sx;
40 private static const ZOOM_MINMAX:RegExp =/^ (\d+)\-(\d+) $/sx;
41 private static const ZOOM_MIN:RegExp =/^ (\d+)\- $/sx;
42 private static const ZOOM_MAX:RegExp =/^ \-(\d+) $/sx;
43 private static const ZOOM_SINGLE:RegExp =/^ (\d+) $/sx;
45 private static const CONDITION_TRUE:RegExp =/^ \s* ([:\w]+) \s* = \s* yes \s* $/isx;
46 private static const CONDITION_FALSE:RegExp =/^ \s* ([:\w]+) \s* = \s* no \s* $/isx;
47 private static const CONDITION_SET:RegExp =/^ \s* ([:\w]+) \s* $/sx;
48 private static const CONDITION_UNSET:RegExp =/^ \s* !([:\w]+) \s* $/sx;
49 private static const CONDITION_EQ:RegExp =/^ \s* ([:\w]+) \s* = \s* (.+) \s* $/sx;
50 private static const CONDITION_NE:RegExp =/^ \s* ([:\w]+) \s* != \s* (.+) \s* $/sx;
51 private static const CONDITION_GT:RegExp =/^ \s* ([:\w]+) \s* > \s* (.+) \s* $/sx;
52 private static const CONDITION_GE:RegExp =/^ \s* ([:\w]+) \s* >= \s* (.+) \s* $/sx;
53 private static const CONDITION_LT:RegExp =/^ \s* ([:\w]+) \s* < \s* (.+) \s* $/sx;
54 private static const CONDITION_LE:RegExp =/^ \s* ([:\w]+) \s* <= \s* (.+) \s* $/sx;
55 private static const CONDITION_REGEX:RegExp =/^ \s* ([:\w]+) \s* =~\/ \s* (.+) \/ \s* $/sx;
57 private static const ASSIGNMENT_EVAL:RegExp =/^ \s* (\S+) \s* \: \s* eval \s* \( \s* ' (.+?) ' \s* \) \s* $/isx;
58 private static const ASSIGNMENT:RegExp =/^ \s* (\S+) \s* \: \s* (.+?) \s* $/sx;
59 private static const SET_TAG_EVAL:RegExp =/^ \s* set \s+(\S+)\s* = \s* eval \s* \( \s* ' (.+?) ' \s* \) \s* $/isx;
60 private static const SET_TAG:RegExp =/^ \s* set \s+(\S+)\s* = \s* (.+?) \s* $/isx;
61 private static const SET_TAG_TRUE:RegExp =/^ \s* set \s+(\S+)\s* $/isx;
62 private static const EXIT:RegExp =/^ \s* exit \s* $/isx;
64 private static const oZOOM:uint=2;
65 private static const oGROUP:uint=3;
66 private static const oCONDITION:uint=4;
67 private static const oOBJECT:uint=5;
68 private static const oDECLARATION:uint=6;
70 private static const DASH:RegExp=/\-/g;
71 private static const COLOR:RegExp=/color$/;
72 private static const BOLD:RegExp=/^bold$/i;
73 private static const ITALIC:RegExp=/^italic|oblique$/i;
74 private static const UNDERLINE:RegExp=/^underline$/i;
75 private static const CAPS:RegExp=/^uppercase$/i;
76 private static const CENTER:RegExp=/^center$/i;
77 private static const FALSE:RegExp=/^(no|false|0)$/i;
79 private static const HEX:RegExp=/^#([0-9a-f]+)$/i;
80 private static const CSSCOLORS:Object = {
82 antiquewhite:0xfaebd7,
89 blanchedalmond:0xffebcd,
98 cornflowerblue:0x6495ed,
104 darkgoldenrod:0xb8860b,
108 darkmagenta:0x8b008b,
109 darkolivegreen:0x556b2f,
114 darkseagreen:0x8fbc8f,
115 darkslateblue:0x483d8b,
116 darkslategray:0x2f4f4f,
117 darkturquoise:0x00ced1,
120 deepskyblue:0x00bfff,
124 floralwhite:0xfffaf0,
125 forestgreen:0x228b22,
133 greenyellow:0xadff2f,
141 lavenderblush:0xfff0f5,
143 lemonchiffon:0xfffacd,
147 lightgoldenrodyellow:0xfafad2,
151 lightsalmon:0xffa07a,
152 lightseagreen:0x20b2aa,
153 lightskyblue:0x87cefa,
154 lightslategray:0x778899,
155 lightsteelblue:0xb0c4de,
156 lightyellow:0xffffe0,
162 mediumaquamarine:0x66cdaa,
164 mediumorchid:0xba55d3,
165 mediumpurple:0x9370d8,
166 mediumseagreen:0x3cb371,
167 mediumslateblue:0x7b68ee,
168 mediumspringgreen:0x00fa9a,
169 mediumturquoise:0x48d1cc,
170 mediumvioletred:0xc71585,
171 midnightblue:0x191970,
175 navajowhite:0xffdead,
183 palegoldenrod:0xeee8aa,
185 paleturquoise:0xafeeee,
186 palevioletred:0xd87093,
197 saddlebrown:0x8b4513,
208 springgreen:0x00ff7f,
220 yellowgreen:0x9acd32 };
222 public function RuleSet(mins:uint,maxs:uint,redrawCall:Function=null,iconLoadedCallback:Function=null):void {
225 redrawCallback = redrawCall;
226 iconCallback = iconLoadedCallback;
229 // Get styles for an object
231 public function getStyles(obj:Entity, tags:Object, zoom:uint):StyleList {
232 var sl:StyleList=new StyleList();
233 for each (var sc:StyleChooser in choosers) {
234 sc.updateStyles(obj,tags,sl,imageWidths,zoom);
239 // ---------------------------------------------------------------------------------------------------------
240 // Loading stylesheet
242 public function loadFromCSS(str:String):void {
243 if (str.match(/[\s\n\r\t]/)!=null) { parseCSS(str); loaded=true; redrawCallback(); return; }
245 var request:DebugURLRequest=new DebugURLRequest(str);
246 var loader:URLLoader=new URLLoader();
248 // request.method=URLRequestMethod.GET;
249 loader.dataFormat = URLLoaderDataFormat.TEXT;
250 loader.addEventListener(Event.COMPLETE, doParseCSS);
251 loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
252 loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
253 loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
254 loader.load(request.request);
257 private function doParseCSS(e:Event):void {
258 parseCSS(e.target.data);
261 private function parseCSS(str:String):void {
264 if (evals.length==0) { redrawCallback(); }
269 // ------------------------------------------------------------------------------------------------
270 // Load all referenced images
271 // ** will duplicate if referenced twice, shouldn't
273 public function loadImages():void {
275 for each (var chooser:StyleChooser in choosers) {
276 for each (var style:Style in chooser.styles) {
277 if (style is PointStyle && PointStyle(style).icon_image ) { filename=PointStyle(style).icon_image; }
278 else if (style is ShapeStyle && ShapeStyle(style).fill_image ) { filename=ShapeStyle(style).fill_image; }
279 else if (style is ShieldStyle && ShieldStyle(style).shield_image) { filename=ShieldStyle(style).shield_image; }
281 if (filename=='square' || filename=='circle') { continue; }
284 var request:DebugURLRequest=new DebugURLRequest(filename);
285 var loader:ExtendedURLLoader=new ExtendedURLLoader();
286 loader.dataFormat=URLLoaderDataFormat.BINARY;
287 loader.info['filename']=filename;
288 loader.addEventListener(Event.COMPLETE, loadedImage, false, 0, true);
289 loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler, false, 0, true);
290 loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onImageLoadSecurityError, false, 0, true);
291 loader.addEventListener(IOErrorEvent.IO_ERROR, onImageLoadioError, false, 0, true);
292 loader.load(request.request);
299 private function loadedImage(event:Event):void {
300 var fn:String=event.target.info['filename'];
301 images[fn]=event.target.data;
303 var loader:ExtendedLoader = new ExtendedLoader();
304 loader.info['filename']=fn;
305 loader.contentLoaderInfo.addEventListener(Event.COMPLETE, measureWidth);
306 loader.loadBytes(images[fn]);
309 private function measureWidth(event:Event):void {
310 var fn:String=event.target.loader.info['filename'];
311 imageWidths[fn]=event.target.width;
312 // ** do we need to explicitly remove the loader object now?
314 oneLessImageToLoad();
317 private function oneLessImageToLoad():void {
319 if (iconsToLoad<=0 && iconCallback!=null) { iconCallback(); }
322 private function onImageLoadioError ( event:IOErrorEvent ):void {
323 trace("ioerrorevent: "+event.target.info['filename']);
324 oneLessImageToLoad();
327 private function onImageLoadSecurityError ( event:SecurityErrorEvent ):void {
328 trace("securityerrorevent: "+event.target.info['filename']);
329 oneLessImageToLoad();
332 private function httpStatusHandler( event:HTTPStatusEvent ):void { }
333 private function securityErrorHandler( event:SecurityErrorEvent ):void { Globals.vars.root.addDebug("securityerrorevent"); }
334 private function ioErrorHandler( event:IOErrorEvent ):void { Globals.vars.root.addDebug("ioerrorevent"); }
336 // ------------------------------------------------------------------------------------------------
339 public function parse(css:String):void {
340 var previous:uint=0; // what was the previous CSS word?
341 var sc:StyleChooser=new StyleChooser(); // currently being assembled
342 choosers=new Array();
345 var o:Object=new Object();
346 while (css.length>0) {
349 if ((o=COMMENT.exec(css))) {
350 css=css.replace(COMMENT,'');
352 // Whitespace (probably only at beginning of file)
353 } else if ((o=WHITESPACE.exec(css))) {
354 css=css.replace(WHITESPACE,'');
356 // Class - .motorway, .builtup, :hover
357 } else if ((o=CLASS.exec(css))) {
358 if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
360 css=css.replace(CLASS,'');
361 sc.addCondition(new Condition('set',o[1]));
364 // Not class - !.motorway, !.builtup, !:hover
365 } else if ((o=NOT_CLASS.exec(css))) {
366 if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
368 css=css.replace(NOT_CLASS,'');
369 sc.addCondition(new Condition('unset',o[1]));
373 } else if ((o=ZOOM.exec(css))) {
374 if (previous!=oOBJECT && previous!=oCONDITION) { sc.newObject(); }
376 css=css.replace(ZOOM,'');
377 var z:Array=parseZoom(o[1]);
378 sc.addZoom(z[0],z[1]);
381 // Grouping - just a comma
382 } else if ((o=GROUP.exec(css))) {
383 css=css.replace(GROUP,'');
387 // Condition - [highway=primary]
388 } else if ((o=CONDITION.exec(css))) {
389 if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
390 if (previous!=oOBJECT && previous!=oZOOM && previous!=oCONDITION) { sc.newObject(); }
391 css=css.replace(CONDITION,'');
392 sc.addCondition(parseCondition(o[1]) as Condition);
395 // Object - way, node, relation
396 } else if ((o=OBJECT.exec(css))) {
397 if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
399 css=css.replace(OBJECT,'');
403 // Declaration - {...}
404 } else if ((o=DECLARATION.exec(css))) {
405 css=css.replace(DECLARATION,'');
406 sc.addStyles(parseDeclaration(o[1]));
407 previous=oDECLARATION;
410 } else if ((o=UNKNOWN.exec(css))) {
411 css=css.replace(UNKNOWN,'');
412 Globals.vars.root.addDebug("unknown: "+o[1]);
413 // ** do some debugging with o[1]
416 Globals.vars.root.addDebug("choked on "+css);
420 if (previous==oDECLARATION) { saveChooser(sc); sc=new StyleChooser(); }
423 private function saveChooser(sc:StyleChooser):void {
427 private function saveEval(expr:String):Eval {
429 var e:Eval=new Eval(expr);
430 e.addEventListener("swf_loaded",evalLoaded);
435 private function evalLoaded(e:Event):void {
437 if (evalsToLoad==0) { redrawCallback(); }
440 // Parse declaration string into list of styles
442 private function parseDeclaration(s:String):Array {
444 var t:Object=new Object();
445 var o:Object=new Object();
446 var a:String, k:String, v:*;
449 var ss:ShapeStyle =new ShapeStyle() ;
450 var ps:PointStyle =new PointStyle() ;
451 var ts:TextStyle =new TextStyle() ;
452 var hs:ShieldStyle=new ShieldStyle();
453 var xs:InstructionStyle=new InstructionStyle();
455 for each (a in s.split(';')) {
456 if ((o=ASSIGNMENT_EVAL.exec(a))) { t[o[1].replace(DASH,'_')]=saveEval(o[2]); }
457 else if ((o=ASSIGNMENT.exec(a))) { t[o[1].replace(DASH,'_')]=o[2]; }
458 else if ((o=SET_TAG_EVAL.exec(a))) { xs.addSetTag(o[1],saveEval(o[2])); }
459 else if ((o=SET_TAG.exec(a))) { xs.addSetTag(o[1],o[2]); }
460 else if ((o=SET_TAG_TRUE.exec(a))) { xs.addSetTag(o[1],true); }
461 else if ((o=EXIT.exec(a))) { xs.setPropertyFromString('breaker',true); }
466 if (t['z_index']) { sub=Number(t['z_index']); delete t['z_index']; }
467 ss.sublayer=ps.sublayer=ts.sublayer=hs.sublayer=sub;
471 var inter:Boolean=true;
472 if (t['interactive']) { inter=t['interactive'].match(FALSE) ? false : true; delete t['interactive']; }
473 ss.interactive=ps.interactive=ts.interactive=hs.interactive=xs.interactive=inter;
475 // Munge special values
476 if (t['font_weight'] ) { t['font_bold' ] = t['font_weight' ].match(BOLD ) ? true : false; delete t['font_weight']; }
477 if (t['font_style'] ) { t['font_italic'] = t['font_style' ].match(ITALIC) ? true : false; delete t['font_style']; }
478 if (t['text_decoration']) { t['font_underline'] = t['text_decoration'].match(UNDERLINE) ? true : false; delete t['text_decoration']; }
479 if (t['text_position'] ) { t['text_center'] = t['text_position' ].match(CENTER) ? true : false; delete t['text_position']; }
480 if (t['text_transform']) {
481 // ** needs other transformations, e.g. lower-case, sentence-case
482 if (t['text_transform'].match(CAPS)) { t['font_caps']=true; } else { t['font_caps']=false; }
483 delete t['text_transform'];
486 // ** Do compound settings (e.g. line: 5px dotted blue;)
488 // Assign each property to the appropriate style
491 // ** also do units, e.g. px/pt/m
492 if (a.match(COLOR)) { v = parseCSSColor(t[a]); }
496 if (ss.hasOwnProperty(a)) { ss.setPropertyFromString(a,v); }
497 else if (ps.hasOwnProperty(a)) { ps.setPropertyFromString(a,v); }
498 else if (ts.hasOwnProperty(a)) { ts.setPropertyFromString(a,v); }
499 else if (hs.hasOwnProperty(a)) { hs.setPropertyFromString(a,v); }
502 // Add each style to list
503 if (ss.edited) { styles.push(ss); }
504 if (ps.edited) { styles.push(ps); }
505 if (ts.edited) { styles.push(ts); }
506 if (hs.edited) { styles.push(hs); }
507 if (xs.edited) { styles.push(xs); }
511 private function parseZoom(s:String):Array {
512 var o:Object=new Object();
513 if ((o=ZOOM_MINMAX.exec(s))) { return [o[1],o[2]]; }
514 else if ((o=ZOOM_MIN.exec(s))) { return [o[1],maxscale]; }
515 else if ((o=ZOOM_MAX.exec(s))) { return [minscale,o[1]]; }
516 else if ((o=ZOOM_SINGLE.exec(s))) { return [o[1],o[1]]; }
520 private function parseCondition(s:String):Object {
521 var o:Object=new Object();
522 if ((o=CONDITION_TRUE.exec(s))) { return new Condition('true' ,o[1]); }
523 else if ((o=CONDITION_FALSE.exec(s))) { return new Condition('false',o[1]); }
524 else if ((o=CONDITION_SET.exec(s))) { return new Condition('set' ,o[1]); }
525 else if ((o=CONDITION_UNSET.exec(s))) { return new Condition('unset',o[1]); }
526 else if ((o=CONDITION_NE.exec(s))) { return new Condition('ne' ,o[1],o[2]); }
527 else if ((o=CONDITION_GT.exec(s))) { return new Condition('>' ,o[1],o[2]); }
528 else if ((o=CONDITION_GE.exec(s))) { return new Condition('>=' ,o[1],o[2]); }
529 else if ((o=CONDITION_LT.exec(s))) { return new Condition('<' ,o[1],o[2]); }
530 else if ((o=CONDITION_LE.exec(s))) { return new Condition('<=' ,o[1],o[2]); }
531 else if ((o=CONDITION_REGEX.exec(s))) { return new Condition('regex',o[1],o[2]); }
532 else if ((o=CONDITION_EQ.exec(s))) { return new Condition('eq' ,o[1],o[2]); }
536 public static function parseCSSColor(colorStr:String):uint {
537 colorStr = colorStr.toLowerCase();
538 if (CSSCOLORS[colorStr]) {
539 return CSSCOLORS[colorStr];
541 var match:Object = HEX.exec(colorStr);
543 if ( match[1].length == 3) {
544 // repeat digits. #abc => 0xaabbcc
545 return Number("0x"+match[1].charAt(0)+match[1].charAt(0)+
546 match[1].charAt(1)+match[1].charAt(1)+
547 match[1].charAt(2)+match[1].charAt(2));
548 } else if ( match[1].length == 6) {
549 return Number("0x"+match[1]);
551 return Number("0x000000"); //as good as any