1 ! Copyright (C) 2003, 2009 Slava Pestov.
2 ! Copyright (C) 2008 Eduardo Cavazos.
3 ! See http://factorcode.org/license.txt for BSD license.
4 USING: accessors ascii arrays assocs combinators grouping
5 io.encodings.utf8 io.files kernel lexer math math.functions
6 math.parser sequences splitting vocabs.loader ;
9 ! FIXME: replace with MIXIN: color INSTANCE: rgba color
20 GENERIC: >rgba ( color -- rgba )
22 M: rgba >rgba ; inline
24 M: color red>> >rgba red>> ;
25 M: color green>> >rgba green>> ;
26 M: color blue>> >rgba blue>> ;
28 : >rgba-components ( object -- r g b a )
29 >rgba { [ red>> ] [ green>> ] [ blue>> ] [ alpha>> ] } cleave ; inline
31 : opaque? ( color -- ? ) alpha>> 1 number= ;
33 CONSTANT: transparent T{ rgba f 0.0 0.0 0.0 0.0 }
35 : inverse-color ( color -- color' )
36 >rgba-components [ [ 1.0 swap - ] tri@ ] dip <rgba> ;
38 : color= ( color1 color2 -- ? )
39 [ >rgba-components 4array ] bi@ [ 0.00000001 ~ ] 2all? ;
43 : parse-color ( line -- name color )
45 [ [ string>number 255 /f ] tri@ 1.0 <rgba> ] dip
46 [ ascii:blank? ] trim-head H{ { CHAR: \s CHAR: - } } substitute swap ;
48 : parse-colors ( lines -- assoc )
50 [ 11 cut [ " \t" split harvest ] dip suffix ] map
51 [ parse-color ] H{ } map>assoc ;
53 MEMO: colors ( -- assoc )
54 "resource:basis/colors/rgb.txt"
55 "resource:basis/colors/factor-colors.txt"
56 "resource:basis/colors/solarized-colors.txt"
57 [ utf8 file-lines parse-colors ] tri@ assoc-union assoc-union ;
59 ERROR: invalid-hex-color hex ;
61 : hex>rgba ( hex -- rgba )
63 { 6 [ 2 group [ hex> 255 /f ] map first3 1.0 ] }
64 { 8 [ 2 group [ hex> 255 /f ] map first4 ] }
65 { 3 [ [ digit> 15 /f ] { } map-as first3 1.0 ] }
66 { 4 [ [ digit> 15 /f ] { } map-as first4 ] }
67 [ drop invalid-hex-color ]
72 : named-colors ( -- keys ) colors keys ;
74 ERROR: no-such-color name ;
76 : named-color ( name -- color )
77 dup colors at [ ] [ no-such-color ] ?if ;
79 : parse-color ( str -- color )
80 "#" ?head [ hex>rgba ] [ named-color ] if ;
82 TUPLE: parsed-color < color string value ;
84 M: parsed-color >rgba value>> >rgba ;
86 SYNTAX: COLOR: scan-token dup parse-color parsed-color boa suffix! ;
88 { "colors" "prettyprint" } "colors.prettyprint" require-when