Source

cssutils-hg-merge / src / try.py

Full commit
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
# -*- coding: utf-8 -*-
__date__ = '$LastChangedDate::                            $:'

from StringIO import StringIO
from cssutils.prodparser import *
from pprint import pprint as pp
import codecs
import cssutils
import logging
import os
import re
import sys
import timeit
import unicodedata
import urllib
import urlparse
import xml
import xml.dom
try:
    from minimock import mock, restore
except ImportError:
    pass

sys.stdout.write(sys.version)
print

def save(name, string):
    f = open(name, 'w')
    f.write(string)
    f.close()


def maketokens(valuelist):
                # returns list of tuples
                return [('TYPE', v, 0, 0) for v in valuelist]



if 1:
    #cssutils.ser.prefs.indentClosingBrace = False
    css = '''
    a {
        left: .0;
        left: 0.0;
        left: .5;
        top: 0.6;
        top: -.5;
        top: +.5;
        left: .5px;
        top: 0.6px;
        top: -.5px;
        top: +.5px;
        left: .5%;
        top: 0.6%;
        top: -.5%;
        top: +.5%;
    }'''
    print cssutils.parseString(css).cssText
    cssutils.ser.prefs.keepLeadingZero = False
    print cssutils.parseString(css).cssText
    sys.exit(0)
    


if 1:
    href = os.path.join(os.path.dirname(__file__),
                        '..', 'sheets', 'import.css')
    href = cssutils.helper.path2url(href)
    #href = 'http://seewhatever.de/sheets/import.css'
    s = cssutils.parseUrl(href,
                          media='tv, print',
                          title='from url')
    print s.cssText
    sys.exit(0)

if 1:
    css = '\\ReD white transparent, navy #ff0000 #f0f #ff00ff #00ff00'
    p = cssutils.css.Property('color', css)
    print p
    print
    pv = p.propertyValue
    for c in pv:
        print c
        #print c.name, c.colorType, c.red, c.green, c.blue, c.alpha
#    for i, v in enumerate(pv):
#        print i, v
#        print 'RGBA', v.red, v.green, v.blue, v.alpha
#    v = cssutils.css.Value(css)
    #v = cssutils.css.CSSFunction(css)

#    print v
#    for i, x in enumerate(v.seq):
#        print i, x.value
    sys.exit(1)



if 1:
    import cssutils.script
    #p = r'sheets\vars\vars.css'
    p = r'sheets\var\start.css'

    do = """
    import cssutils
    t = cssutils.tokenize2.Tokenizer()
    css='''
    @page {}
    @media {}
    @media {}
    @media {}
    @media {}
    @media {}
    @media {}
    /* basic styles
 * $Id$
 */
html,body,h1,h2,h3,h4,h5,h6,p,form,iframe,pre,blockquote,ul,ol,li,dd,dl,fieldset,hr {
    margin: 0;
    padding: 0;
    }
body {
    font: normal 75%/1.5 sans-serif;
    color: #000;
    background-color: #fff;
    }
a {
    text-decoration: none;
    }
img {
    border: 0;
    }
textarea {
    resize: vertical;
    }
*>body sup,
*>body sub {
    vertical-align: baseline;
    position: relative;
    }
    *>body sup {
        top: -0.4em;
        }
    *>body sub {
        bottom: -0.2em;
        }
table {
    border-collapse: collapse;
    border-spacing: 0;
    }
    tr {
        vertical-align: top;
        }
    caption, th {
        text-align: left;
        }
ul, ol, li, dd {
    margin-left:20px
    }
    li {
        line-height: 1.25em;
        }
.inline {
    list-style: none;
    margin-left: 0;
    }
    .inline li {
        display: inline;
        margin-left: 0;
        }
    .inline dt {
        clear: left;
        float: left;
        }
        .inline dd {
            margin-left: 0;
            }

/* useful for and shown by JS */
.jsblock, .jsinline {
    display: none;
    }

/* add to floating elements which shall clear floating after themselves */
* html .clearfix {
    height: 1%; /* IE5-6 */
    }
*+html .clearfix {
    display: inline-block; /* IE7not8 */
    }
.clearfix:after { /* FF, IE8, O, S, etc. */
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
    }
    }
    '''
    list(t.tokenize(css))

#    c = {}
#    for x in t.tokenize(css):
#        n = x[0]
#        try:
#            c[n] += 1
#        except KeyError:
#            c[n] = 1
#    print c
    """
    t = cssutils.tokenize2.Tokenizer()


    t = timeit.Timer(do)       # outside the try/except
    try:
        print t.timeit(100)    # or t.repeat(...)
    except:
        print t.print_exc()

#    print cssutils.script.csscombine(p,
#                                     resolveVariables=True)
#    cssutils.ser.prefs.resolveVariables = True
#    s = cssutils.parseFile(p)
#    print s.cssRules
#    print s.cssText
    sys.exit(1)


if 1:
    css='''
    a {
        border: red 1px solid;
        border-radius: 1px  2px /   4px;
        border-top-right-radius: 1%;
        border-top-right-radius: 1% 2%;
        behavior: url(css3pie.htc);
        color: rgba(1,2,3, 0.0);
        margin: 1px 2px 3px;
        padding: 1px 2px;
        background: black;
        background-color: #fff;
        content: "string";
    }
    '''
    t = cssutils.tokenize2.Tokenizer()
    for x in t.tokenize(css):
        print x
#
#    v = cssutils.css.URIValue(u'url(/**/1)')
#    print v.cssText
#    v.uri = 'uri'
#    print v.cssText
#    v.value = 'value'
#    print v.cssText

    sys.exit(1)

if 1:
    # request by Walter
    style = cssutils.parseStyle("background-image: url(1.png), url('2.png')")
    cssutils.replaceUrls(style, lambda url: 'prefix/'+url)
    print style.cssText

    sys.exit(1)

if 0:
    # ISSUE 35
    css = """div.one {color: expression((function(ele){ele.style.behavior="none";})(this));}   """
    css = """div.one {color: expression(function(ele){ele.style.behavior="none";})(this);}   """
    sheet = cssutils.parseString(css)
    print sheet.cssText

    sys.exit(1)




if 1:
    css = """
    .content div:after,
.content div .ieafter { content: ""; position: absolute; z-index: -1;
                        left: 0; top: 0; right: -1px; bottom: -9999px;
                        background: inherit; }

/* IE 6/7/8 fixes */
* html .content       { height: 1%; /* IE6 hasLayout */ }
.content div          { -ieafter: expression(this.ieAfter ? 0 : (function(el) {
                        el.ieAfter = document.createElement('span'); el.ieAfter.className = 'ieafter';
                        el.appendChild(el.ieAfter); })(this)); }
.ieafter              { width: expression(parseInt(parentNode.offsetWidth) + 1 + 'px');
                        height: expression(parseInt(parentNode.parentNode.offsetHeight) + 'px');
                        background-color: expression(parentNode.currentStyle.backgroundColor);
                        background-image: expression(parentNode.currentStyle.backgroundImage);
                        background-repeat: expression(parentNode.currentStyle.backgroundRepeat); }
                    """
    s = cssutils.parseString(css)
    print s.cssText
    sys.exit(1)


if 0:
    # Issue 34
    try:
        raise xml.dom.SyntaxErr('msg')
    except Exception, e:
        print e
    sys.exit(1)






if 1:
    def fetcher(url):
        url = url.replace('\\', '/')
        url = url[url.rfind('/')+1:]
        return (None, {
            '3.css': '''
                @variables {
                    over3-2-1-0: 3;
                    over3-2-1: 3;
                    over3-2: 3;
                    over3-2-0: 3;
                    over3-1: 3;
                    over3-1-0: 3;
                    over3-0: 3;
                    local3: 3;
                }

            ''',
            '2.css': '''
                @variables {
                    over3-2-1-0: 2;
                    over3-2-1: 2;
                    over3-2-0: 2;
                    over3-2: 2;
                    over2-1: 2;
                    over2-1-0: 2;
                    over2-0: 2;
                    local2: 2;
                }

            ''',
            '1.css': '''
                @import "3.css";
                @import "2.css";
                @variables {
                    over3-2-1-0: 1;
                    over3-2-1: 1;
                    over3-1: 1;
                    over3-1-0: 1;
                    over2-1: 1;
                    over2-1-0: 1;
                    over1-0: 1;
                    local1: 1;
                }

            '''
            }[url])

    css = '''
        @import "1.css";
        @variables {
            over3-2-1-0: 0;
            over3-2-0: 0;
            over3-1-0: 0;
            over2-1-0: 0;
            over3-0: 0;
            over2-0: 0;
            over1-0: 0;
            local0: 0;
        }
        a {
            local0: var(local0);
            local1: var(local1);
            local2: var(local2);
            local3: var(local3);
            over1-0: var(over1-0);
            over2-0: var(over2-0);
            over3-0: var(over3-0);
            over2-1: var(over2-1);
            over3-1: var(over3-1);
            over3-2: var(over3-2);
            over2-1-0: var(over2-1-0);
            over3-2-0: var(over3-2-0);
            over3-2-1: var(over3-2-1);
            over3-2-1-0: var(over3-2-1-0);
        }
    '''
    cssutils.ser.prefs.resolveVariables = False
    p = cssutils.CSSParser(fetcher=fetcher)
    s = p.parseString(css)
    #print s.cssText
    print
    s = cssutils.resolveImports(s)
    print sorted(s.variables.keys())

    sys.exit(0)



if 1:
    print cssutils.ser.prefs.keepUnkownAtRules
    cssutils.ser.prefs.keepUnkownAtRules = 1
    sys.exit(1)


    def fetcher(url):
        if url == "/1/2.css":
            return None, '''@variables {
                color: red;
            }'''
        else:
            return None, 'a { color: red }'

    parser = cssutils.CSSParser(fetcher=fetcher)
    sheet = parser.parseString('''@import "2.css" tv "title";''',
                               href='/1/')

    print sheet.cssText

    sys.exit(0)

if 1:
    do = """
    import cssutils
    css = '''
    a {
 color: red;
 background: 1px 2px 3px;
 padding: 1px 1px 2px 5cm;
 font: normal 1px/5em Arial, sans-serif;
 color: red;
 background: 1px 2px 3px;
 padding: 1px 1px 2px 5cm;
 font: normal 1px/5em Arial, sans-serif;
 color: red;
 background: 1px 2px 3px;
 padding: 1px 1px 2px 5cm;
 font: normal 1px/5em Arial, sans-serif;
 color: red;
 background: 1px 2px 3px;
 padding: 1px 1px 2px 5cm;
 font: normal 1px/5em Arial, sans-serif;
 }    '''
    cssutils.parseString(css)
    """
    print cssutils.VERSION
    t = timeit.Timer(do)       # outside the try/except
    try:
        print t.timeit(100)    # or t.repeat(...)
    except:
        print t.print_exc()

    sys.exit(0)


if 1:

    def f(url):
        return (None, '/*%s*/' % url)
    p = cssutils.CSSParser(fetcher=f)

    cssrulessheet = p.parseString('@import "x";')
    imp = cssutils.css.CSSImportRule(href="imp.css")
    sheet = p.parseString('@charset "ascii";', href='http://example.com')
    sheet.add(cssrulessheet.cssRules[0])
    added = sheet.cssRules[1]
    print sheet == added.parentStyleSheet
    print 'x' == added.href
    print added.styleSheet.encoding# == u'utf-8'
    print 1, cssrulessheet.cssText
    print 2, added.styleSheet.cssText # == u'/**/'

    sys.exit(0)



if 0:
    css = u'''
    @variables {
      c1: #0f0;
      /*1*/
      c2: red;
      /* TODO @x; */
      a : var(x)
    }
    a {
    color: red}
    '''
    s = cssutils.parseString(css)
    varrule = s.cssRules[0]
    print varrule
    for v in varrule.variables:
        print v, varrule.variables[v]
    print 20*'-'

    v = cssutils.css.CSSVariablesDeclaration(cssText='''
    a: 1px;
    /* 1 */
    c: #f00;
    a: 2px 2px
    ''')
    print v.cssText
    sys.exit(1)

    v.setVariable('a', '1')
    print v.getVariableValue('a')

    print 'a' in v

    v['b'] = 2
    print v['b']

    print v
    print 'keys', v.keys()

    for k in v:
        print k, v[k]
    for i in range(0, v.length):
        print i, v.item(i), v.getVariableValue(v.item(i))

    v.removeVariable('a')
    del v['b']
    print v
    print 'keys', v.keys()

    sys.exit(0)

if 1:
    css = u'''
    @variables {
      c1: #0f0;
      c2: scroll;
    }
    @media all {
        a {
            color: var(c1);
            };
    }
    div.logoContainer {
        color:red;
      color: var(c1);
      color: var(c3);
      background: var(c1) no-repeat var(c2) var(c3);
      }
    '''
    s = cssutils.parseString(css)

    varrule, mediarule, stylerule = s.cssRules

    #cssutils.ser.prefs.resolveVariables = True
    print s.cssText
    #print 20*'-'
    #print cssutils.resolveVariables(s).cssText


    sys.exit(1)

    print
#    p = stylerule.style.getProperty('color')
#    print p
#    print '3', id(p.cssValue), type(p.cssValue), p.cssValue
    print '\n--- RESOLVE var() and remove @variables ---'

    # replace vars (ALL!)
    for p in stylerule.style.getProperties(all=True):
        v = p.cssValue
        #print 1, v.cssValueTypeString, v

        if v.cssValueType == v.CSS_VALUE_LIST:
            newvalue = []
            for vi in v:
                if vi.cssValueType == vi.CSS_VARIABLE:
                    if vi.value:
                        print '+ CSSValueList: Replacing %r with %r' % (p.value,
                                                                        vi.value)
                        newvalue.append(vi.value)
                    else:
                        print '- CSSValueList: No value found for %r' % vi.cssText
                        newvalue.append(vi.cssText)
                else:
                    newvalue.append(vi.cssText)

            p.value = ' '.join(newvalue)

        elif v.cssValueType == v.CSS_VARIABLE:
            if v.value:
                print '+ Replacing %r with %r' % (p.value, v.value)
                p.value = v.value
            else:
                print '- No value found for %r' % p.value


    # remove @variables rules
    for r in s:
        if r.VARIABLES_RULE == r.type:
            s.deleteRule(r)

    #cssutils.ser.prefs.validOnly = True
    print
    print s.cssText

    sys.exit(1)




if 0:
    cssutils.cssproductions.PRODUCTIONS.insert(1,('EXPRESSION',
        r'\(?\s*function\s*\(({ident},?\s*)*\)\s*\{(\s|\S)*\}\s*\)?\((({ident}|\.),?\s*)*\)'))

    css = """
    selector {
x:expression((function(ele){ele.style.behavior=''})(this));
}
    """
    s =  cssutils.parseString(css)
#    p = s.cssRules[0].style.getPropertyCSSValue('x')
#    print p
#    p.cssText = u'expression((function(ele){ele.style.behavior="none";})(this))'

    #p = cssutils.css.CSSPrimitiveValue(u'expression((function(ele){ele.style.behavior="none";})(this))')

    sys.exit(1)


if 1:
    css3 = """
.radius2 {
    border-radius: 3px 6px 8px 10px;
    -moz-border-radius: 3px 6px 8px 10px;
    -webkit-border-radius: 3px 6px 8px 10px;
}
.caption { background: rgba(255, 255, 255, .5); }
.multi-bg {
    background: url(/image/css3-multi-top.png) no-repeat,
    url(/image/css3-multi-bottom.png) no-repeat 0 100%,
    url(/image/css3-multi-repeat.png) repeat-y;
    background-color: #516ac4;
}
.text-shadow {
    text-shadow: 6px 6px 4px #cecece;
    -moz-text-shadow: 6px 6px 4px #cecece;
    -webkit-text-shadow: 6px 6px 4px #cecece;
}
.text-shadow {
    text-shadow: 1px 2px 3px #1a1a1a;
}
.columns {
    -moz-column-count: 3;
    -moz-column-gap: 1em;
    -moz-column-rule: 1px solid black;
    -moz-column-width: 200px;
    -webkit-column-count: 3;
    -webkit-column-gap: 1em;
    -webkit-column-rule: 1px solid black;
    -webkit-column-width: 200px;
}
.border-img {
    background-color: #516ac4;
    border: 10px solid;
    border-image: url(/image/css3-border-img.png) 10 10 10 10 repeat repeat;
    -moz-border-image: url(/image/css3-border-img.png) 10 10 10 10 repeat repeat;
    -webkit-border-image: url(/image/css3-border-img.png) 10 10 10 10 repeat repeat;
}
    """
    print cssutils.parseString(css3).cssText
    sys.exit(0)



if 1:
    import cssutils.sac

    echo = cssutils.sac.EchoHandler()
    p = cssutils.sac.Parser(echo)
    p.parseString('''@charset "ascii";
        /* 1 */
        @import url("x");
        @namespace x "urlx";
        @font-face {
            font-family: Test;
            }
        @page {
            margin: 0;
            }
        @media all {
            a{}
            }
        @x 1;
        html, x>y, .x {left:0;color:red ! /*1*/ important;}''')

    print '\n\n--------------'
    print echo.out

    sys.exit(1)

    sheet =  []
    for t in p.parseString('''
    a, b {
        color: red;
        background: url(/1.png); }'''):
        type_, text, line, col = t
        if 'URI' == type_:
            uri = cssutils.helper.urivalue(text)
            if uri.startswith('/'):
                text = cssutils.helper.uri('..' + uri)

        sheet.append(text)

    print u''.join(sheet)

    sys.exit(1)



if 1:
    s = cssutils.parseString('''a { color: red; top: 0; }''')
    r = s.cssRules[0]
    d = r.style
    print 1, d.color
    d.color = ''
    print 2, d.color
    print s.cssText

    p = d.getProperty('top')
    print 1, p
    p.value = ''
    print 2, p

    sys.exit(0)








if 1:
    css = u"""
    .heading {
          background: #729FCF -moz-linear-gradient(left top, left bottom,
            from(rgba(255, 255, 255, 0.45)), to(rgba(255, 255, 255, 0.50)),
            color-stop(0.4, rgba(255, 255, 255, 0.25)),
            color-stop(0.6, rgba(255, 255, 255, 0.0)),
            color-stop(0.9, rgba(255, 255, 255, 0.10)));
          color: white;
          height: 40px;
        }
    """
    css = u'''
    /* variables and calculations */
    @variables {
      CorporateLogoBGColor: #fe8d12;
      left: 1px;
    }
    div.logoContainer {
      background-color: var(CorporateLogoBGColor);
      /* left: calc(var(left) * 2); */
    }

    /* define declarations to be used in another style declaration
        possible with overriding */
    @define colors {
        color: red;
        background: #fff;
        }
    @define margins {
        top: 1;
        /* left: var(left); */
        }
    a {
        @use colors, margins;
        color: green;
        }

    '''
    s = cssutils.parseString(css)
    print s.cssText
    sys.exit(1)

if 1:
    r = cssutils.parseString(r'''
        @font-face {
            font-family: a;
            src: local(x)
        }
    ''').cssRules[0]
    print r, r.valid
    sys.exit(1)
    for p in st.getProperties():
        print p
#        v = p.cssValue
#        if v.cssValueType == v.CSS_VALUE_LIST:
#            for i, x in enumerate(v):
#                #print i, x
#                #if x.primitiveType == x.CSS_STRING:
#                #    print '\t', 111, x.getStringValue()
#                print
#        print v
    print st.cssText
    print
    sys.exit(1)
    s = cssutils.parseString('''
    @font-face {
        src: local(HiraKakuPro-W3), local(Meiryo), local(IPAPGothic);
        src: local(Gentium), url(/fonts/Gentium.ttf);
        src: local(Futura-Medium),
           url(fonts.svg#MyGeometricModern) format("svg");



        src: url(../fonts/LateefRegAAT.ttf) format("truetype-aat"),
             url(../fonts/LateefRegOT.ttf) format("opentype");

        src: url(a) format( "123x"  , "a"   );
        src: local(x);
        src: url(a);
        src: url(../fonts/LateefRegAAT.ttf) format("truetype-aat");
        src: url(DoulosSILR.ttf) format("opentype","truetype-aat");


        }
        /*src: 'x'*/
    /*a {
        font-weight: bolder;
        }
    @page {
        font-weight: bolder;
        }*/
    ''')
    for r in s:
        if r.type != r.COMMENT:
            for p in r.style.getProperties(all=True):
                print p.valid, p

if 1:
    url = 'http://example.com/test.css'

    def make_fetcher(r):
        # normally r == encoding, content
        def fetcher(url):
            return r
        return fetcher

    sys.exit(0)

def pathname2url(p):
    """OS-specific conversion from a file system path to a relative URL
    of the 'file' scheme; not recommended for general use."""
    # e.g.
    # C:\foo\bar\spam.foo
    # becomes
    # ///C|/foo/bar/spam.foo
    import urllib
    if not ':' in p:
        # No drive specifier, just convert slashes and quote the name
        if p[:2] == '\\\\':
        # path is something like \\host\path\on\remote\host
        # convert this to ////host/path/on/remote/host
        # (notice doubling of slashes at the start of the path)
            p = '\\\\' + p
        components = p.split('\\')
        return urllib.quote('/'.join(components))
    comp = p.split(':')
    if len(comp) != 2 or len(comp[0]) > 1:
        error = 'Bad path: ' + p
        raise IOError, error

    drive = urllib.quote(comp[0].upper())
    components = comp[1].split('\\')
    path = '///' + drive + '|'
    for comp in components:
        if comp:
            path = path + '/' + urllib.quote(comp)
    return path


if 0:
    def jyhref(path):
        href = os.path.abspath(path)
        href = href.replace('\\', '/')
        return 'file:'+href

    name = os.path.join(os.path.dirname(__file__),
                            '..', 'sheets', 'import.css')

    #href = 'file:' + urllib.pathname2url(name)

    from nturl2path import pathname2url
    href = pathname2url(os.path.abspath(name))
    href = href.replace('|', ':')
    href = href[3:]
    href = u'file:' + href

    href = jyhref(name)
    href = None

    print name, href
    s = cssutils.parseFile(name, href=href, media='screen', title='from file')

    print 0, s
    print 1, s.cssRules[0].styleSheet
    print 2, s.cssRules[0].styleSheet.cssText
    sys.exit(0)




if 1:
    import cssutils, pprint
    # remove ALL predefined property profiles
    cssutils.profile.removeProfile(all=True)

    # add your custom profile, {num} is defined in Profile and always available
    macros = {'myvalue': 'a|b|c'}
    props = {'abc': '{myvalue}|{num}', 'color': 'red|blue'}
    cssutils.profile.addProfile('my-profile', props, macros)

    # keep only valid properties (valid in given profile)
    cssutils.ser.prefs.validOnly = True

    print cssutils.parseString('''a {
        color: green;
        color: red;
        abc: 1;
        abc: b;
        abc: 1 a
    }''').cssText

#    import cssutils, pprint
#    print "TOKEN_MACROS"
#    pprint.pprint(cssutils.profile._TOKEN_MACROS)
#    print "MACROS"
#    pprint.pprint(cssutils.profile._MACROS)

    from cssutils.profiles import macros as predef
    from cssutils import profile
    macros = {'my-font': predef[profile.CSS_LEVEL_2]['family-name'],
              'identifier': predef[profile.CSS_LEVEL_2]['identifier']}
    props = {'f': '{my-font}'}
    cssutils.profile.addProfile('my-font-profile', props, macros)
    print cssutils.parseString('''a {
        f: 1; /* 1 is invalid! */
        f: Arial;
    }''').cssText

    sys.exit(0)

if 1:
    from cssutils.script import csscombine
    #a = csscombine(url='http://localhost/css.css', targetencoding='iso-8859-1', minify=False)
    print
    b = csscombine(r"E:\xampp\htdocs\css.css", targetencoding='iso-8859-1', minify=False)
    #print a
    print b

    sys.exit(0)

if 1:
    css = '''@page :left { @top-left {x:1} left: 0; @top-right {x:1} top: 0}'''
    css = '''@page :left { opacity: 0}'''
    s = cssutils.parseString(css)
    style = s.cssRules[0].style
    print s.cssText
    sys.exit(1)



if 1:
    cssutils.log.setLevel(logging.DEBUG)
    css = '''rect(1,2,3)'''
    p = cssutils.css.Property('left', '1.2pc')
    print p


    v = cssutils.css.CSSValue(css)
#
    print v
    print v.cssText

#
    #print v.getRGBColorValue()
    #v.setFloatValue(v.CSS_RGBACOLOR, 1)
    print

    #print v
    #v.setFloatValue(cssutils.css.CSSPrimitiveValue.CSS_KHZ, 2000)
    #print v
#    s = cssutils.parseString('a { left:  inherit; }')
#    print s.cssText
    #cssutils.log.raiseExceptions = False
#    p = cssutils.css.Property(name="color",
#                              value="red",
#                              priority="!important"
#                              )
#    print p
#    print p.cssText
    sys.exit(1)


if 1:
    cssutils.log.setLevel(logging.DEBUG)
    s = cssutils.parseString('')
    print s.cssText
    #v = s.cssRules[0].style.getPropertyCSSValue('color')
    #print v

    sys.exit()

#    from cssutils.profiles import profiles
    # TODO: better API
#    cssutils.css.profiles.profiles.addProfile('x', {
#        'color': '1',
#        'x': '{int}'})
    cssutils.log.setLevel(logging.DEBUG)

    print list(profiles.propertiesByProfile('profiles.CSS3_COLOR'))

    print cssutils.parseString('''
        a { opacity: 0.9;
            color: #000;
            color: rgba(0,0,0, 0);
        }
    ''').cssText

    sys.exit(1)

if 1:
    cssutils.log.setLevel(logging.DEBUG)
    from cssutils.script import csscombine
    c = csscombine('sheets/csscombine-proxy.css')
    print c

    sys.exit(1)


if 0:
    # FETCHER
    def fetchUrlGAE(self):
        """
        uses GoogleAppEngine (GAE)
            fetch(url, payload=None, method=GET, headers={}, allow_truncated=False)

        Response
            content
                The body content of the response.
            content_was_truncated
                True if the allow_truncated parameter to fetch() was True and
                the response exceeded the maximum response size. In this case,
                the content attribute contains the truncated response.
            status_code
                The HTTP status code.
            headers
                The HTTP response headers, as a mapping of names to values.

        Exceptions
            exception InvalidURLError()
                The URL of the request was not a valid URL, or it used an
                unsupported method. Only http and https URLs are supported.
            exception DownloadError()
                There was an error retrieving the data.

                This exception is not raised if the server returns an HTTP
                error code: In that case, the response data comes back intact,
                including the error code.

            exception ResponseTooLargeError()
                The response data exceeded the maximum allowed size, and the
                allow_truncated parameter passed to fetch() was False.
        """
        from google.appengine.api import urlfetch

        try:
            r = urlfetch.fetch(url, method=urlfetch.GET)
        except urlfetch.Error, e:
            cssutils.log.warn(u'Error opening url=%r: %s' % (url, e.message),
                              error=IOError)
        else:
            if r.status_code == 200:
                # find mimetype and encoding
                mimetype = 'application/octet-stream'
                try:
                    mimetype, params = cgi.parse_header(r.headers['content-type'])
                    encoding = params['charset']
                except KeyError:
                    encoding = None

                return encoding, r.content
            else:
                # TODO: 301 etc
                cssutils.log.warn(u'Error opening url=%r: HTTP status %s' %
                                  (url, r.status_code), error=IOError)

    def fetcher(url):
        return 'text/css', 'ascii', '/*test*/'

    p = cssutils.CSSParser()#fetcher=fetcher)
    url = 'http://cdot.local/sheets/import.css'
    x = p.parseUrl(url, encoding='iso-8859-1')
    print
    print 1, x
    print x.cssText[:80]
    print
    x2 = x.cssRules[2].styleSheet
    print 2, x2
    print x2.cssText[:50]

    # ValueError:
#    css = u'a {content: "ä"}'.encode('iso-8859-1')
#    s = cssutils.parseString(css, encoding='iso-8859-1')
#    print s

    # HTTPError
    #_fetchUrl('http://cthedot.de/__UNKNOWN__.css')

    # URLError
    #_fetchUrl('mailto:a.css')
    #_fetchUrl('http://localhost/__UNKNOWN__.css')

    sys.exit(0)


if 0:
    # RESOLVE INDENTATION!!!
    sheet = cssutils.parseString('''
        a,b  { color: red }
        a:hover {color: blue}
        b a { left: 0 }
        c a { color: blue}
        @media all {
            a { color: red;}
            b a { color: blue}
            a:hover { color: blue}
        }
        ''')
    sheet.setSerializerPref('indentSpecificities', True)
    print sheet.cssText

    sys.exit(0)


if 0:
    # SELECTOR4QUERY
    from lxml.cssselect import CSSSelector
#    sl = cssutils.css.SelectorList(selectorText='''
#        :not(a|x) *|* a|* * /*x*/* b>c|c+d[a]~e[a=v].a,
#        a:not(x) p|a[p|a=a],
#        [a="x"][a|=dash][a~=incl][a^=pref][a$=suff][a*=suff]''')
#
#        #*|*, *|e, |e, e, p|*, p|e   ''')
    s = cssutils.css.Selector('*|* |* * *|a |a a')
    print s.selectorText
    ns = [
           {'p': 'URI'},
           {'': 'EMPTY', 'p': 'URI'},
           ]
    for n in ns:
        sl = cssutils.css.SelectorList(selectorText='*|* |* * *|a |a a p|* p|a',
                                       namespaces=n)
        print
        for s in sl:
            print 'ns', n
            print 'Selector.seq:', repr(s.seq)
            print '\t', s.selectorText
            #print  CSSSelector(s.selectorText).path
            print

    sys.exit(0)

if 1:
    # QUERY
    defaultsheet = cssutils.parseFile('sheets/default_html4.css')

    css = '''
        a { a: green; /* only here */
            b: red;
            c: green !important; /* important */
            d: red !important;
            e: red !important;
            x: red;
            x: green; /* later */
            }
        body a {
            b: green; /* specificity */
            c: red;
            d: red;
            e: green !important; /* important */
            }
        a { b: green; /* later */
            c: red;
            d: green !important; /* important */
            e: red;
            }
    '''
    css = '''
        body {
            font: normal 100% sans-serif;
        }
        a {
            font-family: serif;
            c\olor: red;
            font-size: 2em;
        }
        .cssutils {
            font: 1em "Lucida Console", monospace;
            border: 1px solid;
            padding: 0 10px;
        }
    '''
    html = '''<html>
        <body>
            <a href="#1" style="color: green;">link</a>
            <p><a href="#2">coming: <b>b</b>link</a></p>
        </body>
    </html>'''

    from lxml import etree
    from lxml.builder import E
    from lxml.cssselect import CSSSelector

    document = etree.HTML(html)
    e = etree.Element('pre', {'class': 'cssutils'})
    e.text = css
    document.find('body').append(e)

    sheet = cssutils.parseString(css)

    view = {}
    specificities = {} # temporarily needed
    # TODO: filter rules simpler?, add @media
    rules = (rule for rule in sheet.cssRules if rule.type == rule.STYLE_RULE)

    for rule in rules:
        for selector in rule.selectorList:
            cssselector = CSSSelector(selector.selectorText)
            elements = cssselector.evaluate(document)
            for element in elements:
                # add styles for all matching DOM elements
                if element not in view:
                    # add initial
                    view[element] = cssutils.css.CSSStyleDeclaration()
                    specificities[element] = {}

                for p in rule.style:
                    # update styles
                    if p not in view[element]:
                        view[element].setProperty(p)
                        specificities[element][p.name] = selector.specificity
                    else:
                        sameprio = (p.priority ==
                                    view[element].getPropertyPriority(p.name))
                        if not sameprio and bool(p.priority) or (
                           sameprio and selector.specificity >=
                                        specificities[element][p.name]):
                            # later, more specific or higher prio
                            view[element].setProperty(p)
    #pp(view)

    # render somewhat (add @style and text with how it should look
    for element, style in view.items():
        v = style.getCssText(separator=u'')
        element.set('style', v)
        element.set('title', v)


    f = open('c.html', 'w')
    f.write(etree.tostring(document, pretty_print=True))
    f.close()

    sys.exit(0)


if 1:
    #QUERY
    from lxml.cssselect import CSSSelector

    css = '''@namespace p 'test';
    p|a[att~='1'], b>b, c+c, d d { color: red }'''
    sheet = cssutils.parseString(css)
    for s in sheet.cssRules[1].selectorList:
        print s
        print '.prefixes\t', s.prefixes
        print '.selectorText\t', s.selectorText
        # new in beta1: needs to be resolved
        print '._items\t\t', list(s.seq._items)
        sel = CSSSelector(s.selectorText)
        print 'XPath\t\t', sel.path
        print

    sys.exit(0)


if 1:
    # SELECTORS
    s = cssutils.css.SelectorList()
    s.selectorText = 'a,'
    print repr(s.seq)
    print s
    sys.exit(0)

    print 'combinator'
    s.selectorText = 'a + b ~ c > d   \n\r e'
    print s
    s.selectorText = 'a+b~c>d e'
    print s

    print '\n[ type_selector | universal ]'
    s.selectorText = '* |* *|*  *|a b|*'
    print s
    print s.prefixes
    s.selectorText = 'a |b x|c'
    print s
    print s.prefixes

    print '\n[ HASH | class | attrib | pseudo | negation ]*'
    s.selectorText = '#a a#b *#c #d'
    print s
    s.selectorText = '.a a.b *.c .d'
    print s

    print 'attrib'
    s.selectorText = 'a[a|href][x="1"][y=a][x*=a][x|=a]'#':a x ::b y'
    print s

    print 'pseudo'
    s.selectorText = '::a x::b a:first-letter b:first-line c:before d:after'
    print s
    s.selectorText = ':a(+) :b(-) :c(1em) :d(1) :lang("1" 1) :e(a)'
    print s
    s.selectorText = ':a x:a x:a:b'
    print s
    s.selectorText = '::a x::a' # only 1
    print s
    print '\nnot(: type_selector | universal | HASH | class | attrib | pseudo)'
    s.selectorText = 'not(a) not(*|*) not(*) not(#a) not(.b) not([a]) not(:d)'
    print s


    s.selectorText = '*|* * a|b+|c~a|e#1 #a a.a'#'a *~x+b>c'#:not(*)'
    s.selectorText = 'not(*) not(#a) not(.a)'
    print s
    print s.prefixes
    sys.exit(0)