forked from scanny/python-pptx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpletypes.py
More file actions
740 lines (546 loc) · 19.3 KB
/
simpletypes.py
File metadata and controls
740 lines (546 loc) · 19.3 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
"""Simple-type classes.
A "simple-type" is a scalar type, generally serving as an XML attribute. This is in contrast to a
"complex-type" which would specify an XML element.
These objects providing validation and format translation for values stored in XML element
attributes. Naming generally corresponds to the simple type in the associated XML schema.
"""
from __future__ import annotations
import numbers
from typing import Any
from pptx.exc import InvalidXmlError
from pptx.util import Centipoints, Emu
class BaseSimpleType:
@classmethod
def from_xml(cls, xml_value: str) -> Any:
return cls.convert_from_xml(xml_value)
@classmethod
def to_xml(cls, value: Any) -> str:
cls.validate(value)
str_value = cls.convert_to_xml(value)
return str_value
@classmethod
def validate_float(cls, value: Any):
"""Note that int values are accepted."""
if not isinstance(value, (int, float)):
raise TypeError("value must be a number, got %s" % type(value))
@classmethod
def validate_int(cls, value):
if not isinstance(value, numbers.Integral):
raise TypeError("value must be an integral type, got %s" % type(value))
@classmethod
def validate_float_in_range(cls, value, min_inclusive, max_inclusive):
cls.validate_float(value)
if value < min_inclusive or value > max_inclusive:
raise ValueError(
"value must be in range %s to %s inclusive, got %s"
% (min_inclusive, max_inclusive, value)
)
@classmethod
def validate_int_in_range(cls, value, min_inclusive, max_inclusive):
cls.validate_int(value)
if value < min_inclusive or value > max_inclusive:
raise ValueError(
"value must be in range %d to %d inclusive, got %d"
% (min_inclusive, max_inclusive, value)
)
@classmethod
def validate_string(cls, value):
if isinstance(value, str):
return value
try:
if isinstance(value, basestring):
return value
except NameError: # means we're on Python 3
pass
raise TypeError("value must be a string, got %s" % type(value))
class BaseFloatType(BaseSimpleType):
@classmethod
def convert_from_xml(cls, str_value):
return float(str_value)
@classmethod
def convert_to_xml(cls, value):
return str(float(value))
@classmethod
def validate(cls, value):
if not isinstance(value, (int, float)):
raise TypeError("value must be a number, got %s" % type(value))
class BaseIntType(BaseSimpleType):
@classmethod
def convert_from_percent_literal(cls, str_value):
int_str = str_value.replace("%", "")
return int(int_str)
@classmethod
def convert_from_xml(cls, str_value):
return int(str_value)
@classmethod
def convert_to_xml(cls, value):
return str(value)
@classmethod
def validate(cls, value):
cls.validate_int(value)
class BaseStringType(BaseSimpleType):
@classmethod
def convert_from_xml(cls, str_value):
return str_value
@classmethod
def convert_to_xml(cls, value):
return value
@classmethod
def validate(cls, value):
cls.validate_string(value)
class BaseStringEnumerationType(BaseStringType):
@classmethod
def validate(cls, value):
cls.validate_string(value)
if value not in cls._members:
raise ValueError("must be one of %s, got '%s'" % (cls._members, value))
class XsdAnyUri(BaseStringType):
"""
There's a regular expression this is supposed to meet but so far thinking
spending cycles on validating wouldn't be worth it for the number of
programming errors it would catch.
"""
class XsdBoolean(BaseSimpleType):
@classmethod
def convert_from_xml(cls, str_value):
if str_value not in ("1", "0", "true", "false"):
raise InvalidXmlError(
"value must be one of '1', '0', 'true' or 'false', got '%s'" % str_value
)
return str_value in ("1", "true")
@classmethod
def convert_to_xml(cls, value):
return {True: "1", False: "0"}[value]
@classmethod
def validate(cls, value):
if value not in (True, False):
raise TypeError(
"only True or False (and possibly None) may be assigned, got" " '%s'" % value
)
class XsdDouble(BaseFloatType):
pass
class XsdId(BaseStringType):
"""
String that must begin with a letter or underscore and cannot contain any
colons. Not fully validated because not used in external API.
"""
class XsdInt(BaseIntType):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, -2147483648, 2147483647)
class XsdLong(BaseIntType):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, -9223372036854775808, 9223372036854775807)
class XsdString(BaseStringType):
pass
class XsdStringEnumeration(BaseStringEnumerationType):
"""
Set of enumerated xsd:string values.
"""
class XsdToken(BaseStringType):
"""
xsd:string with whitespace collapsing, e.g. multiple spaces reduced to
one, leading and trailing space stripped.
"""
class XsdTokenEnumeration(BaseStringEnumerationType):
"""
xsd:string with whitespace collapsing, e.g. multiple spaces reduced to
one, leading and trailing space stripped.
"""
class XsdUnsignedByte(BaseIntType):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 255)
class XsdUnsignedInt(BaseIntType):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 4294967295)
class XsdUnsignedShort(BaseIntType):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 65535)
class ST_Angle(XsdInt):
"""
Valid values for `rot` attribute on `<a:xfrm>` element. 60000ths of
a degree rotation.
"""
DEGREE_INCREMENTS = 60000
THREE_SIXTY = 360 * DEGREE_INCREMENTS
@classmethod
def convert_from_xml(cls, str_value: str) -> float:
rot = int(str_value) % cls.THREE_SIXTY
return float(rot) / cls.DEGREE_INCREMENTS
@classmethod
def convert_to_xml(cls, value):
"""
Convert signed angle float like -42.42 to int 60000 per degree,
normalized to positive value.
"""
# modulo normalizes negative and >360 degree values
rot = int(round(value * cls.DEGREE_INCREMENTS)) % cls.THREE_SIXTY
return str(rot)
@classmethod
def validate(cls, value):
BaseFloatType.validate(value)
class ST_AxisUnit(XsdDouble):
"""
Valid values for val attribute on c:majorUnit and others.
"""
@classmethod
def validate(cls, value):
super(ST_AxisUnit, cls).validate(value)
if value <= 0.0:
raise ValueError("must be positive numeric value, got %s" % value)
class ST_BarDir(XsdStringEnumeration):
"""
Valid values for <c:barDir val="?"> attribute
"""
BAR = "bar"
COL = "col"
_members = (BAR, COL)
class ST_BubbleScale(BaseIntType):
"""
String value is an integer in range 0-300, representing a percent,
optionally including a '%' suffix.
"""
@classmethod
def convert_from_xml(cls, str_value):
if "%" in str_value:
return cls.convert_from_percent_literal(str_value)
return super(ST_BubbleScale, cls).convert_from_xml(str_value)
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 300)
class ST_ContentType(XsdString):
"""
Has a pretty wicked regular expression it needs to match in the schema,
but figuring it's not worth the trouble or run time to identify
a programming error (as opposed to a user/runtime error).
"""
pass
class ST_Coordinate(BaseSimpleType):
@classmethod
def convert_from_xml(cls, str_value):
if "i" in str_value or "m" in str_value or "p" in str_value:
return ST_UniversalMeasure.convert_from_xml(str_value)
return Emu(int(str_value))
@classmethod
def convert_to_xml(cls, value):
return str(value)
@classmethod
def validate(cls, value):
ST_CoordinateUnqualified.validate(value)
class ST_Coordinate32(BaseSimpleType):
"""
xsd:union of ST_Coordinate32Unqualified, ST_UniversalMeasure
"""
@classmethod
def convert_from_xml(cls, str_value):
if "i" in str_value or "m" in str_value or "p" in str_value:
return ST_UniversalMeasure.convert_from_xml(str_value)
return ST_Coordinate32Unqualified.convert_from_xml(str_value)
@classmethod
def convert_to_xml(cls, value):
return ST_Coordinate32Unqualified.convert_to_xml(value)
@classmethod
def validate(cls, value):
ST_Coordinate32Unqualified.validate(value)
class ST_Coordinate32Unqualified(XsdInt):
@classmethod
def convert_from_xml(cls, str_value):
return Emu(int(str_value))
class ST_CoordinateUnqualified(XsdLong):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, -27273042329600, 27273042316900)
class ST_Direction(XsdTokenEnumeration):
"""Valid values for `<p:ph orient="...">` attribute."""
HORZ = "horz"
VERT = "vert"
_members = (HORZ, VERT)
class ST_DrawingElementId(XsdUnsignedInt):
pass
class ST_Extension(XsdString):
"""
Has a regular expression it needs to match in the schema, but figuring
it's not worth the trouble or run time to identify a programming error
(as opposed to a user/runtime error).
"""
pass
class ST_GapAmount(BaseIntType):
"""
String value is an integer in range 0-500, representing a percent,
optionally including a '%' suffix.
"""
@classmethod
def convert_from_xml(cls, str_value):
if "%" in str_value:
return cls.convert_from_percent_literal(str_value)
return super(ST_GapAmount, cls).convert_from_xml(str_value)
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 500)
class ST_Grouping(XsdStringEnumeration):
"""
Valid values for <c:grouping val=""> attribute. Overloaded for use as
ST_BarGrouping using same tag name.
"""
CLUSTERED = "clustered"
PERCENT_STACKED = "percentStacked"
STACKED = "stacked"
STANDARD = "standard"
_members = (CLUSTERED, PERCENT_STACKED, STACKED, STANDARD)
class ST_HexColorRGB(BaseStringType):
@classmethod
def convert_to_xml(cls, value):
"""
Keep alpha characters all uppercase just for consistency.
"""
return value.upper()
@classmethod
def validate(cls, value):
# must be string ---------------
str_value = cls.validate_string(value)
# must be 6 chars long----------
if len(str_value) != 6:
raise ValueError("RGB string must be six characters long, got '%s'" % str_value)
# must parse as hex int --------
try:
int(str_value, 16)
except ValueError:
raise ValueError("RGB string must be valid hex string, got '%s'" % str_value)
class ST_LayoutMode(XsdStringEnumeration):
"""
Valid values for `val` attribute on c:xMode and other elements of type
CT_LayoutMode.
"""
EDGE = "edge"
FACTOR = "factor"
_members = (EDGE, FACTOR)
class ST_LblOffset(XsdUnsignedShort):
"""
Unsigned integer value between 0 and 1000 inclusive, with optional
percent character ('%') suffix.
"""
@classmethod
def convert_from_xml(cls, str_value):
if str_value.endswith("%"):
return cls.convert_from_percent_literal(str_value)
return int(str_value)
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 1000)
class ST_LineWidth(XsdInt):
@classmethod
def convert_from_xml(cls, str_value):
return Emu(int(str_value))
@classmethod
def validate(cls, value):
super(ST_LineWidth, cls).validate(value)
if value < 0 or value > 20116800:
raise ValueError(
"value must be in range 0-20116800 inclusive (0-1584 points)" ", got %d" % value
)
class ST_MarkerSize(XsdUnsignedByte):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 2, 72)
class ST_Orientation(XsdStringEnumeration):
"""Valid values for `val` attribute on c:orientation (CT_Orientation)."""
MAX_MIN = "maxMin"
MIN_MAX = "minMax"
_members = (MAX_MIN, MIN_MAX)
class ST_Overlap(BaseIntType):
"""
String value is an integer in range -100..100, representing a percent,
optionally including a '%' suffix.
"""
@classmethod
def convert_from_xml(cls, str_value):
if "%" in str_value:
return cls.convert_from_percent_literal(str_value)
return super(ST_Overlap, cls).convert_from_xml(str_value)
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, -100, 100)
class ST_Percentage(BaseIntType):
"""Percentage value like 42000 or '42.0%'
Either an integer literal representing 1000ths of a percent
(e.g. "42000"), or a floating point literal with a '%' suffix
(e.g. "42.0%).
"""
@classmethod
def convert_from_xml(cls, str_value):
if "%" in str_value:
return cls._convert_from_percent_literal(str_value)
return int(str_value) / 100000.0
@classmethod
def convert_to_xml(cls, value):
return str(int(round(value * 100000.0)))
@classmethod
def validate(cls, value):
cls.validate_float_in_range(value, -21474.83648, 21474.83647)
@classmethod
def _convert_from_percent_literal(cls, str_value):
float_part = str_value[:-1] # trim off '%' character
return float(float_part) / 100.0
class ST_PlaceholderSize(XsdTokenEnumeration):
"""
Valid values for <p:ph> sz (size) attribute
"""
FULL = "full"
HALF = "half"
QUARTER = "quarter"
_members = (FULL, HALF, QUARTER)
class ST_PositiveCoordinate(XsdLong):
@classmethod
def convert_from_xml(cls, str_value):
int_value = super(ST_PositiveCoordinate, cls).convert_from_xml(str_value)
return Emu(int_value)
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 27273042316900)
class ST_PositiveFixedAngle(ST_Angle):
"""Valid values for `a:lin@ang`.
60000ths of a degree rotation, constained to positive angles less than
360 degrees.
"""
@classmethod
def convert_to_xml(cls, degrees):
"""Convert signed angle float like -427.42 to int 60000 per degree.
Value is normalized to a positive value less than 360 degrees.
"""
if degrees < 0.0:
degrees %= -360
degrees += 360
elif degrees > 0.0:
degrees %= 360
return str(int(round(degrees * cls.DEGREE_INCREMENTS)))
class ST_PositiveFixedPercentage(ST_Percentage):
"""Percentage value between 0 and 100% like 42000 or '42.0%'
Either an integer literal representing 1000ths of a percent
(e.g. "42000"), or a floating point literal with a '%' suffix
(e.g. "42.0%). Value is constrained to range of 0% to 100%. The source
value is a float between 0.0 and 1.0.
"""
@classmethod
def validate(cls, value):
cls.validate_float_in_range(value, 0.0, 1.0)
class ST_RelationshipId(XsdString):
pass
class ST_SlideId(XsdUnsignedInt):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 256, 2147483647)
class ST_SlideSizeCoordinate(BaseIntType):
@classmethod
def convert_from_xml(cls, str_value):
return Emu(str_value)
@classmethod
def validate(cls, value):
cls.validate_int(value)
if value < 914400 or value > 51206400:
raise ValueError(
"value must be in range(914400, 51206400) (1-56 inches), got" " %d" % value
)
class ST_Style(XsdUnsignedByte):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 1, 48)
class ST_TargetMode(XsdString):
"""
The valid values for the ``TargetMode`` attribute in a Relationship
element, either 'External' or 'Internal'.
"""
@classmethod
def validate(cls, value):
cls.validate_string(value)
if value not in ("External", "Internal"):
raise ValueError("must be one of 'Internal' or 'External', got '%s'" % value)
class ST_TextFontScalePercentOrPercentString(BaseFloatType):
"""
Valid values for the `fontScale` attribute of ``<a:normAutofit>``.
Translates to a float value.
"""
@classmethod
def convert_from_xml(cls, str_value):
if str_value.endswith("%"):
return float(str_value[:-1]) # trim off '%' character
return int(str_value) / 1000.0
@classmethod
def convert_to_xml(cls, value):
return str(int(value * 1000.0))
@classmethod
def validate(cls, value):
BaseFloatType.validate(value)
if value < 1.0 or value > 100.0:
raise ValueError("value must be in range 1.0..100.0 (percent), got %s" % value)
class ST_TextFontSize(BaseIntType):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 100, 400000)
class ST_TextIndentLevelType(BaseIntType):
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 8)
class ST_TextSpacingPercentOrPercentString(BaseFloatType):
@classmethod
def convert_from_xml(cls, str_value):
if str_value.endswith("%"):
return cls._convert_from_percent_literal(str_value)
return int(str_value) / 100000.0
@classmethod
def _convert_from_percent_literal(cls, str_value):
float_part = str_value[:-1] # trim off '%' character
percent_value = float(float_part)
lines_value = percent_value / 100.0
return lines_value
@classmethod
def convert_to_xml(cls, value):
"""
1.75 -> '175000'
"""
lines = value * 100000.0
return str(int(round(lines)))
@classmethod
def validate(cls, value):
cls.validate_float_in_range(value, 0.0, 132.0)
class ST_TextSpacingPoint(BaseIntType):
@classmethod
def convert_from_xml(cls, str_value):
"""
Reads string integer centipoints, returns |Length| value.
"""
return Centipoints(int(str_value))
@classmethod
def convert_to_xml(cls, value):
length = Emu(value) # just to make sure
return str(length.centipoints)
@classmethod
def validate(cls, value):
cls.validate_int_in_range(value, 0, 20116800)
class ST_TextTypeface(XsdString):
pass
class ST_TextWrappingType(XsdTokenEnumeration):
"""
Valid values for <a:bodyPr wrap=""> attribute
"""
NONE = "none"
SQUARE = "square"
_members = (NONE, SQUARE)
class ST_UniversalMeasure(BaseSimpleType):
@classmethod
def convert_from_xml(cls, str_value):
float_part, units_part = str_value[:-2], str_value[-2:]
quantity = float(float_part)
multiplier = {
"mm": 36000,
"cm": 360000,
"in": 914400,
"pt": 12700,
"pc": 152400,
"pi": 152400,
}[units_part]
emu_value = Emu(int(round(quantity * multiplier)))
return emu_value