forked from jaraco/cssutils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcssvalue.py
More file actions
1355 lines (1184 loc) · 46.6 KB
/
cssvalue.py
File metadata and controls
1355 lines (1184 loc) · 46.6 KB
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
"""CSSValue related classes
- CSSValue implements DOM Level 2 CSS CSSValue
- CSSPrimitiveValue implements DOM Level 2 CSS CSSPrimitiveValue
- CSSValueList implements DOM Level 2 CSS CSSValueList
"""
__all__ = ['CSSValue', 'CSSPrimitiveValue', 'CSSValueList', 'RGBColor', 'CSSVariable']
import math
import re
import xml.dom
import cssutils
import cssutils.helper
from cssutils.prodparser import Choice, PreDef, Prod, ProdParser, Sequence
class CSSValue(cssutils.util._NewBase):
"""The CSSValue interface represents a simple or a complex value.
A CSSValue object only occurs in a context of a CSS property.
"""
# The value is inherited and the cssText contains "inherit".
CSS_INHERIT = 0
# The value is a CSSPrimitiveValue.
CSS_PRIMITIVE_VALUE = 1
# The value is a CSSValueList.
CSS_VALUE_LIST = 2
# The value is a custom value.
CSS_CUSTOM = 3
# The value is a CSSVariable.
CSS_VARIABLE = 4
_typestrings = {
0: 'CSS_INHERIT',
1: 'CSS_PRIMITIVE_VALUE',
2: 'CSS_VALUE_LIST',
3: 'CSS_CUSTOM',
4: 'CSS_VARIABLE',
}
def __init__(self, cssText=None, parent=None, readonly=False):
"""
:param cssText:
the parsable cssText of the value
:param readonly:
defaults to False
"""
super().__init__()
self._cssValueType = None
self.wellformed = False
self.parent = parent
if cssText is not None: # may be 0
if isinstance(cssText, int):
cssText = str(cssText) # if it is an integer
elif isinstance(cssText, float):
cssText = '%f' % cssText # if it is a floating point number
self.cssText = cssText
self._readonly = readonly
def __repr__(self):
return f"cssutils.css.{self.__class__.__name__}({self.cssText!r})"
def __str__(self):
return (
"<cssutils.css.%s object cssValueTypeString=%r cssText=%r at "
"0x%x>"
% (self.__class__.__name__, self.cssValueTypeString, self.cssText, id(self))
)
def _setCssText(self, cssText): # noqa: C901
"""
Format::
unary_operator
: '-' | '+'
;
operator
: '/' S* | ',' S* | /* empty */
;
expr
: term [ operator term ]*
;
term
: unary_operator?
[ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* |
ANGLE S* | TIME S* | FREQ S* ]
| STRING S* | IDENT S* | URI S* | hexcolor | function
| UNICODE-RANGE S*
;
function
: FUNCTION S* expr ')' S*
;
/*
* There is a constraint on the color that it must
* have either 3 or 6 hex-digits (i.e., [0-9a-fA-F])
* after the "#"; e.g., "#000" is OK, but "#abcd" is not.
*/
hexcolor
: HASH S*
;
:exceptions:
- :exc:`~xml.dom.SyntaxErr`:
Raised if the specified CSS string value has a syntax error
(according to the attached property) or is unparsable.
- :exc:`~xml.dom.InvalidModificationErr`:
TODO: Raised if the specified CSS string value represents a
different type of values than the values allowed by the CSS
property.
- :exc:`~xml.dom.NoModificationAllowedErr`:
Raised if this value is readonly.
"""
self._checkReadonly()
# used as operator is , / or S
nextSor = ',/'
term = Choice(
Sequence(
PreDef.unary(),
Choice(
PreDef.number(nextSor=nextSor),
PreDef.percentage(nextSor=nextSor),
PreDef.dimension(nextSor=nextSor),
),
),
PreDef.string(nextSor=nextSor),
PreDef.ident(nextSor=nextSor),
PreDef.uri(nextSor=nextSor),
PreDef.hexcolor(nextSor=nextSor),
PreDef.unicode_range(nextSor=nextSor),
# special case IE only expression
Prod(
name='expression',
match=lambda t, v: t == self._prods.FUNCTION
and (
cssutils.helper.normalize(v)
in (
'expression(',
'alpha(',
'blur(',
'chroma(',
'dropshadow(',
'fliph(',
'flipv(',
'glow(',
'gray(',
'invert(',
'mask(',
'shadow(',
'wave(',
'xray(',
)
or v.startswith('progid:DXImageTransform.Microsoft.')
),
nextSor=nextSor,
toSeq=lambda t, tokens: (
ExpressionValue._functionName,
ExpressionValue(cssutils.helper.pushtoken(t, tokens), parent=self),
),
),
# CSS Variable var(
PreDef.variable(
nextSor=nextSor,
toSeq=lambda t, tokens: (
'CSSVariable',
CSSVariable(cssutils.helper.pushtoken(t, tokens), parent=self),
),
),
# calc(
PreDef.calc(
nextSor=nextSor,
toSeq=lambda t, tokens: (
CalcValue._functionName,
CalcValue(cssutils.helper.pushtoken(t, tokens), parent=self),
),
),
# TODO:
# # rgb/rgba(
# Prod(name='RGBColor',
# match=lambda t, v: t == self._prods.FUNCTION and (
# cssutils.helper.normalize(v) in (u'rgb(',
# u'rgba('
# )
# ),
# nextSor=nextSor,
# toSeq=lambda t, tokens: (RGBColor._functionName,
# RGBColor(
# cssutils.helper.pushtoken(t, tokens),
# parent=self)
# )
# ),
# other functions like rgb( etc
PreDef.function(
nextSor=nextSor,
toSeq=lambda t, tokens: (
'FUNCTION',
CSSFunction(cssutils.helper.pushtoken(t, tokens), parent=self),
),
),
)
operator = Choice(
PreDef.S(),
PreDef.char('comma', ',', toSeq=lambda t, tokens: ('operator', t[1])),
PreDef.char('slash', '/', toSeq=lambda t, tokens: ('operator', t[1])),
optional=True,
)
# CSSValue PRODUCTIONS
valueprods = Sequence(
term,
Sequence(
operator, # mayEnd this Sequence if whitespace
# TODO: only when setting via other class
# used by variabledeclaration currently
PreDef.char('END', ';', stopAndKeep=True, optional=True),
term,
minmax=lambda: (0, None),
),
)
# parse
wellformed, seq, store, notused = ProdParser().parse(
cssText, 'CSSValue', valueprods, keepS=True
)
if wellformed:
# - count actual values and set firstvalue which is used later on
# - combine comma separated list, e.g. font-family to a single item
# - remove S which should be an operator but is no needed
count, firstvalue = 0, ()
newseq = self._tempSeq()
i, end = 0, len(seq)
while i < end:
item = seq[i]
if item.type == self._prods.S:
pass
elif (item.value, item.type) == (',', 'operator'):
# , separared counts as a single STRING for now
# URI or STRING value might be a single CHAR too!
newseq.appendItem(item)
count -= 1
if firstvalue:
# list of IDENTs is handled as STRING!
if firstvalue[1] == self._prods.IDENT:
firstvalue = firstvalue[0], 'STRING'
elif item.value == '/':
# / separated items count as one
newseq.appendItem(item)
elif item.value == '-' or item.value == '+':
# combine +- and following number or other
i += 1
try:
next = seq[i]
except IndexError:
firstvalue = () # raised later
break
newval = item.value + next.value
newseq.append(newval, next.type, item.line, item.col)
if not firstvalue:
firstvalue = (newval, next.type)
count += 1
elif item.type != cssutils.css.CSSComment:
newseq.appendItem(item)
if not firstvalue:
firstvalue = (item.value, item.type)
count += 1
else:
newseq.appendItem(item)
i += 1
if not firstvalue:
self._log.error(
'CSSValue: Unknown syntax or no value: %r.'
% self._valuestr(cssText)
)
else:
# ok and set
self._setSeq(newseq)
self.wellformed = wellformed
if hasattr(self, '_value'):
# only in case of CSSPrimitiveValue, else remove!
del self._value
if count == 1:
# inherit, primitive or variable
if isinstance(
firstvalue[0], str
) and 'inherit' == cssutils.helper.normalize(firstvalue[0]):
self.__class__ = CSSValue
self._cssValueType = CSSValue.CSS_INHERIT
elif 'CSSVariable' == firstvalue[1]:
self.__class__ = CSSVariable
self._value = firstvalue
# TODO: remove major hack!
self._name = firstvalue[0]._name
else:
self.__class__ = CSSPrimitiveValue
self._value = firstvalue
elif count > 1:
# valuelist
self.__class__ = CSSValueList
# change items in list to specific type (primitive etc)
newseq = self._tempSeq()
commalist = []
nexttocommalist = False
def itemValue(item):
"Reserialized simple item.value"
if self._prods.STRING == item.type:
return cssutils.helper.string(item.value)
elif self._prods.URI == item.type:
return cssutils.helper.uri(item.value)
elif (
self._prods.FUNCTION == item.type
or 'CSSVariable' == item.type
):
return item.value.cssText
else:
return item.value
def saveifcommalist(commalist, newseq):
"""
saves items in commalist to seq and items
if anything in there
"""
if commalist:
newseq.replace(
-1,
CSSPrimitiveValue(cssText=''.join(commalist)),
CSSPrimitiveValue,
newseq[-1].line,
newseq[-1].col,
)
del commalist[:]
for i, item in enumerate(self._seq):
if issubclass(type(item.value), CSSValue):
# set parent of CSSValueList items to the lists
# parent
item.value.parent = self.parent
if item.type in (
self._prods.DIMENSION,
self._prods.FUNCTION,
self._prods.HASH,
self._prods.IDENT,
self._prods.NUMBER,
self._prods.PERCENTAGE,
self._prods.STRING,
self._prods.URI,
self._prods.UNICODE_RANGE,
'CSSVariable',
):
if nexttocommalist:
# wait until complete
commalist.append(itemValue(item))
else:
saveifcommalist(commalist, newseq)
# append new item
if hasattr(item.value, 'cssText'):
newseq.append(
item.value,
item.value.__class__,
item.line,
item.col,
)
else:
newseq.append(
CSSPrimitiveValue(itemValue(item)),
CSSPrimitiveValue,
item.line,
item.col,
)
nexttocommalist = False
elif ',' == item.value:
if not commalist:
# save last item to commalist
commalist.append(itemValue(self._seq[i - 1]))
commalist.append(',')
nexttocommalist = True
else:
if nexttocommalist:
commalist.append(item.value.cssText)
else:
newseq.appendItem(item)
saveifcommalist(commalist, newseq)
self._setSeq(newseq)
else:
# should not happen...
self.__class__ = CSSValue
self._cssValueType = CSSValue.CSS_CUSTOM
cssText = property(
lambda self: cssutils.ser.do_css_CSSValue(self),
_setCssText,
doc="A string representation of the current value.",
)
cssValueType = property(
lambda self: self._cssValueType,
doc="A (readonly) code defining the type of the value.",
)
cssValueTypeString = property(
lambda self: CSSValue._typestrings.get(self.cssValueType, None),
doc="(readonly) Name of cssValueType.",
)
class CSSPrimitiveValue(CSSValue):
"""Represents a single CSS Value. May be used to determine the value of a
specific style property currently set in a block or to set a specific
style property explicitly within the block. Might be obtained from the
getPropertyCSSValue method of CSSStyleDeclaration.
Conversions are allowed between absolute values (from millimeters to
centimeters, from degrees to radians, and so on) but not between
relative values. (For example, a pixel value cannot be converted to a
centimeter value.) Percentage values can't be converted since they are
relative to the parent value (or another property value). There is one
exception for color percentage values: since a color percentage value
is relative to the range 0-255, a color percentage value can be
converted to a number; (see also the RGBColor interface).
"""
# constant: type of this CSSValue class
cssValueType = CSSValue.CSS_PRIMITIVE_VALUE
__types = cssutils.cssproductions.CSSProductions
# An integer indicating which type of unit applies to the value.
CSS_UNKNOWN = 0 # only obtainable via cssText
CSS_NUMBER = 1
CSS_PERCENTAGE = 2
CSS_EMS = 3
CSS_EXS = 4
CSS_PX = 5
CSS_CM = 6
CSS_MM = 7
CSS_IN = 8
CSS_PT = 9
CSS_PC = 10
CSS_DEG = 11
CSS_RAD = 12
CSS_GRAD = 13
CSS_MS = 14
CSS_S = 15
CSS_HZ = 16
CSS_KHZ = 17
CSS_DIMENSION = 18
CSS_STRING = 19
CSS_URI = 20
CSS_IDENT = 21
CSS_ATTR = 22
CSS_COUNTER = 23
CSS_RECT = 24
CSS_RGBCOLOR = 25
# NOT OFFICIAL:
CSS_RGBACOLOR = 26
CSS_UNICODE_RANGE = 27
_floattypes = (
CSS_NUMBER,
CSS_PERCENTAGE,
CSS_EMS,
CSS_EXS,
CSS_PX,
CSS_CM,
CSS_MM,
CSS_IN,
CSS_PT,
CSS_PC,
CSS_DEG,
CSS_RAD,
CSS_GRAD,
CSS_MS,
CSS_S,
CSS_HZ,
CSS_KHZ,
CSS_DIMENSION,
)
_stringtypes = (CSS_ATTR, CSS_IDENT, CSS_STRING, CSS_URI)
_countertypes = (CSS_COUNTER,)
_recttypes = (CSS_RECT,)
_rbgtypes = (CSS_RGBCOLOR, CSS_RGBACOLOR)
_lengthtypes = (
CSS_NUMBER,
CSS_EMS,
CSS_EXS,
CSS_PX,
CSS_CM,
CSS_MM,
CSS_IN,
CSS_PT,
CSS_PC,
)
# oldtype: newType: converterfunc
_converter = {
# cm <-> mm <-> in, 1 inch is equal to 2.54 centimeters.
# pt <-> pc, the points used by CSS 2.1 are equal to 1/72nd of an inch.
# pc: picas - 1 pica is equal to 12 points
(CSS_CM, CSS_MM): lambda x: x * 10,
(CSS_MM, CSS_CM): lambda x: x / 10,
(CSS_PT, CSS_PC): lambda x: x * 12,
(CSS_PC, CSS_PT): lambda x: x / 12,
(CSS_CM, CSS_IN): lambda x: x / 2.54,
(CSS_IN, CSS_CM): lambda x: x * 2.54,
(CSS_MM, CSS_IN): lambda x: x / 25.4,
(CSS_IN, CSS_MM): lambda x: x * 25.4,
(CSS_IN, CSS_PT): lambda x: x / 72,
(CSS_PT, CSS_IN): lambda x: x * 72,
(CSS_CM, CSS_PT): lambda x: x / 2.54 / 72,
(CSS_PT, CSS_CM): lambda x: x * 72 * 2.54,
(CSS_MM, CSS_PT): lambda x: x / 25.4 / 72,
(CSS_PT, CSS_MM): lambda x: x * 72 * 25.4,
(CSS_IN, CSS_PC): lambda x: x / 72 / 12,
(CSS_PC, CSS_IN): lambda x: x * 12 * 72,
(CSS_CM, CSS_PC): lambda x: x / 2.54 / 72 / 12,
(CSS_PC, CSS_CM): lambda x: x * 12 * 72 * 2.54,
(CSS_MM, CSS_PC): lambda x: x / 25.4 / 72 / 12,
(CSS_PC, CSS_MM): lambda x: x * 12 * 72 * 25.4,
# hz <-> khz
(CSS_KHZ, CSS_HZ): lambda x: x * 1000,
(CSS_HZ, CSS_KHZ): lambda x: x / 1000,
# s <-> ms
(CSS_S, CSS_MS): lambda x: x * 1000,
(CSS_MS, CSS_S): lambda x: x / 1000,
(CSS_RAD, CSS_DEG): lambda x: math.degrees(x),
(CSS_DEG, CSS_RAD): lambda x: math.radians(x),
# TODO: convert grad <-> deg or rad
# (CSS_RAD, CSS_GRAD): lambda x: math.degrees(x),
# (CSS_DEG, CSS_GRAD): lambda x: math.radians(x),
# (CSS_GRAD, CSS_RAD): lambda x: math.radians(x),
# (CSS_GRAD, CSS_DEG): lambda x: math.radians(x)
}
def __init__(self, cssText=None, parent=None, readonly=False):
"""See CSSPrimitiveValue.__init__()"""
super().__init__(cssText=cssText, parent=parent, readonly=readonly)
def __str__(self):
return f"<cssutils.css.{self.__class__.__name__} object primitiveType={self.primitiveTypeString} cssText={self.cssText!r} at 0x{id(self):x}>"
_unitnames = [
'CSS_UNKNOWN',
'CSS_NUMBER',
'CSS_PERCENTAGE',
'CSS_EMS',
'CSS_EXS',
'CSS_PX',
'CSS_CM',
'CSS_MM',
'CSS_IN',
'CSS_PT',
'CSS_PC',
'CSS_DEG',
'CSS_RAD',
'CSS_GRAD',
'CSS_MS',
'CSS_S',
'CSS_HZ',
'CSS_KHZ',
'CSS_DIMENSION',
'CSS_STRING',
'CSS_URI',
'CSS_IDENT',
'CSS_ATTR',
'CSS_COUNTER',
'CSS_RECT',
'CSS_RGBCOLOR',
'CSS_RGBACOLOR',
'CSS_UNICODE_RANGE',
]
_reNumDim = re.compile(r'([+-]?\d*\.\d+|[+-]?\d+)(.*)$', re.I | re.U | re.X)
def _unitDIMENSION(value):
"""Check val for dimension name."""
units = {
'em': 'CSS_EMS',
'ex': 'CSS_EXS',
'px': 'CSS_PX',
'cm': 'CSS_CM',
'mm': 'CSS_MM',
'in': 'CSS_IN',
'pt': 'CSS_PT',
'pc': 'CSS_PC',
'deg': 'CSS_DEG',
'rad': 'CSS_RAD',
'grad': 'CSS_GRAD',
'ms': 'CSS_MS',
's': 'CSS_S',
'hz': 'CSS_HZ',
'khz': 'CSS_KHZ',
}
val, dim = CSSPrimitiveValue._reNumDim.findall(
cssutils.helper.normalize(value)
)[0]
return units.get(dim, 'CSS_DIMENSION')
def _unitFUNCTION(value):
"""Check val for function name."""
units = {
'attr(': 'CSS_ATTR',
'counter(': 'CSS_COUNTER',
'rect(': 'CSS_RECT',
'rgb(': 'CSS_RGBCOLOR',
'rgba(': 'CSS_RGBACOLOR',
}
return units.get(
re.findall(r'^(.*?\()', cssutils.helper.normalize(value.cssText), re.U)[0],
'CSS_UNKNOWN',
)
__unitbytype = {
__types.NUMBER: 'CSS_NUMBER',
__types.PERCENTAGE: 'CSS_PERCENTAGE',
__types.STRING: 'CSS_STRING',
__types.UNICODE_RANGE: 'CSS_UNICODE_RANGE',
__types.URI: 'CSS_URI',
__types.IDENT: 'CSS_IDENT',
__types.HASH: 'CSS_RGBCOLOR',
__types.DIMENSION: _unitDIMENSION,
__types.FUNCTION: _unitFUNCTION,
}
def __set_primitiveType(self):
"""primitiveType is readonly but is set lazy if accessed"""
# TODO: check unary and font-family STRING a, b, "c"
val, type_ = self._value
# try get by type_
pt = self.__unitbytype.get(type_, 'CSS_UNKNOWN')
if callable(pt):
# multiple options, check value too
pt = pt(val)
self._primitiveType = getattr(self, pt)
def _getPrimitiveType(self):
if not hasattr(self, '_primitivetype'):
self.__set_primitiveType()
return self._primitiveType
primitiveType = property(
_getPrimitiveType,
doc="(readonly) The type of the value as defined "
"by the constants in this class.",
)
def _getPrimitiveTypeString(self):
return self._unitnames[self.primitiveType]
primitiveTypeString = property(
_getPrimitiveTypeString, doc="Name of primitive type of this value."
)
def _getCSSPrimitiveTypeString(self, type):
"get TypeString by given type which may be unknown, used by setters"
try:
return self._unitnames[type]
except (IndexError, TypeError):
return '%r (UNKNOWN TYPE)' % type
def _getNumDim(self, value=None):
"Split self._value in numerical and dimension part."
if value is None:
value = cssutils.helper.normalize(self._value[0])
try:
val, dim = CSSPrimitiveValue._reNumDim.findall(value)[0]
except IndexError:
val, dim = value, ''
try:
val = float(val)
if val == int(val):
val = int(val)
except ValueError as err:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue: No float value %r' % self._value[0]
) from err
return val, dim
def getFloatValue(self, unitType=None):
"""(DOM) This method is used to get a float value in a
specified unit. If this CSS value doesn't contain a float value
or can't be converted into the specified unit, a DOMException
is raised.
:param unitType:
to get the float value. The unit code can only be a float unit type
(i.e. CSS_NUMBER, CSS_PERCENTAGE, CSS_EMS, CSS_EXS, CSS_PX, CSS_CM,
CSS_MM, CSS_IN, CSS_PT, CSS_PC, CSS_DEG, CSS_RAD, CSS_GRAD, CSS_MS,
CSS_S, CSS_HZ, CSS_KHZ, CSS_DIMENSION) or None in which case
the current dimension is used.
:returns:
not necessarily a float but some cases just an integer
e.g. if the value is ``1px`` it return ``1`` and **not** ``1.0``
Conversions might return strange values like 1.000000000001
"""
if unitType is not None and unitType not in self._floattypes:
raise xml.dom.InvalidAccessErr('unitType Parameter is not a float type')
val, dim = self._getNumDim()
if unitType is not None and self.primitiveType != unitType:
# convert if needed
try:
val = self._converter[self.primitiveType, unitType](val)
except KeyError as err:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue: Cannot coerce primitiveType %r to %r'
% (
self.primitiveTypeString,
self._getCSSPrimitiveTypeString(unitType),
)
) from err
if val == int(val):
val = int(val)
return val
def setFloatValue(self, unitType, floatValue):
"""(DOM) A method to set the float value with a specified unit.
If the property attached with this value can not accept the
specified unit or the float value, the value will be unchanged and
a DOMException will be raised.
:param unitType:
a unit code as defined above. The unit code can only be a float
unit type
:param floatValue:
the new float value which does not have to be a float value but
may simple be an int e.g. if setting::
setFloatValue(CSS_PX, 1)
:exceptions:
- :exc:`~xml.dom.InvalidAccessErr`:
Raised if the attached property doesn't
support the float value or the unit type.
- :exc:`~xml.dom.NoModificationAllowedErr`:
Raised if this property is readonly.
"""
self._checkReadonly()
if unitType not in self._floattypes:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue: unitType %r is not a float type'
% self._getCSSPrimitiveTypeString(unitType)
)
try:
val = float(floatValue)
except ValueError as err:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue: floatValue %r is not a float' % floatValue
) from err
oldval, dim = self._getNumDim()
if self.primitiveType != unitType:
# convert if possible
try:
val = self._converter[unitType, self.primitiveType](val)
except KeyError as err:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue: Cannot coerce primitiveType %r to %r'
% (
self.primitiveTypeString,
self._getCSSPrimitiveTypeString(unitType),
)
) from err
if val == int(val):
val = int(val)
self.cssText = f'{val}{dim}'
def getStringValue(self):
"""(DOM) This method is used to get the string value. If the
CSS value doesn't contain a string value, a DOMException is raised.
Some properties (like 'font-family' or 'voice-family')
convert a whitespace separated list of idents to a string.
Only the actual value is returned so e.g. all the following return the
actual value ``a``: url(a), attr(a), "a", 'a'
"""
if self.primitiveType not in self._stringtypes:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue %r is not a string type' % self.primitiveTypeString
)
if CSSPrimitiveValue.CSS_ATTR == self.primitiveType:
return self._value[0].cssText[5:-1]
else:
return self._value[0]
def setStringValue(self, stringType, stringValue):
"""(DOM) A method to set the string value with the specified
unit. If the property attached to this value can't accept the
specified unit or the string value, the value will be unchanged and
a DOMException will be raised.
:param stringType:
a string code as defined above. The string code can only be a
string unit type (i.e. CSS_STRING, CSS_URI, CSS_IDENT, and
CSS_ATTR).
:param stringValue:
the new string value
Only the actual value is expected so for (CSS_URI, "a") the
new value will be ``url(a)``. For (CSS_STRING, "'a'")
the new value will be ``"\\'a\\'"`` as the surrounding ``'`` are
not part of the string value
:exceptions:
- :exc:`~xml.dom.InvalidAccessErr`:
Raised if the CSS value doesn't contain a
string value or if the string value can't be converted into
the specified unit.
- :exc:`~xml.dom.NoModificationAllowedErr`:
Raised if this property is readonly.
"""
self._checkReadonly()
# self not stringType
if self.primitiveType not in self._stringtypes:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue %r is not a string type' % self.primitiveTypeString
)
# given stringType is no StringType
if stringType not in self._stringtypes:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue: stringType %s is not a string type'
% self._getCSSPrimitiveTypeString(stringType)
)
if self._primitiveType != stringType:
raise xml.dom.InvalidAccessErr(
'CSSPrimitiveValue: Cannot coerce primitiveType %r to %r'
% (
self.primitiveTypeString,
self._getCSSPrimitiveTypeString(stringType),
)
)
if CSSPrimitiveValue.CSS_STRING == self._primitiveType:
self.cssText = cssutils.helper.string(stringValue)
elif CSSPrimitiveValue.CSS_URI == self._primitiveType:
self.cssText = cssutils.helper.uri(stringValue)
elif CSSPrimitiveValue.CSS_ATTR == self._primitiveType:
self.cssText = 'attr(%s)' % stringValue
else:
self.cssText = stringValue
self._primitiveType = stringType
def getCounterValue(self):
"""(DOM) This method is used to get the Counter value. If
this CSS value doesn't contain a counter value, a DOMException
is raised. Modification to the corresponding style property
can be achieved using the Counter interface.
**Not implemented.**
"""
if not self.CSS_COUNTER == self.primitiveType:
raise xml.dom.InvalidAccessErr('Value is not a counter type')
# TODO: use Counter class
raise NotImplementedError()
def getRGBColorValue(self):
"""(DOM) This method is used to get the RGB color. If this
CSS value doesn't contain a RGB color value, a DOMException
is raised. Modification to the corresponding style property
can be achieved using the RGBColor interface.
"""
if self.primitiveType not in self._rbgtypes:
raise xml.dom.InvalidAccessErr('Value is not a RGBColor value')
return RGBColor(self._value[0])
def getRectValue(self):
"""(DOM) This method is used to get the Rect value. If this CSS
value doesn't contain a rect value, a DOMException is raised.
Modification to the corresponding style property can be achieved
using the Rect interface.
**Not implemented.**
"""
if self.primitiveType not in self._recttypes:
raise xml.dom.InvalidAccessErr('value is not a Rect value')
# TODO: use Rect class
raise NotImplementedError()
def _getCssText(self):
"""Overwrites CSSValue."""
return cssutils.ser.do_css_CSSPrimitiveValue(self)
def _setCssText(self, cssText):
"""Use CSSValue."""
return super()._setCssText(cssText)
cssText = property(
_getCssText, _setCssText, doc="A string representation of the current value."
)
class CSSValueList(CSSValue):
"""The CSSValueList interface provides the abstraction of an ordered
collection of CSS values.
Some properties allow an empty list into their syntax. In that case,
these properties take the none identifier. So, an empty list means
that the property has the value none.
The items in the CSSValueList are accessible via an integral index,
starting from 0.
"""
cssValueType = CSSValue.CSS_VALUE_LIST
def __init__(self, cssText=None, parent=None, readonly=False):
"""Init a new CSSValueList"""
super().__init__(cssText=cssText, parent=parent, readonly=readonly)
self._items = []
def __iter__(self):
"CSSValueList is iterable."
for item in self.__items():
yield item.value
def __str__(self):
return (
"<cssutils.css.%s object cssValueType=%r cssText=%r length=%r "
"at 0x%x>"
% (
self.__class__.__name__,
self.cssValueTypeString,
self.cssText,
self.length,
id(self),
)
)
def __items(self):
return [item for item in self._seq if isinstance(item.value, CSSValue)]
def item(self, index):
"""(DOM) Retrieve a CSSValue by ordinal `index`. The
order in this collection represents the order of the values in the
CSS style property. If `index` is greater than or equal to the number
of values in the list, this returns ``None``.
"""
try:
return self.__items()[index].value
except IndexError:
return None
length = property(
lambda self: len(self.__items()),
doc="(DOM attribute) The number of CSSValues in the " "list.",
)
class CSSFunction(CSSPrimitiveValue):
"""A CSS function value like rect() etc."""
_functionName = 'CSSFunction'
primitiveType = CSSPrimitiveValue.CSS_UNKNOWN
def __init__(self, cssText=None, parent=None, readonly=False):
"""
Init a new CSSFunction
:param cssText:
the parsable cssText of the value
:param readonly:
defaults to False
"""
super().__init__(parent=parent)
self._funcType = None