File: enums.py

package info (click to toggle)
fpdf2 2.8.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 114,352 kB
  • sloc: python: 50,410; sh: 133; makefile: 12
file content (1877 lines) | stat: -rw-r--r-- 61,954 bytes parent folder | download
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
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
import abc
from dataclasses import dataclass
from enum import Enum, Flag, IntEnum, IntFlag
from sys import intern
from typing import (
    TYPE_CHECKING,
    ClassVar,
    Optional,
    Protocol,
    Type,
    TypeAlias,
    TypeVar,
    Union,
    cast,
)

from .drawing_primitives import convert_to_device_color
from .syntax import Name, wrap_in_local_context

if TYPE_CHECKING:
    from .drawing_primitives import Color, DeviceCMYK, DeviceGray, DeviceRGB
    from .fpdf import FPDF


class SignatureFlag(IntEnum):
    SIGNATURES_EXIST = 1
    "If set, the document contains at least one signature field."
    APPEND_ONLY = 2
    """
    If set, the document contains signatures that may be invalidated
    if the file is saved (written) in a way that alters its previous contents,
    as opposed to an incremental update.
    """


E = TypeVar("E", bound="CoerciveEnum")
IE = TypeVar("IE", bound="CoerciveIntEnum")
IF = TypeVar("IF", bound="CoerciveIntFlag")


class CoerciveEnum(Enum):
    "An enumeration that provides a helper to coerce strings into enumeration members."

    @classmethod
    def coerce(cls: Type[E], value: E | str, case_sensitive: bool = False) -> E:
        """
        Attempt to coerce `value` into a member of this enumeration.

        If value is already a member of this enumeration it is returned unchanged.
        Otherwise, if it is a string, attempt to convert it as an enumeration value. If
        that fails, attempt to convert it (case insensitively, by upcasing) as an
        enumeration name.

        If all different conversion attempts fail, an exception is raised.

        Args:
            value (Enum, str): the value to be coerced.

        Raises:
            ValueError: if `value` is a string but neither a member by name nor value.
            TypeError: if `value`'s type is neither a member of the enumeration nor a
                string.
        """

        if isinstance(value, cls):
            return value

        if isinstance(value, str):
            try:
                return cls(value)
            except ValueError:
                pass
            try:
                return cls[value] if case_sensitive else cls[value.upper()]
            except KeyError:
                pass

            raise ValueError(f"{value} is not a valid {cls.__name__}")

        raise TypeError(f"{value} cannot be converted to a {cls.__name__}")


class CoerciveIntEnum(IntEnum):
    """
    An enumeration that provides a helper to coerce strings and integers into
    enumeration members.
    """

    @classmethod
    def coerce(cls: Type[IE], value: IE | str | int) -> IE:
        """
        Attempt to coerce `value` into a member of this enumeration.

        If value is already a member of this enumeration it is returned unchanged.
        Otherwise, if it is a string, attempt to convert it (case insensitively, by
        upcasing) as an enumeration name. Otherwise, if it is an int, attempt to
        convert it as an enumeration value.

        Otherwise, an exception is raised.

        Args:
            value (IntEnum, str, int): the value to be coerced.

        Raises:
            ValueError: if `value` is an int but not a member of this enumeration.
            ValueError: if `value` is a string but not a member by name.
            TypeError: if `value`'s type is neither a member of the enumeration nor an
                int or a string.
        """
        if isinstance(value, cls):
            return value

        if isinstance(value, str):
            try:
                return cls[value.upper()]
            except KeyError:
                raise ValueError(f"{value} is not a valid {cls.__name__}") from None

        if isinstance(value, int):
            return cls(value)

        raise TypeError(f"{value} cannot convert to a {cls.__name__}")


class CoerciveIntFlag(IntFlag):
    """
    Enumerated constants that can be combined using the bitwise operators,
    with a helper to coerce strings and integers into enumeration members.
    """

    @classmethod
    def coerce(cls: Type[IF], value: IF | str | int) -> IF:
        """
        Attempt to coerce `value` into a member of this enumeration.

        If value is already a member of this enumeration it is returned unchanged.
        Otherwise, if it is a string, attempt to convert it (case insensitively, by
        upcasing) as an enumeration name. Otherwise, if it is an int, attempt to
        convert it as an enumeration value.
        Otherwise, an exception is raised.

        Args:
            value (IntEnum, str, int): the value to be coerced.

        Raises:
            ValueError: if `value` is an int but not a member of this enumeration.
            ValueError: if `value` is a string but not a member by name.
            TypeError: if `value`'s type is neither a member of the enumeration nor an
                int or a string.
        """
        if isinstance(value, cls):
            return value

        if isinstance(value, str):
            try:
                return cls[value.upper()]
            except KeyError:
                pass
            try:
                flags = cls[value[0].upper()]
                for char in value[1:]:
                    flags = flags | cls[char.upper()]
                return flags
            except KeyError:
                raise ValueError(f"{value} is not a valid {cls.__name__}") from None

        if isinstance(value, int):
            return cls(value)

        raise TypeError(f"{value} cannot convert to a {cls.__name__}")


class WrapMode(CoerciveEnum):
    "Defines how to break and wrap lines in multi-line text."

    WORD = intern("WORD")
    "Wrap by word"

    CHAR = intern("CHAR")
    "Wrap by character"


class CharVPos(CoerciveEnum):
    "Defines the vertical position of text relative to the line."

    SUP = intern("SUP")
    "Superscript"

    SUB = intern("SUB")
    "Subscript"

    NOM = intern("NOM")
    "Nominator of a fraction"

    DENOM = intern("DENOM")
    "Denominator of a fraction"

    LINE = intern("LINE")
    "Default line position"


class Align(CoerciveEnum):
    "Defines how to render text in a cell"

    C = intern("CENTER")
    "Center text horizontally"

    X = intern("X_CENTER")
    "Center text horizontally around current x position"

    L = intern("LEFT")
    "Left-align text"

    R = intern("RIGHT")
    "Right-align text"

    J = intern("JUSTIFY")
    "Justify text"

    @classmethod
    def coerce(  # pyright: ignore[reportIncompatibleMethodOverride]
        cls, value: Union["Align", str], case_sensitive: bool = False
    ) -> "Align":
        if value == "":
            return cls.L
        if isinstance(value, str):
            value = value.upper()
        return super(cls, cls).coerce(
            value, case_sensitive  # pyright: ignore[reportArgumentType]
        )


class VAlign(CoerciveEnum):
    """Defines how to vertically render text in a cell.
    Default value is MIDDLE"""

    M = intern("MIDDLE")
    "Center text vertically"

    T = intern("TOP")
    "Place text at the top of the cell, but obey the cells padding"

    B = intern("BOTTOM")
    "Place text at the bottom of the cell, but obey the cells padding"

    @classmethod
    def coerce(  # pyright: ignore[reportIncompatibleMethodOverride]
        cls, value: Union["VAlign", str], case_sensitive: bool = False
    ) -> "VAlign":
        if value == "":
            return cls.M
        return super(cls, cls).coerce(
            value, case_sensitive  # pyright: ignore[reportArgumentType]
        )


class TextEmphasis(CoerciveIntFlag):
    """
    Indicates use of bold / italics / underline.

    This enum values can be combined with & and | operators:
        style = B | I
    """

    NONE = 0
    "No emphasis"

    B = 1
    "Bold"

    I = 2
    "Italics"

    U = 4
    "Underline"

    S = 8
    "Strikethrough"

    @property
    def style(self) -> str:
        return "".join(
            name for name, value in self.__class__.__members__.items() if value & self
        )

    def add(self, value: "TextEmphasis") -> "TextEmphasis":
        return self | value

    def remove(self, value: "TextEmphasis") -> "TextEmphasis":
        return TextEmphasis.coerce(
            "".join(s for s in self.style if s not in value.style)
        )

    @classmethod
    def coerce(cls, value: Union["TextEmphasis", str, int]) -> "TextEmphasis":
        if isinstance(value, str):
            if value == "":
                return cls.NONE
            if value.upper() == "BOLD":
                return cls.B
            if value.upper() == "ITALICS":
                return cls.I
            if value.upper() == "UNDERLINE":
                return cls.U
            if value.upper() == "STRIKETHROUGH":
                return cls.S
        return super(cls, cls).coerce(value)


class MethodReturnValue(CoerciveIntFlag):
    """
    Defines the return value(s) of a FPDF content-rendering method.

    This enum values can be combined with & and | operators:
        PAGE_BREAK | LINES
    """

    PAGE_BREAK = 1
    "The method will return a boolean indicating if a page break occurred"

    LINES = 2
    "The method will return a multi-lines array of strings, after performing word-wrapping"

    HEIGHT = 4
    "The method will return how much vertical space was used"


class CellBordersLayout(CoerciveIntFlag):
    """Defines how to render cell borders in table

    The integer value of `border` determines which borders are applied. Below are some common examples:

    - border=1 (LEFT): Only the left border is enabled.
    - border=3 (LEFT | RIGHT): Both the left and right borders are enabled.
    - border=5 (LEFT | TOP): The left and top borders are enabled.
    - border=12 (TOP | BOTTOM): The top and bottom borders are enabled.
    - border=15 (ALL): All borders (left, right, top, bottom) are enabled.
    - border=16 (INHERIT): Inherit the border settings from the parent element.

    Using `border=3` will combine LEFT and RIGHT borders, as it represents the
    bitwise OR of `LEFT (1)` and `RIGHT (2)`.
    """

    NONE = 0
    "Draw no border on any side of cell"

    LEFT = 1
    "Draw border on the left side of the cell"

    RIGHT = 2
    "Draw border on the right side of the cell"

    TOP = 4
    "Draw border on the top side of the cell"

    BOTTOM = 8
    "Draw border on the bottom side of the cell"

    ALL = LEFT | RIGHT | TOP | BOTTOM
    "Draw border on all side of the cell"

    INHERIT = 16
    "Inherits the border layout from the table borders layout"

    @classmethod
    def coerce(cls, value: Union["CellBordersLayout", str, int]) -> "CellBordersLayout":
        if isinstance(value, int) and value > 16:
            raise ValueError("INHERIT cannot be combined with other values")
        return super().coerce(value)

    def __and__(self, value: int) -> "CellBordersLayout":
        value = super().__and__(value)
        if value > 16:
            raise ValueError("INHERIT cannot be combined with other values")
        return value

    def __or__(self, value: int) -> "CellBordersLayout":
        value = super().__or__(value)
        if value > 16:
            raise ValueError("INHERIT cannot be combined with other values")
        return value

    def __str__(self) -> str:
        border_str: list[str] = []
        if self & CellBordersLayout.LEFT:
            border_str.append("L")
        if self & CellBordersLayout.RIGHT:
            border_str.append("R")
        if self & CellBordersLayout.TOP:
            border_str.append("T")
        if self & CellBordersLayout.BOTTOM:
            border_str.append("B")
        return "".join(border_str) if border_str else "NONE"


@dataclass
class TableBorderStyle:
    """A helper class for drawing one border of a table

    Attributes:
        thickness: The thickness of the border. If None use default. If <= 0 don't draw the border.
        color: The color of the border. If None use default.
    """

    thickness: Optional[float] = None
    color: Union[
        int, tuple[int, int, int], "DeviceRGB", "DeviceGray", "DeviceCMYK", None
    ] = None
    dash: Optional[float] = None
    gap: float = 0.0
    phase: float = 0.0

    @staticmethod
    def from_bool(should_draw: Union[bool, "TableBorderStyle"]) -> "TableBorderStyle":
        """
        From boolean or TableBorderStyle input, convert to definite TableBorderStyle class object
        """
        if isinstance(should_draw, TableBorderStyle):
            return should_draw  # don't change specified TableBorderStyle
        if should_draw:
            return TableBorderStyle()  # keep default stroke
        return TableBorderStyle(thickness=0.0)  # don't draw the border

    def _changes_thickness(self, pdf: "FPDF") -> bool:
        """Return True if this style changes the thickness of the draw command, False otherwise"""
        return (
            self.thickness is not None
            and self.thickness > 0.0
            and self.thickness != pdf.line_width
        )

    def _changes_color(self, pdf: "FPDF") -> bool:
        """Return True if this style changes the color of the draw command, False otherwise"""
        return self.color is not None and self.color != pdf.draw_color

    @property
    def dash_dict(self) -> dict[str, Optional[float]]:
        """Return dict object specifying dash in the same format as the pdf object"""
        return {"dash": self.dash, "gap": self.gap, "phase": self.phase}

    def _changes_dash(self, pdf: "FPDF") -> bool:
        """Return True if this style changes the dash of the draw command, False otherwise"""
        return self.dash is not None and self.dash_dict != pdf.dash_pattern

    def changes_stroke(self, pdf: "FPDF") -> bool:
        """Return True if this style changes the any aspect of the draw command, False otherwise"""
        return self.should_render() and (
            self._changes_color(pdf)
            or self._changes_thickness(pdf)
            or self._changes_dash(pdf)
        )

    def should_render(self) -> bool:
        """Return True if this style produces a visible stroke, False otherwise"""
        return self.thickness is None or self.thickness > 0.0

    def _get_change_thickness_command(
        self, scale: float, pdf: Optional["FPDF"] = None
    ) -> list[str]:
        """Return list with string for the draw command to change thickness (empty if no change)"""
        thickness = self.thickness if pdf is None else pdf.line_width
        return [] if thickness is None else [f"{thickness * scale:.2f} w"]

    def _get_change_line_color_command(self, pdf: Optional["FPDF"] = None) -> list[str]:
        """Return list with string for the draw command to change color (empty if no change)"""
        if pdf is None:
            color = self.color
        else:
            color = pdf.draw_color
        return (
            []
            if color is None
            else [convert_to_device_color(color).serialize().upper()]
        )

    def _get_change_dash_command(
        self, scale: float, pdf: Optional["FPDF"] = None
    ) -> list[str]:
        """Return list with string for the draw command to change dash (empty if no change)"""
        dash_dict = self.dash_dict if pdf is None else pdf.dash_pattern
        dash, gap, phase = dash_dict["dash"], dash_dict["gap"], dash_dict["phase"]
        if dash is None:
            return []
        if dash <= 0:
            return ["[] 0 d"]
        assert phase is not None
        if gap is None or gap <= 0:
            return [f"[{dash * scale:.3f}] {phase * scale:.3f} d"]
        return [f"[{dash * scale:.3f} {gap * scale:.3f}] {phase * scale:.3f} d"]

    def get_change_stroke_commands(self, scale: float) -> list[str]:
        """Return list of strings for the draw command to change stroke (empty if no change)"""
        return (
            self._get_change_dash_command(scale)
            + self._get_change_line_color_command()
            + self._get_change_thickness_command(scale)
        )

    @staticmethod
    def get_line_command(x1: float, y1: float, x2: float, y2: float) -> list[str]:
        """Return list with string for the command to draw a line at the specified endpoints"""
        return [f"{x1:.2f} {y1:.2f} m {x2:.2f} {y2:.2f} l S"]

    def get_draw_commands(
        self, pdf: "FPDF", x1: float, y1: float, x2: float, y2: float
    ) -> list[str]:
        """
        Get draw commands for this section of a cell border. x and y are presumed to be already
        shifted and scaled.
        """
        if not self.should_render():
            return []

        if self.changes_stroke(pdf):
            draw_commands = self.get_change_stroke_commands(
                scale=pdf.k
            ) + self.get_line_command(x1, y1, x2, y2)
            # wrap in local context to prevent stroke changes from affecting later rendering
            return wrap_in_local_context(draw_commands)
        return self.get_line_command(x1, y1, x2, y2)


@dataclass
class TableCellStyle:
    """A helper class for drawing all the borders of one cell in a table

    Attributes:
        left: bool or TableBorderStyle specifying the style of the cell's left border
        bottom: bool or TableBorderStyle specifying the style of the cell's bottom border
        right: bool or TableBorderStyle specifying the style of the cell's right border
        top: bool or TableBorderStyle specifying the style of the cell's top border
    """

    left: bool | TableBorderStyle = False
    bottom: bool | TableBorderStyle = False
    right: bool | TableBorderStyle = False
    top: bool | TableBorderStyle = False

    def _get_common_border_style(self) -> Optional[bool | TableBorderStyle]:
        """Return bool or TableBorderStyle if all borders have the same style, otherwise None"""
        if all(
            isinstance(border, bool)
            for border in [self.left, self.bottom, self.right, self.top]
        ):
            if all(border for border in [self.left, self.bottom, self.right, self.top]):
                return True
            if all(
                not border for border in [self.left, self.bottom, self.right, self.top]
            ):
                return False
        elif all(
            isinstance(border, TableBorderStyle)
            for border in [self.left, self.bottom, self.right, self.top]
        ):
            common = self.left
            if all(border == common for border in [self.bottom, self.right, self.top]):
                return common
        return None

    @staticmethod
    def get_change_fill_color_command(color: Union["Color", str]) -> list[str]:
        """Return list with string for command to change device color (empty list if no color)"""
        return (
            []
            if color is None
            else [convert_to_device_color(color).serialize().lower()]
        )

    def get_draw_commands(
        self,
        pdf: "FPDF",
        x1: float,
        y1: float,
        x2: float,
        y2: float,
        fill_color: Optional[Union["Color", str]] = None,
    ) -> list[str]:
        """
        Get list of primitive commands to draw the cell border for this cell, and fill it with the
        given fill color.
        """
        # y top to bottom instead of bottom to top
        y1 = pdf.h - y1
        y2 = pdf.h - y2
        # scale coordinates and thickness
        scale = pdf.k
        x1 *= scale
        y1 *= scale
        x2 *= scale
        y2 *= scale

        common_border_style = self._get_common_border_style()
        draw_commands, needs_wrap = (
            self._draw_when_no_common_style(x1, y1, x2, y2, pdf, fill_color)
            if common_border_style is None
            else (
                self._draw_with_no_border(x1, y1, x2, y2, pdf, fill_color)
                if common_border_style is False
                else self._draw_all_borders_the_same(
                    x1, y1, x2, y2, pdf, fill_color, scale, common_border_style
                )
            )
        )

        if needs_wrap:
            draw_commands = wrap_in_local_context(draw_commands)

        return draw_commands

    def _draw_when_no_common_style(
        self,
        x1: float,
        y1: float,
        x2: float,
        y2: float,
        pdf: "FPDF",
        fill_color: Optional[Union["Color", str]],
    ) -> tuple[list[str], bool]:
        """Get draw commands for case when some of the borders have different styles"""
        needs_wrap = False
        draw_commands: list[str] = []
        if fill_color is not None:
            # draw fill with no box
            if fill_color != pdf.fill_color:
                needs_wrap = True
                draw_commands.extend(self.get_change_fill_color_command(fill_color))
            draw_commands.append(f"{x1:.2f} {y2:.2f} {x2 - x1:.2f} {y1 - y2:.2f} re f")
        # draw the individual borders
        draw_commands.extend(
            TableBorderStyle.from_bool(self.left).get_draw_commands(pdf, x1, y2, x1, y1)
            + TableBorderStyle.from_bool(self.bottom).get_draw_commands(
                pdf, x1, y2, x2, y2
            )
            + TableBorderStyle.from_bool(self.right).get_draw_commands(
                pdf, x2, y2, x2, y1
            )
            + TableBorderStyle.from_bool(self.top).get_draw_commands(
                pdf, x1, y1, x2, y1
            )
        )
        return draw_commands, needs_wrap

    def _draw_with_no_border(
        self,
        x1: float,
        y1: float,
        x2: float,
        y2: float,
        pdf: "FPDF",
        fill_color: Optional[Union["Color", str]],
    ) -> tuple[list[str], bool]:
        """Get draw commands for case when all of the borders are off / not drawn"""
        needs_wrap = False
        draw_commands: list[str] = []
        if fill_color is not None:
            # draw fill with no box
            if fill_color != pdf.fill_color:
                needs_wrap = True
                draw_commands.extend(self.get_change_fill_color_command(fill_color))
            draw_commands.append(f"{x1:.2f} {y2:.2f} {x2 - x1:.2f} {y1 - y2:.2f} re f")
        return draw_commands, needs_wrap

    def _draw_all_borders_the_same(
        self,
        x1: float,
        y1: float,
        x2: float,
        y2: float,
        pdf: "FPDF",
        fill_color: Optional[Union["Color", str]],
        scale: float,
        common_border_style: Optional[TableBorderStyle | bool],
    ) -> tuple[list[str], bool]:
        """Get draw commands for case when all the borders have the same style"""
        needs_wrap = False
        draw_commands: list[str] = []
        # all borders are the same
        if isinstance(
            common_border_style, TableBorderStyle
        ) and common_border_style.changes_stroke(pdf):
            # the border styles aren't default, so
            draw_commands.extend(common_border_style.get_change_stroke_commands(scale))
            needs_wrap = True
        if fill_color is not None:
            # draw filled rectangle
            if fill_color != pdf.fill_color:
                needs_wrap = True
                draw_commands.extend(self.get_change_fill_color_command(fill_color))
            draw_commands.append(f"{x1:.2f} {y2:.2f} {x2 - x1:.2f} {y1 - y2:.2f} re B")
        else:
            # draw empty rectangle
            draw_commands.append(f"{x1:.2f} {y2:.2f} {x2 - x1:.2f} {y1 - y2:.2f} re S")
        return draw_commands, needs_wrap

    def override_cell_border(self, cell_border: CellBordersLayout) -> "TableCellStyle":
        """Allow override by CellBordersLayout mechanism"""
        return (
            self
            if cell_border == CellBordersLayout.INHERIT
            else TableCellStyle(  # translate cell_border into equivalent TableCellStyle
                left=bool(cell_border & CellBordersLayout.LEFT),
                bottom=bool(cell_border & CellBordersLayout.BOTTOM),
                right=bool(cell_border & CellBordersLayout.RIGHT),
                top=bool(cell_border & CellBordersLayout.TOP),
            )
        )

    def draw_cell_border(
        self,
        pdf: "FPDF",
        x1: float,
        y1: float,
        x2: float,
        y2: float,
        fill_color: Optional[Union["Color", str]] = None,
    ) -> None:
        """
        Draw the cell border for this cell, and fill it with the given fill color.
        """
        pdf._out(  # pylint: disable=protected-access # pyright: ignore[reportPrivateUsage]
            " ".join(self.get_draw_commands(pdf, x1, y1, x2, y2, fill_color=fill_color))
        )


class TableBordersLayout(abc.ABC):
    """
    Customizable class for setting the drawing style of cell borders for the whole table.
    cell_style_getter is an abstract method that derived classes must implement. All current classes
    do not use self, but it is available in case a very complicated derived class needs to refer to
    stored internal data.

    Standard TableBordersLayouts are available as static members of this class

    Attributes:
        cell_style_getter: a callable that takes row_num, column_num,
            num_heading_rows, num_rows, num_columns; and returns the drawing style of
            the cell border (as a TableCellStyle object)
        ALL: static TableBordersLayout that draws all table cells borders
        NONE: static TableBordersLayout that draws no table cells borders
        INTERNAL: static TableBordersLayout that draws only internal horizontal & vertical borders
        MINIMAL: static TableBordersLayout that draws only the top horizontal border, below the
            headings, and internal vertical borders
        HORIZONTAL_LINES: static TableBordersLayout that draws only horizontal lines
        NO_HORIZONTAL_LINES: static TableBordersLayout that draws all cells border except interior
            horizontal lines after the headings
        SINGLE_TOP_LINE: static TableBordersLayout that draws only the top horizontal border, below
            the headings
    """

    ALL: ClassVar["TableBordersLayout"]
    NONE: ClassVar["TableBordersLayout"]
    INTERNAL: ClassVar["TableBordersLayout"]
    MINIMAL: ClassVar["TableBordersLayout"]
    HORIZONTAL_LINES: ClassVar["TableBordersLayout"]
    NO_HORIZONTAL_LINES: ClassVar["TableBordersLayout"]
    SINGLE_TOP_LINE: ClassVar["TableBordersLayout"]

    @abc.abstractmethod
    def cell_style_getter(
        self,
        row_idx: int,
        col_idx: int,
        col_pos: int,
        num_heading_rows: int,
        num_rows: int,
        num_col_idx: int,
        num_col_pos: int,
    ) -> TableCellStyle:
        """Specify the desired TableCellStyle for the given position in the table

        Args:
            row_idx: the 0-based index of the row in the table
            col_idx: the 0-based logical index of the cell in the row. If colspan > 1, this indexes
                into non-null cells. e.g. if there are two cells with colspan = 3, then col_idx will
                be 0 or 1
            col_pos: the 0-based physical position of the cell in the row. If colspan > 1, this
                indexes into all cells including null ones. e.g. e.g. if there are two cells with
                colspan = 3, then col_pos will be 0 or 3
            num_heading_rows: the number of rows in the table heading
            num_rows: the total number of rows in the table
            num_col_idx: the number of non-null cells. e.g. if there are two cells with colspan = 3,
                then num_col_idx = 2
            num_col_pos: the full width of the table in physical cells. e.g. if there are two cells
                with colspan = 3, then num_col_pos = 6
        Returns:
            TableCellStyle for the given position in the table
        """
        raise NotImplementedError

    @classmethod
    def coerce(cls, value: Union["TableBordersLayout", str]) -> "TableBordersLayout":
        """
        Attempt to coerce `value` into a member of this class.

        If value is already a member of this enumeration it is returned unchanged.
        Otherwise, if it is a string, attempt to convert it as an enumeration value. If
        that fails, attempt to convert it (case insensitively, by upcasing) as an
        enumeration name.

        If all different conversion attempts fail, an exception is raised.

        Args:
            value (Enum, str): the value to be coerced.

        Raises:
            ValueError: if `value` is a string but neither a member by name nor value.
            TypeError: if `value`'s type is neither a member of the enumeration nor a
                string.
        """

        if isinstance(value, cls):
            return value

        if isinstance(value, str):
            try:
                coerced_value = getattr(cls, value.upper())
                if isinstance(coerced_value, cls):
                    return coerced_value
            except ValueError:
                pass

        raise ValueError(f"{value} is not a valid {cls.__name__}")


class TableBordersLayoutAll(TableBordersLayout):
    """Class for drawing all cell borders"""

    def cell_style_getter(
        self,
        row_idx: int,
        col_idx: int,
        col_pos: int,
        num_heading_rows: int,
        num_rows: int,
        num_col_idx: int,
        num_col_pos: int,
    ) -> TableCellStyle:
        return TableCellStyle(left=True, bottom=True, right=True, top=True)


# add as static member of base TableBordersLayout class
TableBordersLayout.ALL = TableBordersLayoutAll()


class TableBordersLayoutNone(TableBordersLayout):
    """Class for drawing zero cell borders"""

    def cell_style_getter(
        self,
        row_idx: int,
        col_idx: int,
        col_pos: int,
        num_heading_rows: int,
        num_rows: int,
        num_col_idx: int,
        num_col_pos: int,
    ) -> TableCellStyle:
        return TableCellStyle(left=False, bottom=False, right=False, top=False)


# add as static member of base TableBordersLayout class
TableBordersLayout.NONE = TableBordersLayoutNone()


class TableBordersLayoutInternal(TableBordersLayout):
    """Class to draw only internal horizontal & vertical borders"""

    def cell_style_getter(
        self,
        row_idx: int,
        col_idx: int,
        col_pos: int,
        num_heading_rows: int,
        num_rows: int,
        num_col_idx: int,
        num_col_pos: int,
    ) -> TableCellStyle:
        return TableCellStyle(
            left=col_idx > 0,
            bottom=row_idx < num_rows - 1,
            right=col_idx < num_col_idx - 1,
            top=row_idx > 0,
        )


# add as static member of base TableBordersLayout class
TableBordersLayout.INTERNAL = TableBordersLayoutInternal()


class TableBordersLayoutMinimal(TableBordersLayout):
    """
    Class to draw only the top horizontal border, below the headings, and internal vertical borders
    """

    def cell_style_getter(
        self,
        row_idx: int,
        col_idx: int,
        col_pos: int,
        num_heading_rows: int,
        num_rows: int,
        num_col_idx: int,
        num_col_pos: int,
    ) -> TableCellStyle:
        return TableCellStyle(
            left=col_idx > 0,
            bottom=row_idx < num_heading_rows,
            right=col_idx < num_col_idx - 1,
            top=0 < row_idx <= num_heading_rows,
        )


# add as static member of base TableBordersLayout class
TableBordersLayout.MINIMAL = TableBordersLayoutMinimal()


class TableBordersLayoutHorizontalLines(TableBordersLayout):
    """Class to draw only horizontal lines"""

    def cell_style_getter(
        self,
        row_idx: int,
        col_idx: int,
        col_pos: int,
        num_heading_rows: int,
        num_rows: int,
        num_col_idx: int,
        num_col_pos: int,
    ) -> TableCellStyle:
        return TableCellStyle(
            left=False,
            bottom=row_idx < num_rows - 1,
            right=False,
            top=row_idx > 0,
        )


# add as static member of base TableBordersLayout class
TableBordersLayout.HORIZONTAL_LINES = TableBordersLayoutHorizontalLines()


class TableBordersLayoutNoHorizontalLines(TableBordersLayout):
    """Class to draw all cells border except interior horizontal lines after the headings"""

    def cell_style_getter(
        self,
        row_idx: int,
        col_idx: int,
        col_pos: int,
        num_heading_rows: int,
        num_rows: int,
        num_col_idx: int,
        num_col_pos: int,
    ) -> TableCellStyle:
        return TableCellStyle(
            left=True,
            bottom=row_idx == num_rows - 1,
            right=True,
            top=row_idx <= num_heading_rows,
        )


# add as static member of base TableBordersLayout class
TableBordersLayout.NO_HORIZONTAL_LINES = TableBordersLayoutNoHorizontalLines()


class TableBordersLayoutSingleTopLine(TableBordersLayout):
    """Class to draw a single top line"""

    def cell_style_getter(
        self,
        row_idx: int,
        col_idx: int,
        col_pos: int,
        num_heading_rows: int,
        num_rows: int,
        num_col_idx: int,
        num_col_pos: int,
    ) -> TableCellStyle:
        return TableCellStyle(
            left=False, bottom=row_idx <= num_heading_rows - 1, right=False, top=False
        )


# add as static member of base TableBordersLayout class
TableBordersLayout.SINGLE_TOP_LINE = TableBordersLayoutSingleTopLine()


class CellFillProtocol(Protocol):
    """Protocol for custom table cell fill mode classes"""

    def should_fill_cell(self, i: int, j: int) -> bool: ...


TableCellFillModeType: TypeAlias = "TableCellFillMode | CellFillProtocol"


class TableCellFillMode(CoerciveEnum):
    "Defines which table cells to fill"

    NONE = intern("NONE")
    "Fill zero table cell"

    ALL = intern("ALL")
    "Fill all table cells"

    ROWS = intern("ROWS")
    "Fill only table cells in odd rows"

    COLUMNS = intern("COLUMNS")
    "Fill only table cells in odd columns"

    EVEN_ROWS = intern("EVEN_ROWS")
    "Fill only table cells in even rows"

    EVEN_COLUMNS = intern("EVEN_COLUMNS")
    "Fill only table cells in even columns"

    @classmethod
    def coerce(  # type: ignore[override]
        cls,
        value: Union[TableCellFillModeType, str],
        case_sensitive: bool = False,
    ) -> TableCellFillModeType:
        if callable(getattr(value, "should_fill_cell", None)):
            return cast(CellFillProtocol, value)
        return super().coerce(value, case_sensitive)  # type: ignore[arg-type] # pyright: ignore[reportArgumentType]

    def should_fill_cell(self, i: int, j: int) -> bool:
        if self is TableCellFillMode.NONE:
            return False
        if self is TableCellFillMode.ALL:
            return True
        if self is TableCellFillMode.ROWS:
            return i % 2 == 1
        if self is TableCellFillMode.COLUMNS:
            return j % 2 == 1
        if self is TableCellFillMode.EVEN_ROWS:
            return i % 2 == 0
        if self is TableCellFillMode.EVEN_COLUMNS:
            return j % 2 == 0
        raise NotImplementedError


class TableSpan(CoerciveEnum):
    ROW = intern("ROW")
    "Mark this cell as a continuation of the previous row"

    COL = intern("COL")
    "Mark this cell as a continuation of the previous column"


class TableHeadingsDisplay(CoerciveIntEnum):
    "Defines how the table headings should be displayed"

    NONE = 0
    "0: Only render the table headings at the beginning of the table"

    ON_TOP_OF_EVERY_PAGE = 1
    "1: When a page break occurs, repeat the table headings at the top of every table fragment"


class RenderStyle(CoerciveEnum):
    "Defines how to render shapes"

    D = intern("DRAW")
    """
    Draw lines.
    Line color can be controlled with `fpdf.fpdf.FPDF.set_draw_color()`.
    Line thickness can be controlled with `fpdf.fpdf.FPDF.set_line_width()`.
    """

    F = intern("FILL")
    """
    Fill areas.
    Filling color can be controlled with `fpdf.fpdf.FPDF.set_fill_color()`.
    """

    DF = intern("DRAW_FILL")
    "Draw lines and fill areas"

    @property
    def operator(self) -> str:
        return {RenderStyle.D: "S", RenderStyle.F: "f", RenderStyle.DF: "B"}[self]

    @property
    def is_draw(self) -> bool:
        return self in (RenderStyle.D, RenderStyle.DF)

    @property
    def is_fill(self) -> bool:
        return self in (RenderStyle.F, RenderStyle.DF)

    @classmethod
    def coerce(  # pyright: ignore[reportIncompatibleMethodOverride]
        cls, value: Union["RenderStyle", str], case_sensitive: bool = False
    ) -> "RenderStyle":
        if not value:
            return cls.D
        if value == "FD":
            value = "DF"
        return super(cls, cls).coerce(
            value, case_sensitive  # pyright: ignore[reportArgumentType]
        )


class TextMode(CoerciveIntEnum):
    "Values described in PDF spec section 'Text Rendering Mode'"

    FILL = 0
    STROKE = 1
    FILL_STROKE = 2
    INVISIBLE = 3
    FILL_CLIP = 4
    STROKE_CLIP = 5
    FILL_STROKE_CLIP = 6
    CLIP = 7


class XPos(CoerciveEnum):
    "Positional values in horizontal direction for use after printing text."

    LEFT = intern("LEFT")  # self.x
    "left end of the cell"

    RIGHT = intern("RIGHT")  # self.x + w
    "right end of the cell (default)"

    START = intern("START")
    "left start of actual text"

    END = intern("END")
    "right end of actual text"

    WCONT = intern("WCONT")
    "for write() to continue next (slightly left of END)"

    CENTER = intern("CENTER")
    "center of actual text"

    LMARGIN = intern("LMARGIN")  # self.l_margin
    "left page margin (start of printable area)"

    RMARGIN = intern("RMARGIN")  # self.w - self.r_margin
    "right page margin (end of printable area)"


class YPos(CoerciveEnum):
    "Positional values in vertical direction for use after printing text"

    TOP = intern("TOP")  # self.y
    "top of the first line (default)"

    LAST = intern("LAST")
    "top of the last line (same as TOP for single-line text)"

    NEXT = intern("NEXT")  # LAST + h
    "top of next line (bottom of current text)"

    TMARGIN = intern("TMARGIN")  # self.t_margin
    "top page margin (start of printable area)"

    BMARGIN = intern("BMARGIN")  # self.h - self.b_margin
    "bottom page margin (end of printable area)"


class Angle(CoerciveIntEnum):
    "Direction values used for mirror transformations specifying the angle of mirror line"

    NORTH = 90
    EAST = 0
    SOUTH = 270
    WEST = 180
    NORTHEAST = 45
    SOUTHEAST = 315
    SOUTHWEST = 225
    NORTHWEST = 135


class PageLayout(CoerciveEnum):
    "Specify the page layout shall be used when the document is opened"

    SINGLE_PAGE = Name("SinglePage")
    "Display one page at a time"

    ONE_COLUMN = Name("OneColumn")
    "Display the pages in one column"

    TWO_COLUMN_LEFT = Name("TwoColumnLeft")
    "Display the pages in two columns, with odd-numbered pages on the left"

    TWO_COLUMN_RIGHT = Name("TwoColumnRight")
    "Display the pages in two columns, with odd-numbered pages on the right"

    TWO_PAGE_LEFT = Name("TwoPageLeft")
    "Display the pages two at a time, with odd-numbered pages on the left"

    TWO_PAGE_RIGHT = Name("TwoPageRight")
    "Display the pages two at a time, with odd-numbered pages on the right"


class PageMode(CoerciveEnum):
    "Specifying how to display the document on exiting full-screen mode"

    USE_NONE = Name("UseNone")
    "Neither document outline nor thumbnail images visible"

    USE_OUTLINES = Name("UseOutlines")
    "Document outline visible"

    USE_THUMBS = Name("UseThumbs")
    "Thumbnail images visible"

    FULL_SCREEN = Name("FullScreen")
    "Full-screen mode, with no menu bar, window controls, or any other window visible"

    USE_OC = Name("UseOC")
    "Optional content group panel visible"

    USE_ATTACHMENTS = Name("UseAttachments")
    "Attachments panel visible"


class TextMarkupType(CoerciveEnum):
    "Subtype of a text markup annotation"

    HIGHLIGHT = Name("Highlight")

    UNDERLINE = Name("Underline")

    SQUIGGLY = Name("Squiggly")

    STRIKE_OUT = Name("StrikeOut")


class BlendMode(CoerciveEnum):
    "An enumeration of the named standard named blend functions supported by PDF."

    NORMAL = Name("Normal")
    '''"Selects the source color, ignoring the backdrop."'''
    MULTIPLY = Name("Multiply")
    '''"Multiplies the backdrop and source color values."'''
    SCREEN = Name("Screen")
    """
    "Multiplies the complements of the backdrop and source color values, then
    complements the result."
    """
    OVERLAY = Name("Overlay")
    """
    "Multiplies or screens the colors, depending on the backdrop color value. Source
    colors overlay the backdrop while preserving its highlights and shadows. The
    backdrop color is not replaced but is mixed with the source color to reflect the
    lightness or darkness of the backdrop."
    """
    DARKEN = Name("Darken")
    '''"Selects the darker of the backdrop and source colors."'''
    LIGHTEN = Name("Lighten")
    '''"Selects the lighter of the backdrop and source colors."'''
    COLOR_DODGE = Name("ColorDodge")
    """
    "Brightens the backdrop color to reflect the source color. Painting with black
     produces no changes."
    """
    COLOR_BURN = Name("ColorBurn")
    """
    "Darkens the backdrop color to reflect the source color. Painting with white
     produces no change."
    """
    HARD_LIGHT = Name("HardLight")
    """
    "Multiplies or screens the colors, depending on the source color value. The effect
    is similar to shining a harsh spotlight on the backdrop."
    """
    SOFT_LIGHT = Name("SoftLight")
    """
    "Darkens or lightens the colors, depending on the source color value. The effect is
    similar to shining a diffused spotlight on the backdrop."
    """
    DIFFERENCE = Name("Difference")
    '''"Subtracts the darker of the two constituent colors from the lighter color."'''
    EXCLUSION = Name("Exclusion")
    """
    "Produces an effect similar to that of the Difference mode but lower in contrast.
    Painting with white inverts the backdrop color; painting with black produces no
    change."
    """
    HUE = Name("Hue")
    """
    "Creates a color with the hue of the source color and the saturation and luminosity
    of the backdrop color."
    """
    SATURATION = Name("Saturation")
    """
    "Creates a color with the saturation of the source color and the hue and luminosity
    of the backdrop color. Painting with this mode in an area of the backdrop that is
    a pure gray (no saturation) produces no change."
    """
    COLOR = Name("Color")
    """
    "Creates a color with the hue and saturation of the source color and the luminosity
    of the backdrop color. This preserves the gray levels of the backdrop and is
    useful for coloring monochrome images or tinting color images."
    """
    LUMINOSITY = Name("Luminosity")
    """
    "Creates a color with the luminosity of the source color and the hue and saturation
    of the backdrop color. This produces an inverse effect to that of the Color mode."
    """


class CompositingOperation(CoerciveEnum):
    "An enumeration of Porter-Duff compositing operations."

    CLEAR = Name("Clear")
    """ Draw nothing """

    SOURCE = Name("Source")
    """ Draw the source only """

    DESTINATION = Name("Destination")
    """ Draw the destination only """

    SOURCE_OVER = Name("SourceOver")
    """The source is drawn over the destination (backdrop)."""

    DESTINATION_OVER = Name("DestinationOver")
    """The destination (backdrop) is drawn over the source."""

    SOURCE_IN = Name("SourceIn")
    """Only the part of the source that overlaps with the destination is drawn. The rest is discarded."""

    DESTINATION_IN = Name("DestinationIn")
    """Only the part of the destination that overlaps with the source is drawn. The rest is discarded."""

    SOURCE_OUT = Name("SourceOut")
    """Only the part of the source that does not overlap the destination is drawn."""

    DESTINATION_OUT = Name("DestinationOut")
    """Only the part of the destination that does not overlap the source is drawn."""

    SOURCE_ATOP = Name("SourceAtop")
    """The part of the source that overlaps the destination is drawn over the destination. The rest of the source is discarded."""

    DESTINATION_ATOP = Name("DestinationAtop")
    """The part of the destination that overlaps the source is drawn over the source. The rest of the destination is discarded."""

    XOR = Name("XOR")
    """Only the parts of the source and destination that do not overlap are drawn."""


class AnnotationFlag(CoerciveIntEnum):
    INVISIBLE = 1
    """
    If set, do not display the annotation if it does not belong to one of the
    standard annotation types and no annotation handler is available.
    """
    HIDDEN = 2
    "If set, do not display or print the annotation or allow it to interact with the user"
    PRINT = 4
    "If set, print the annotation when the page is printed."
    NO_ZOOM = 8
    "If set, do not scale the annotation’s appearance to match the magnification of the page."
    NO_ROTATE = 16
    "If set, do not rotate the annotation’s appearance to match the rotation of the page."
    NO_VIEW = 32
    "If set, do not display the annotation on the screen or allow it to interact with the user"
    READ_ONLY = 64
    """
    If set, do not allow the annotation to interact with the user.
    The annotation may be displayed or printed but should not respond to mouse clicks.
    """
    LOCKED = 128
    """
    If set, do not allow the annotation to be deleted or its properties
    (including position and size) to be modified by the user.
    """
    TOGGLE_NO_VIEW = 256
    "If set, invert the interpretation of the NoView flag for certain events."
    LOCKED_CONTENTS = 512
    "If set, do not allow the contents of the annotation to be modified by the user."


class AnnotationName(CoerciveEnum):
    "The name of an icon that shall be used in displaying the annotation"

    NOTE = Name("Note")
    COMMENT = Name("Comment")
    HELP = Name("Help")
    PARAGRAPH = Name("Paragraph")
    NEW_PARAGRAPH = Name("NewParagraph")
    INSERT = Name("Insert")


class FileAttachmentAnnotationName(CoerciveEnum):
    "The name of an icon that shall be used in displaying the annotation"

    PUSH_PIN = Name("PushPin")
    GRAPH_PUSH_PIN = Name("GraphPushPin")
    PAPERCLIP_TAG = Name("PaperclipTag")


class IntersectionRule(CoerciveEnum):
    """
    An enumeration representing the two possible PDF intersection rules.

    The intersection rule is used by the renderer to determine which points are
    considered to be inside the path and which points are outside the path. This
    primarily affects fill rendering and clipping paths.
    """

    NONZERO = "nonzero"
    """
    "The nonzero winding number rule determines whether a given point is inside a path
    by conceptually drawing a ray from that point to infinity in any direction and
    then examining the places where a segment of the path crosses the ray. Starting
    with a count of 0, the rule adds 1 each time a path segment crosses the ray from
    left to right and subtracts 1 each time a segment crosses from right to left.
    After counting all the crossings, if the result is 0, the point is outside the
    path; otherwise, it is inside."
    """
    EVENODD = "evenodd"
    """
    "An alternative to the nonzero winding number rule is the even-odd rule. This rule
    determines whether a point is inside a path by drawing a ray from that point in
    any direction and simply counting the number of path segments that cross the ray,
    regardless of direction. If this number is odd, the point is inside; if even, the
    point is outside. This yields the same results as the nonzero winding number rule
    for paths with simple shapes, but produces different results for more complex
    shapes."
    """


class PathPaintRule(CoerciveEnum):
    """
    An enumeration of the PDF drawing directives that determine how the renderer should
    paint a given path.
    """

    # the auto-close paint rules are omitted here because it's easier to just emit
    # close operators when appropriate, programmatically
    STROKE = "S"
    '''"Stroke the path."'''

    FILL_NONZERO = "f"
    """
    "Fill the path, using the nonzero winding number rule to determine the region to
    fill. Any subpaths that are open are implicitly closed before being filled."
    """

    FILL_EVENODD = "f*"
    """
    "Fill the path, using the even-odd rule to determine the region to fill. Any
    subpaths that are open are implicitly closed before being filled."
    """

    STROKE_FILL_NONZERO = "B"
    """
    "Fill and then stroke the path, using the nonzero winding number rule to determine
    the region to fill. This operator produces the same result as constructing two
    identical path objects, painting the first with `FILL_NONZERO` and the second with
    `STROKE`."
    """

    STROKE_FILL_EVENODD = "B*"
    """
    "Fill and then stroke the path, using the even-odd rule to determine the region to
    fill. This operator produces the same result as `STROKE_FILL_NONZERO`, except that
    the path is filled as if with `FILL_EVENODD` instead of `FILL_NONZERO`."
    """

    DONT_PAINT = "n"
    """
    "End the path object without filling or stroking it. This operator is a
    path-painting no-op, used primarily for the side effect of changing the current
    clipping path."
    """

    AUTO = "auto"
    """
    Automatically determine which `PathPaintRule` should be used.

    PaintedPath will select one of the above `PathPaintRule`s based on the resolved
    set/inherited values of its style property.
    """


class ClippingPathIntersectionRule(CoerciveEnum):
    "An enumeration of the PDF drawing directives that define a path as a clipping path."

    NONZERO = "W"
    """
    "The nonzero winding number rule determines whether a given point is inside a path
    by conceptually drawing a ray from that point to infinity in any direction and
    then examining the places where a segment of the path crosses the ray. Starting
    with a count of 0, the rule adds 1 each time a path segment crosses the ray from
    left to right and subtracts 1 each time a segment crosses from right to left.
    After counting all the crossings, if the result is 0, the point is outside the
    path; otherwise, it is inside."
    """
    EVENODD = "W*"
    """
    "An alternative to the nonzero winding number rule is the even-odd rule. This rule
    determines whether a point is inside a path by drawing a ray from that point in
    any direction and simply counting the number of path segments that cross the ray,
    regardless of direction. If this number is odd, the point is inside; if even, the
    point is outside. This yields the same results as the nonzero winding number rule
    for paths with simple shapes, but produces different results for more complex
    shapes."""


class StrokeCapStyle(CoerciveIntEnum):
    """
    An enumeration of values defining how the end of a stroke should be rendered.

    This affects the ends of the segments of dashed strokes, as well.
    """

    BUTT = 0
    """
    "The stroke is squared off at the endpoint of the path. There is no projection
    beyond the end of the path."
    """
    ROUND = 1
    """
    "A semicircular arc with a diameter equal to the line width is drawn around the
    endpoint and filled in."
    """
    SQUARE = 2
    """
    "The stroke continues beyond the endpoint of the path for a distance equal to half
    the line width and is squared off."
    """


class StrokeJoinStyle(CoerciveIntEnum):
    """
    An enumeration of values defining how the corner joining two path components should
    be rendered.
    """

    MITER = 0
    """
    "The outer edges of the strokes for the two segments are extended until they meet at
    an angle, as in a picture frame. If the segments meet at too sharp an angle
    (as defined by the miter limit parameter), a bevel join is used instead."
    """
    ROUND = 1
    """
    "An arc of a circle with a diameter equal to the line width is drawn around the
    point where the two segments meet, connecting the outer edges of the strokes for
    the two segments. This pieslice-shaped figure is filled in, pro- ducing a rounded
    corner."
    """
    BEVEL = 2
    """
    "The two segments are finished with butt caps and the resulting notch beyond the
    ends of the segments is filled with a triangle."
    """


class PDFStyleKeys(Enum):
    "An enumeration of the graphics state parameter dictionary keys."

    FILL_ALPHA = Name("ca")
    BLEND_MODE = Name("BM")  # shared between stroke and fill
    STROKE_ALPHA = Name("CA")
    STROKE_ADJUSTMENT = Name("SA")
    STROKE_WIDTH = Name("LW")
    STROKE_CAP_STYLE = Name("LC")
    STROKE_JOIN_STYLE = Name("LJ")
    STROKE_MITER_LIMIT = Name("ML")
    STROKE_DASH_PATTERN = Name("D")  # array of array, number, e.g. [[1 1] 0]
    SOFT_MASK = Name("SMask")


class Corner(CoerciveEnum):
    TOP_RIGHT = "TOP_RIGHT"
    TOP_LEFT = "TOP_LEFT"
    BOTTOM_RIGHT = "BOTTOM_RIGHT"
    BOTTOM_LEFT = "BOTTOM_LEFT"


class FontDescriptorFlags(Flag):
    """An enumeration of the flags for the unsigned 32-bit integer entry in the font descriptor specifying various
    characteristics of the font. Bit positions are numbered from 1 (low-order) to 32 (high-order).
    """

    FIXED_PITCH = 0x0000001
    """
    "All glyphs have the same width (as opposed to proportional or
    variable-pitch fonts, which have different widths."
    """

    SYMBOLIC = 0x0000004
    """
    "Font contains glyphs outside the Adobe standard Latin character set.
    This flag and the Nonsymbolic flag shall not both be set or both be clear."
    """

    ITALIC = 0x0000040
    """
    "Glyphs have dominant vertical strokes that are slanted."
    """

    FORCE_BOLD = 0x0040000
    """
    "The flag shall determine whether bold glyphs shall be painted with extra pixels even at very
    small text sizes by a conforming reader. If set, features of bold glyphs may be thickened at
    small text sizes."
    """


class AccessPermission(IntFlag):
    "Permission flags will translate as an integer on the encryption dictionary"

    PRINT_LOW_RES = 0b000000000100
    "Print the document"

    MODIFY = 0b000000001000
    "Modify the contents of the document"

    COPY = 0b000000010000
    "Copy or extract text and graphics from the document"

    ANNOTATION = 0b000000100000
    "Add or modify text annotations"

    FILL_FORMS = 0b000100000000
    "Fill in existing interactive form fields"

    COPY_FOR_ACCESSIBILITY = 0b001000000000
    "Extract text and graphics in support of accessibility to users with disabilities"

    ASSEMBLE = 0b010000000000
    "Insert, rotate or delete pages and create bookmarks or thumbnail images"

    PRINT_HIGH_RES = 0b100000000000
    "Print document at the highest resolution"

    @classmethod
    def all(cls) -> int:
        "All flags enabled"
        result = 0
        for permission in list(AccessPermission):
            access_permission = permission
            result = result | access_permission.value
        return result

    @classmethod
    def none(cls) -> int:
        "All flags disabled"
        return 0


class EncryptionMethod(Enum):
    "Algorithm to be used to encrypt the document"

    NO_ENCRYPTION = 0
    RC4 = 1
    AES_128 = 2
    AES_256 = 3


class TextDirection(CoerciveEnum):
    "Text rendering direction for text shaping"

    LTR = intern("LTR")
    "left to right"

    RTL = intern("RTL")
    "right to left"

    TTB = intern("TTB")
    "top to bottom"

    BTT = intern("BTT")
    "bottom to top"


class OutputIntentSubType(CoerciveEnum):
    "Definition for Output Intent Subtypes"

    PDFX = Name("GTS_PDFX")
    "PDF/X-1a which is based upon CMYK processing"

    PDFA = Name("GTS_PDFA1")
    "PDF/A (ISO 19005) standard to produce RGB output"

    ISOPDF = Name("ISO_PDFE1")
    "ISO_PDFE1 PDF/E standards (ISO 24517, all parts)"


class PageLabelStyle(CoerciveEnum):
    "Style of the page label"

    NUMBER = intern("D")
    "decimal arabic numerals"

    UPPER_ROMAN = intern("R")
    "uppercase roman numerals"

    LOWER_ROMAN = intern("r")
    "lowercase roman numerals"

    UPPER_LETTER = intern("A")
    "uppercase letters A to Z, AA to ZZ, AAA to ZZZ and so on"

    LOWER_LETTER = intern("a")
    "uppercase letters a to z, aa to zz, aaa to zzz and so on"

    NONE = None
    "no label"


class Duplex(CoerciveEnum):
    "The paper handling option that shall be used when printing the file from the print dialog."

    SIMPLEX = Name("Simplex")
    "Print single-sided"

    DUPLEX_FLIP_SHORT_EDGE = Name("DuplexFlipShortEdge")
    "Duplex and flip on the short edge of the sheet"

    DUPLEX_FLIP_LONG_EDGE = Name("DuplexFlipLongEdge")
    "Duplex and flip on the long edge of the sheet"


class PageBoundaries(CoerciveEnum):
    ART_BOX = Name("ArtBox")
    BLEED_BOX = Name("BleedBox")
    CROP_BOX = Name("CropBox")
    MEDIA_BOX = Name("MediaBox")
    TRIM_BOX = Name("TrimBox")


class PageOrientation(CoerciveEnum):
    PORTRAIT = intern("P")
    LANDSCAPE = intern("L")

    @classmethod
    def coerce(  # pyright: ignore[reportIncompatibleMethodOverride]
        cls, value: Union["PageOrientation", str], case_sensitive: bool = False
    ) -> "PageOrientation":
        if isinstance(value, str):
            value = value.upper()
        return super(cls, cls).coerce(
            value, case_sensitive  # pyright: ignore[reportArgumentType]
        )


class PDFResourceType(Enum):
    EXT_G_STATE = intern("ExtGState")
    COLOR_SPACE = intern("ColorSpace")
    PATTERN = intern("Pattern")
    SHADING = intern("Shading")
    X_OBJECT = intern("XObject")
    FONT = intern("Font")
    PROC_SET = intern("ProcSet")
    PROPERTIES = intern("Properties")


class GradientUnits(CoerciveEnum):
    "Specifies the coordinate system for gradients."

    OBJECT_BOUNDING_BOX = "objectBoundingBox"
    " Coordinates are expressed as fractions of the painted object's bounding box (0..1 in each axis)."

    USER_SPACE_ON_USE = "userSpaceOnUse"
    " Coordinates are in the current page space."


class GradientSpreadMethod(CoerciveEnum):
    "Specifies how to fill the area outside the gradient's start and end points."

    PAD = "pad"
    " The color at the start or end of the gradient is extended to fill the area before or after the gradient."

    REFLECT = "reflect"
    " The gradient pattern is repeated in reverse order (mirrored) to fill the area before or after the gradient."

    REPEAT = "repeat"
    " The gradient pattern is repeated in the same order to fill the area before or after the gradient."


class DocumentCompliance(Enum):
    """
    Type of compliance enforcement that can be applied to a document.
    Limited to PDF/A at the moment, but extendable to other standards like:
        - PDF/E (Engineering PDFs)
        - PDF/UA (PDF Universal Accessibility)
        - PDF/X (Graphics Exchange PDFs)
    """

    PDFA_1B = ("PDFA", 1, "B")
    PDFA_2B = ("PDFA", 2, "B")
    PDFA_2U = ("PDFA", 2, "U")
    PDFA_3B = ("PDFA", 3, "B")
    PDFA_3U = ("PDFA", 3, "U")
    PDFA_4 = ("PDFA", 4, None)
    PDFA_4E = ("PDFA", 4, "E")
    PDFA_4F = ("PDFA", 4, "F")

    @property
    def profile(self) -> str:
        return str(self.value[0])

    @property
    def part(self) -> int:
        return int(self.value[1])

    @property
    def conformance(self) -> Optional[str]:
        return str(self.value[2]) if self.value[2] is not None else None

    @property
    def label(self) -> str:
        profile = "PDF/A" if self.profile == "PDFA" else self.profile
        return f"{profile}-{self.part}{self.conformance if self.conformance else ''}"

    def __str__(self) -> str:
        return (
            f"{self.profile}_{self.part}{self.conformance if self.conformance else ''}"
        )

    @classmethod
    def coerce(cls, value: Union["DocumentCompliance", str]) -> "DocumentCompliance":
        if isinstance(value, cls):
            return value
        if isinstance(value, str):
            key = value.upper()
            for m in cls:
                if m.name.upper() == key:  # PDFA_2U
                    return m
                if m.label.upper() == key:  # PDF/A-2U
                    return m
        raise ValueError(f"Cannot coerce {value!r} to {cls.__name__}")


class AssociatedFileRelationship(CoerciveEnum):
    """Represents the association between an embedded file and the content on the PDF"""

    SOURCE = intern("Source")
    "The file is the original source material of the content"

    DATA = intern("Data")
    """
    The file has the information used to produce the associated object.
    e.g.: the data used to produce a table or a graph
    """

    ALTERNATIVE = intern("Alternative")
    "The file has an alternative representation of the content"

    SUPPLEMENT = intern("Supplement")
    """
    The file has a supplemental representation of the original source
    or data that may be more easily consumable
    """

    ENCRYPTED_PAYLOAD = intern("EncryptedPayload")
    """
    The file is an encrypted payload document that should be displayed
    to the user if the PDF processor has the cryptographic filter
    needed to decrypt the document
    """

    FORM_DATA = intern("FormData")
    "The file has the data associated with the interactive form in this document"

    SCHEMA = intern("Schema")
    "The file is a schema definition for the associated object"

    UNSPECIFIED = intern("Unspecified")
    """
    Shall be used when the relationship is not known
    or cannot be described using one of the other values
    """