File: drawing_primitives.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 (1127 lines) | stat: -rw-r--r-- 37,982 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
"""
Core drawing primitives for fpdf2.

This module defines the fundamental data structures used throughout the
drawing API, including:

- Color models: ``DeviceRGB``, ``DeviceGray``, ``DeviceCMYK``
- Geometric primitives: ``Point``
- Transformation matrices: ``Transform``

These classes are intentionally lightweight and self-contained so they can be
safely imported from any other drawing-related module without creating circular
dependencies.

All higher-level drawing features (paths, patterns, gradients, etc.) build on
top of these primitives.
"""

import math
from collections.abc import Sequence
from dataclasses import dataclass
from typing import (
    TYPE_CHECKING,
    Callable,
    Iterator,
    Optional,
    TypeAlias,
    TypeVar,
    Union,
)

from .util import Number, NumberClass, number_to_str

if TYPE_CHECKING:
    from .drawing import Renderable

__pdoc__: dict[str, bool | str] = {}
__pdoc__ = {"force_nodocument": False}

Color: TypeAlias = Union["DeviceRGB", "DeviceGray", "DeviceCMYK"]
ColorInput: TypeAlias = Number | Color | str | Sequence[Number]
F = TypeVar("F", bound=Callable[..., object])


def force_nodocument(item: F) -> F:
    """A decorator that forces pdoc not to document the decorated item (class or method)"""
    __pdoc__[item.__qualname__] = False
    return item


@force_nodocument
def force_document(item: F) -> F:
    """A decorator that forces pdoc to document the decorated item (class or method)"""
    __pdoc__[item.__qualname__] = True
    return item


def check_range(value: Number, minimum: float = 0.0, maximum: float = 1.0) -> Number:
    if not minimum <= value <= maximum:
        raise ValueError(f"{value} not in range [{minimum}, {maximum}]")

    return value


# We allow passing alpha in as None instead of a numeric quantity, which signals to the
# rendering procedure not to emit an explicit alpha field for this graphics state,
# causing it to be inherited from the parent.


@dataclass(frozen=True, slots=True, init=False)
class DeviceRGB:
    """A class representing a PDF DeviceRGB color."""

    # This follows a common PDF drawing operator convention where the operand is upcased
    # to apply to stroke and downcased to apply to fill.

    # This could be more manually specified by  `CS`/`cs` to set the color space(e.g. to
    # `/DeviceRGB`) and `SC`/`sc` to set the color parameters. The documentation isn't
    # perfectly clear on this front, but it appears that these cannot be set in the
    # current graphics state dictionary and instead is set in the current page resource
    # dictionary. fpdf appears to only generate a single resource dictionary for the
    # entire document, and even if it created one per page, it would still be a lot
    # clunkier to try to use that.

    # Because PDF hates me, personally, the opacity of the drawing HAS to be specified
    # in the current graphics state dictionary and does not exist as a standalone
    # directive.

    r: float
    g: float
    b: float
    a: Optional[float]

    def __init__(
        self,
        r: Number,
        g: Number,
        b: Number,
        a: Optional[Number] = None,
    ) -> None:
        # normalize everything to float for internal storage
        object.__setattr__(self, "r", float(check_range(r)))
        object.__setattr__(self, "g", float(check_range(g)))
        object.__setattr__(self, "b", float(check_range(b)))
        object.__setattr__(self, "a", float(check_range(a)) if a is not None else None)

    @property
    def operator(self) -> str:
        "The PDF drawing operator used to specify this type of color."
        return "rg"

    @property
    def colors(self) -> tuple[float, float, float]:
        "The color components as a tuple in order `(r, g, b)` with alpha omitted, in range 0-1."
        return (self.r, self.g, self.b)

    @property
    def colors255(self) -> tuple[float, float, float]:
        "The color components as a tuple in order `(r, g, b)` with alpha omitted, in range 0-255."
        return (255 * self.r, 255 * self.g, 255 * self.b)

    def serialize(self) -> str:
        return " ".join(number_to_str(val) for val in self.colors) + f" {self.operator}"

    def is_achromatic(self) -> bool:
        return abs(self.r - self.g) < 1e-9 and abs(self.g - self.b) < 1e-9

    def to_gray(self) -> "DeviceGray":
        # sRGB luminance
        return DeviceGray(0.2126 * self.r + 0.7152 * self.g + 0.0722 * self.b)


__pdoc__["DeviceRGB.r"] = "The red color component. Must be in the interval [0, 1]."
__pdoc__["DeviceRGB.g"] = "The green color component. Must be in the interval [0, 1]."
__pdoc__["DeviceRGB.b"] = "The blue color component. Must be in the interval [0, 1]."
__pdoc__["DeviceRGB.a"] = """
The alpha color component (i.e. opacity). Must be `None` or in the interval [0, 1].

An alpha value of 0 makes the color fully transparent, and a value of 1 makes it fully
opaque. If `None`, the color will be interpreted as not specifying a particular
transparency rather than specifying fully transparent or fully opaque.
"""


@dataclass(frozen=True, slots=True, init=False)
class DeviceGray:
    """A class representing a PDF DeviceGray color."""

    g: float
    a: Optional[float]

    def __init__(
        self,
        g: Number,
        a: Optional[Number] = None,
    ) -> None:
        # normalize everything to float for internal storage
        object.__setattr__(self, "g", float(check_range(g)))
        object.__setattr__(self, "a", float(check_range(a)) if a is not None else None)

    @property
    def operator(self) -> str:
        """The PDF drawing operator used to specify this type of color."""
        return "g"

    @property
    def colors(self) -> tuple[float, float, float]:
        "The color components as a tuple in order (r, g, b) with alpha omitted, in range 0-1."
        return self.g, self.g, self.g

    @property
    def colors255(self) -> tuple[float, float, float]:
        "The color components as a tuple in order `(r, g, b)` with alpha omitted, in range 0-255."
        return 255 * self.g, 255 * self.g, 255 * self.g

    def serialize(self) -> str:
        return f"{number_to_str(self.g)} {self.operator}"


__pdoc__["DeviceGray.g"] = """
The gray color component. Must be in the interval [0, 1].

A value of 0 represents black and a value of 1 represents white.
"""
__pdoc__["DeviceGray.a"] = """
The alpha color component (i.e. opacity). Must be `None` or in the interval [0, 1].

An alpha value of 0 makes the color fully transparent, and a value of 1 makes it fully
opaque. If `None`, the color will be interpreted as not specifying a particular
transparency rather than specifying fully transparent or fully opaque.
"""


@dataclass(frozen=True, slots=True, init=False)
class DeviceCMYK:
    """A class representing a PDF DeviceCMYK color."""

    c: float
    m: float
    y: float
    k: float
    a: Optional[float]

    def __init__(
        self,
        c: Number,
        m: Number,
        y: Number,
        k: Number,
        a: Optional[Number] = None,
    ) -> None:
        # normalize everything to float for internal storage
        object.__setattr__(self, "c", float(check_range(c)))
        object.__setattr__(self, "m", float(check_range(m)))
        object.__setattr__(self, "y", float(check_range(y)))
        object.__setattr__(self, "k", float(check_range(k)))
        object.__setattr__(self, "a", float(check_range(a)) if a is not None else None)

    @property
    def operator(self) -> str:
        "The PDF drawing operator used to specify this type of color."
        return "k"

    @property
    def colors(self) -> tuple[float, float, float, float]:
        "The color components as a tuple in order (c, m, y, k) with alpha omitted, in range 0-1."
        return self.c, self.m, self.y, self.k

    def serialize(self) -> str:
        return " ".join(number_to_str(val) for val in self.colors) + f" {self.operator}"


__pdoc__["DeviceCMYK.OPERATOR"] = False
__pdoc__["DeviceCMYK.c"] = "The cyan color component. Must be in the interval [0, 1]."
__pdoc__["DeviceCMYK.m"] = (
    "The magenta color component. Must be in the interval [0, 1]."
)
__pdoc__["DeviceCMYK.y"] = "The yellow color component. Must be in the interval [0, 1]."
__pdoc__["DeviceCMYK.k"] = "The black color component. Must be in the interval [0, 1]."
__pdoc__["DeviceCMYK.a"] = """
The alpha color component (i.e. opacity). Must be `None` or in the interval [0, 1].

An alpha value of 0 makes the color fully transparent, and a value of 1 makes it fully
opaque. If `None`, the color will be interpreted as not specifying a particular
transparency rather than specifying fully transparent or fully opaque.
"""


def rgb8(
    r: Number, g: Number, b: Number, a: Optional[Number] = None
) -> DeviceGray | DeviceRGB:
    """
    Produce a DeviceRGB color from the given 8-bit RGB values.

    Args:
        r (Number): red color component. Must be in the interval [0, 255].
        g (Number): green color component. Must be in the interval [0, 255].
        b (Number): blue color component. Must be in the interval [0, 255].
        a (Optional[Number]): alpha component. Must be `None` or in the interval
            [0, 255]. 0 is fully transparent, 255 is fully opaque

    Returns:
        DeviceRGB color representation.

    Raises:
        ValueError: if any components are not in their valid interval.
    """
    if a is None:
        if r == g == b:
            return DeviceGray(float(r) / 255.0)
    else:
        a = float(a) / 255.0

    return DeviceRGB(float(r) / 255.0, float(g) / 255.0, float(b) / 255.0, a)


def gray8(g: Number, a: Optional[Number] = None) -> DeviceGray:
    """
    Produce a DeviceGray color from the given 8-bit gray value.

    Args:
        g (Number): gray color component. Must be in the interval [0, 255]. 0 is black,
            255 is white.
        a (Optional[Number]): alpha component. Must be `None` or in the interval
            [0, 255]. 0 is fully transparent, 255 is fully opaque

    Returns:
        DeviceGray color representation.

    Raises:
        ValueError: if any components are not in their valid interval.
    """
    if a is not None:
        a = float(a) / 255.0

    return DeviceGray(float(g) / 255.0, a)


def convert_to_device_color(
    r: Number | Color | str | Sequence[Number] | DeviceCMYK | DeviceGray | DeviceRGB,
    g: Number = -1,
    b: Number = -1,
) -> DeviceGray | DeviceRGB | DeviceCMYK:
    if isinstance(r, (DeviceCMYK, DeviceGray, DeviceRGB)):
        return r
    if isinstance(r, str):
        if r.startswith("#"):
            return color_from_hex_string(r)
        raise ValueError(f"Cannot convert string {r} to a color")
    if isinstance(r, Sequence):
        assert not isinstance(r, str)
        r, g, b = r
    if (r, g, b) == (0, 0, 0) or g == -1:
        return DeviceGray(r / 255)
    return DeviceRGB(r / 255, g / 255, b / 255)


def cmyk8(
    c: Number, m: Number, y: Number, k: Number, a: Optional[Number] = None
) -> DeviceCMYK:
    """
    Produce a DeviceCMYK color from the given 8-bit CMYK values.

    Args:
        c (Number): red color component. Must be in the interval [0, 255].
        m (Number): green color component. Must be in the interval [0, 255].
        y (Number): blue color component. Must be in the interval [0, 255].
        k (Number): blue color component. Must be in the interval [0, 255].
        a (Optional[Number]): alpha component. Must be `None` or in the interval
            [0, 255]. 0 is fully transparent, 255 is fully opaque

    Returns:
        DeviceCMYK color representation.

    Raises:
        ValueError: if any components are not in their valid interval.
    """
    if a is not None:
        a = float(a) / 255.0

    return DeviceCMYK(
        float(c) / 255.0, float(m) / 255.0, float(y) / 255.0, float(k) / 255.0, a
    )


def color_from_hex_string(hexstr: str) -> DeviceRGB | DeviceGray:
    """
    Parse an RGB color from a css-style 8-bit hexadecimal color string.

    Args:
        hexstr (str): of the form `#RGB`, `#RGBA`, `#RRGGBB`, or `#RRGGBBAA` (case
            insensitive). Must include the leading octothorp. Forms omitting the alpha
            field are interpreted as not specifying the opacity, so it will not be
            explicitly set.

            An alpha value of `00` is fully transparent and `FF` is fully opaque.

    Returns:
        DeviceRGB representation of the color.
    """
    if not isinstance(hexstr, str):
        raise TypeError(f"{hexstr} is not of type str")

    if not hexstr.startswith("#"):
        raise ValueError(f"{hexstr} does not start with #")

    hlen = len(hexstr)

    if hlen == 4:  # #RGB
        r = int(hexstr[1] * 2, 16)
        g = int(hexstr[2] * 2, 16)
        b = int(hexstr[3] * 2, 16)
        a = None

    elif hlen == 5:  # #RGBA
        r = int(hexstr[1] * 2, 16)
        g = int(hexstr[2] * 2, 16)
        b = int(hexstr[3] * 2, 16)
        a = int(hexstr[4] * 2, 16)

    elif hlen == 7:  # #RRGGBB
        r = int(hexstr[1:3], 16)
        g = int(hexstr[3:5], 16)
        b = int(hexstr[5:7], 16)
        a = None

    elif hlen == 9:  # #RRGGBBAA
        r = int(hexstr[1:3], 16)
        g = int(hexstr[3:5], 16)
        b = int(hexstr[5:7], 16)
        a = int(hexstr[7:9], 16)

    else:
        raise ValueError(f"{hexstr} could not be interpreted as a RGB(A) hex string")

    return rgb8(r, g, b, a)


def color_from_rgb_string(rgbstr: str) -> DeviceRGB | DeviceGray:
    """
    Parse an RGB color from a css-style rgb(R, G, B, A) color string.

    Args:
        rgbstr (str): of the form `rgb(R, G, B)` or `rgb(R, G, B, A)`.

    Returns:
        DeviceRGB representation of the color.
    """
    if not isinstance(rgbstr, str):
        raise TypeError(f"{rgbstr} is not of type str")

    rgbstr = rgbstr.replace(" ", "")

    if not rgbstr.startswith("rgb(") or not rgbstr.endswith(")"):
        raise ValueError(f"{rgbstr} does not follow the expected rgb(...) format")

    rgbstr = rgbstr[4:-1]
    colors = rgbstr.split(",")

    if len(colors) == 3:
        r, g, b = (int(c) for c in colors)
        return rgb8(r, g, b, a=None)

    if len(colors) == 4:
        return rgb8(*[int(c) for c in colors])

    raise ValueError(f"{rgbstr} could not be interpreted as a rgb(R, G, B[, A]) color")


@dataclass(frozen=True, slots=True)
class Point:
    """
    An x-y coordinate pair within the two-dimensional coordinate frame.
    """

    x: float
    """The abscissa of the point."""

    y: float
    """The ordinate of the point."""

    def render(self) -> str:
        """Render the point to the string `"x y"` for emitting to a PDF."""

        return f"{number_to_str(self.x)} {number_to_str(self.y)}"

    def dot(self, other: "Point") -> float:
        """
        Compute the dot product of two points.

        Args:
            other (Point): the point with which to compute the dot product.

        Returns:
            The scalar result of the dot product computation.

        Raises:
            TypeError: if `other` is not a `Point`.
        """
        if not isinstance(other, Point):
            raise TypeError(f"cannot dot with {other!r}")

        return self.x * other.x + self.y * other.y

    def angle(self, other: "Point") -> float:
        """
        Compute the angle between two points (interpreted as vectors from the origin).

        The return value is in the interval (-pi, pi]. Sign is dependent on ordering,
        with clockwise angle travel considered to be positive due to the orientation of
        the coordinate frame basis vectors (i.e. the angle between `(1, 0)` and `(0, 1)`
        is `+pi/2`, the angle between `(1, 0)` and `(0, -1)` is `-pi/2`, and the angle
        between `(0, -1)` and `(1, 0)` is `+pi/2`).

        Args:
            other (Point): the point to compute the angle sweep toward.

        Returns:
            The scalar angle between the two points **in radians**.

        Raises:
            TypeError: if `other` is not a `Point`.
        """

        if not isinstance(other, Point):
            raise TypeError(f"cannot compute angle with {other!r}")

        signifier = (self.x * other.y) - (self.y * other.x)
        sign = (signifier >= 0) - (signifier < 0)
        if self.mag() * other.mag() == 0:  # Prevent division by 0
            return 0.0
        return sign * math.acos(round(self.dot(other) / (self.mag() * other.mag()), 8))

    def mag(self) -> float:
        """
        Compute the Cartesian distance from this point to the origin

        This is the same as computing the magnitude of the vector represented by this
        point.

        Returns:
            The scalar result of the distance computation.
        """
        return math.hypot(self.x, self.y)

    @force_document
    def __add__(self, other: "Point") -> "Point":
        """
        Produce the sum of two points.

        Adding two points is the same as translating the source point by interpreting
        the other point's x and y coordinates as distances.

        Args:
            other (Point): right-hand side of the infix addition operation

        Returns:
            A Point which is the sum of the two source points.
        """
        if isinstance(other, Point):
            return Point(x=self.x + other.x, y=self.y + other.y)

        return NotImplemented

    @force_document
    def __sub__(self, other: "Point") -> "Point":
        """
        Produce the difference between two points.

        Unlike addition, this is not a commutative operation!

        Args:
            other (Point): right-hand side of the infix subtraction operation

        Returns:
            A Point which is the difference of the two source points.
        """
        if isinstance(other, Point):
            return Point(x=self.x - other.x, y=self.y - other.y)

        return NotImplemented

    @force_document
    def __neg__(self) -> "Point":
        """
        Produce a point by negating this point's coordinates.

        Returns:
            A Point whose coordinates are this points coordinates negated.
        """
        return Point(x=-self.x, y=-self.y)

    @force_document
    def __mul__(self, other: Number) -> "Point":
        """
        Multiply a point by a scalar value.

        Args:
            other (Number): the scalar value by which to multiply the point's
                coordinates.

        Returns:
            A Point whose coordinates are the result of the multiplication.
        """
        if isinstance(other, NumberClass):
            float_other = float(other)
            return Point(self.x * float_other, self.y * float_other)

        return NotImplemented

    @force_document
    def __rmul__(self, other: Number) -> "Point":
        return self.__mul__(other)

    @force_document
    def __truediv__(self, other: Number) -> "Point":
        """
        Divide a point by a scalar value.

        .. note::

            Because division is not commutative, `Point / scalar` is implemented, but
            `scalar / Point` is nonsensical and not implemented.

        Args:
            other (Number): the scalar value by which to divide the point's coordinates.

        Returns:
            A Point whose coordinates are the result of the division.
        """
        if isinstance(other, NumberClass):
            return Point(self.x / float(other), self.y / float(other))

        return NotImplemented

    @force_document
    def __floordiv__(self, other: Number) -> "Point":
        """
        Divide a point by a scalar value using integer division.

        .. note::

            Because division is not commutative, `Point // scalar` is implemented, but
            `scalar // Point` is nonsensical and not implemented.

        Args:
            other (Number): the scalar value by which to divide the point's coordinates.

        Returns:
            A Point whose coordinates are the result of the division.
        """
        if isinstance(other, NumberClass):
            return Point(self.x // float(other), self.y // float(other))

        return NotImplemented

    def __iter__(self) -> Iterator[float]:
        """Iterate over point coordinates in (x, y) order."""
        yield self.x
        yield self.y

    def __len__(self) -> int:
        """Length to mimic tuple-like behaviour for compatibility."""
        return 2

    def __getitem__(self, idx: int) -> float:
        """Indexable access to coordinates in (x, y) order."""
        return (self.x, self.y)[idx]

    # no __r(true|floor)div__ because division is not commutative!

    @force_document
    def __matmul__(self, other: "Transform") -> "Point":
        """
        Transform a point with the given transform matrix.

        .. note::
            This operator is only implemented for Transforms. This transform is not
            commutative, so `Point @ Transform` is implemented, but `Transform @ Point`
            is not implemented (technically speaking, the current implementation is
            commutative because of the way points and transforms are represented, but
            if that representation were to change this operation could stop being
            commutative)

        Args:
            other (Transform): the transform to apply to the point

        Returns:
            A Point whose coordinates are the result of applying the transform.
        """
        if isinstance(other, Transform):
            return Point(
                x=other.a * self.x + other.c * self.y + other.e,
                y=other.b * self.x + other.d * self.y + other.f,
            )

        return NotImplemented

    def __str__(self) -> str:
        return f"(x={number_to_str(self.x)}, y={number_to_str(self.y)})"


@dataclass(frozen=True, slots=True)
class Transform:
    """
    A representation of an affine transformation matrix for 2D shapes.

    The actual matrix is:

    ```
                        [ a b 0 ]
    [x' y' 1] = [x y 1] [ c d 0 ]
                        [ e f 1 ]
    ```

    Complex transformation operations can be composed via a sequence of simple
    transformations by performing successive matrix multiplication of the simple
    transformations.

    For example, scaling a set of points around a specific center point can be
    represented by a translation-scale-translation sequence, where the first
    translation translates the center to the origin, the scale transform scales the
    points relative to the origin, and the second translation translates the points
    back to the specified center point. Transform multiplication is performed using
    python's dedicated matrix multiplication operator, `@`

    The semantics of this representation mean composed transformations are specified
    left-to-right in order of application (some other systems provide transposed
    representations, in which case the application order is right-to-left).

    For example, to rotate the square `(1,1) (1,3) (3,3) (3,1)` 45 degrees clockwise
    about its center point (which is `(2,2)`) , the translate-rotate-translate
    process described above may be applied:

    ```python
    rotate_centered = (
        Transform.translation(-2, -2)
        @ Transform.rotation_d(45)
        @ Transform.translation(2, 2)
    )
    ```

    Instances of this class provide a chaining API, so the above transform could also be
    constructed as follows:

    ```python
    rotate_centered = Transform.translation(-2, -2).rotate_d(45).translate(2, 2)
    ```

    Or, because the particular operation of performing some transformations about a
    specific point is pretty common,

    ```python
    rotate_centered = Transform.rotation_d(45).about(2, 2)
    ```

    By convention, this class provides class method constructors following noun-ish
    naming (`translation`, `scaling`, `rotation`, `shearing`) and instance method
    manipulations following verb-ish naming (`translate`, `scale`, `rotate`, `shear`).
    """

    a: float
    b: float
    c: float
    d: float
    e: float
    f: float

    # compact representation of an affine transformation matrix for 2D shapes.
    # The actual matrix is:
    #                     [ A B 0 ]
    # [x' y' 1] = [x y 1] [ C D 0 ]
    #                     [ E F 1 ]
    # The identity transform is 1 0 0 1 0 0

    def __iter__(self) -> Iterator[float]:
        """Iterate over matrix components in (a, b, c, d, e, f) order."""
        yield self.a
        yield self.b
        yield self.c
        yield self.d
        yield self.e
        yield self.f

    def __len__(self) -> int:
        """Length to mimic tuple-like behaviour for compatibility."""
        return 6

    def __getitem__(self, idx: int) -> float:
        """Indexable access to matrix components in (a, b, c, d, e, f) order."""
        return (self.a, self.b, self.c, self.d, self.e, self.f)[idx]

    @classmethod
    def identity(cls) -> "Transform":
        """
        Create a transform representing the identity transform.

        The identity transform is a no-op.
        """
        return cls(1, 0, 0, 1, 0, 0)

    @classmethod
    def translation(cls, x: Number, y: Number) -> "Transform":
        """
        Create a transform that performs translation.

        Args:
            x (Number): distance to translate points along the x (horizontal) axis.
            y (Number): distance to translate points along the y (vertical) axis.

        Returns:
            A Transform representing the specified translation.
        """

        return cls(1, 0, 0, 1, float(x), float(y))

    @classmethod
    def scaling(cls, x: Number, y: Optional[Number] = None) -> "Transform":
        """
        Create a transform that performs scaling.

        Args:
            x (Number): scaling ratio in the x (horizontal) axis. A value of 1
                results in no scale change in the x axis.
            y (Number): optional scaling ratio in the y (vertical) axis. A value of 1
                results in no scale change in the y axis. If this value is omitted, it
                defaults to the value provided to the `x` argument.

        Returns:
            A Transform representing the specified scaling.
        """
        if y is None:
            y = x

        return cls(float(x), 0, 0, float(y), 0, 0)

    @classmethod
    def rotation(cls, theta: Number) -> "Transform":
        """
        Create a transform that performs rotation.

        Args:
            theta (Number): the angle **in radians** by which to rotate. Positive
                values represent clockwise rotations.

        Returns:
            A Transform representing the specified rotation.

        """
        return cls(
            math.cos(theta), math.sin(theta), -math.sin(theta), math.cos(theta), 0, 0
        )

    @classmethod
    def rotation_d(cls, theta_d: Number) -> "Transform":
        """
        Create a transform that performs rotation **in degrees**.

        Args:
            theta_d (Number): the angle **in degrees** by which to rotate. Positive
                values represent clockwise rotations.

        Returns:
            A Transform representing the specified rotation.

        """
        return cls.rotation(math.radians(theta_d))

    @classmethod
    def shearing(cls, x: Number, y: Optional[Number] = None) -> "Transform":
        """
        Create a transform that performs shearing (not of sheep).

        Args:
            x (Number): The amount to shear along the x (horizontal) axis.
            y (Number): Optional amount to shear along the y (vertical) axis. If omitted,
                this defaults to the value provided to the `x` argument.

        Returns:
            A Transform representing the specified shearing.

        """
        if y is None:
            y = x
        return cls(1, float(y), float(x), 1, 0, 0)

    @classmethod
    def skewing(cls, ax: Number = 0, ay: Optional[Number] = None) -> "Transform":
        """
        Create a skew (shear) transform using angles **in radians**.

        Args:
            ax (Number): skew angle along the X axis (radians).
                Positive ax produces x' = x + tan(ax) * y
            ay (Number): optional skew angle along the Y axis (radians).
                Positive ay produces y' = y + tan(ay) * x
                If omitted, defaults to the value of `ax`.

        Returns:
            A Transform representing the specified skew.
        """
        if ay is None:
            ay = ax
        return cls(1, math.tan(float(ay)), math.tan(float(ax)), 1, 0, 0)

    @classmethod
    def skewing_d(cls, ax_d: Number = 0, ay_d: Optional[Number] = None) -> "Transform":
        """
        Create a skew (shear) transform using angles **in degrees**.

        Args:
            ax_d (Number): skew angle along X in degrees.
            ay_d (Number): optional skew angle along Y in degrees. If omitted, defaults to ax_d.

        Returns:
            A Transform representing the specified skew.

        Raises:
            ValueError: if an angle is too close to 90° + k·180° (infinite shear).
        """
        if ay_d is None:
            ay_d = ax_d
        ax = math.radians(float(ax_d))
        ay = math.radians(float(ay_d))
        # Guard against tan() blow-ups near ±90° (+ k·180°)
        eps = 1e-12
        if abs(math.cos(ax)) < eps or abs(math.cos(ay)) < eps:
            raise ValueError("Skew angle produces infinite shear (near 90° + k·180°).")
        return cls.skewing(ax, ay)

    def translate(self, x: Number, y: Number) -> "Transform":
        """
        Produce a transform by composing the current transform with a translation.

        .. note::
            Transforms are immutable, so this returns a new transform rather than
            mutating self.

        Args:
            x (Number): distance to translate points along the x (horizontal) axis.
            y (Number): distance to translate points along the y (vertical) axis.

        Returns:
            A Transform representing the composed transform.
        """
        return self @ Transform.translation(x, y)

    def scale(self, x: Number, y: Optional[Number] = None) -> "Transform":
        """
        Produce a transform by composing the current transform with a scaling.

        .. note::
            Transforms are immutable, so this returns a new transform rather than
            mutating self.

        Args:
            x (Number): scaling ratio in the x (horizontal) axis. A value of 1
                results in no scale change in the x axis.
            y (Number): optional scaling ratio in the y (vertical) axis. A value of 1
                results in no scale change in the y axis. If this value is omitted, it
                defaults to the value provided to the `x` argument.

        Returns:
            A Transform representing the composed transform.
        """
        return self @ Transform.scaling(x, y)

    def rotate(self, theta: Number) -> "Transform":
        """
        Produce a transform by composing the current transform with a rotation.

        .. note::
            Transforms are immutable, so this returns a new transform rather than
            mutating self.

        Args:
            theta (Number): the angle **in radians** by which to rotate. Positive
                values represent clockwise rotations.

        Returns:
            A Transform representing the composed transform.
        """
        return self @ Transform.rotation(theta)

    def rotate_d(self, theta_d: Number) -> "Transform":
        """
        Produce a transform by composing the current transform with a rotation
        **in degrees**.

        .. note::
            Transforms are immutable, so this returns a new transform rather than
            mutating self.

        Args:
            theta_d (Number): the angle **in degrees** by which to rotate. Positive
                values represent clockwise rotations.

        Returns:
            A Transform representing the composed transform.
        """
        return self @ Transform.rotation_d(theta_d)

    def shear(self, x: Number, y: Optional[Number] = None) -> "Transform":
        """
        Produce a transform by composing the current transform with a shearing.

        .. note::
            Transforms are immutable, so this returns a new transform rather than
            mutating self.

        Args:
            x (Number): The amount to shear along the x (horizontal) axis.
            y (Number): Optional amount to shear along the y (vertical) axis. If omitted,
                this defaults to the value provided to the `x` argument.

        Returns:
            A Transform representing the composed transform.
        """
        return self @ Transform.shearing(x, y)

    def skew(self, ax: Number = 0, ay: Optional[Number] = None) -> "Transform":
        """Compose with a skew (radians)."""
        return self @ Transform.skewing(ax, ay)

    def skew_d(self, ax_d: Number = 0, ay_d: Optional[Number] = None) -> "Transform":
        """Compose with a skew (degrees)."""
        return self @ Transform.skewing_d(ax_d, ay_d)

    def about(self, x: Number, y: Number) -> "Transform":
        """
        Bracket the given transform in a pair of translations to make it appear about a
        point that isn't the origin.

        This is a useful shorthand for performing a transform like a rotation around the
        center point of an object that isn't centered at the origin.

        .. note::
            Transforms are immutable, so this returns a new transform rather than
            mutating self.

        Args:
            x (Number): the point along the x (horizontal) axis about which to transform.
            y (Number): the point along the y (vertical) axis about which to transform.

        Returns:
            A Transform representing the composed transform.
        """
        return Transform.translation(-x, -y) @ self @ Transform.translation(x, y)

    def inverse(self) -> "Transform":
        """
        Produce a transform that is the inverse of this transform.

        Returns:
            A Transform representing the inverse of this transform.

        Raises:
            ValueError: if the transform is not invertible.
        """
        det = self.a * self.d - self.b * self.c
        if det == 0:
            raise ValueError("Transform is not invertible")

        return Transform(
            a=self.d / det,
            b=-self.b / det,
            c=-self.c / det,
            d=self.a / det,
            e=(self.c * self.f - self.d * self.e) / det,
            f=(self.b * self.e - self.a * self.f) / det,
        )

    @force_document
    def __mul__(self, other: Number) -> "Transform":
        """
        Multiply the individual transform parameters by a scalar value.

        Args:
            other (Number): the scalar value by which to multiply the parameters

        Returns:
            A Transform with the modified parameters.
        """
        if isinstance(other, NumberClass):
            other = float(other)
            return Transform(
                a=self.a * other,
                b=self.b * other,
                c=self.c * other,
                d=self.d * other,
                e=self.e * other,
                f=self.f * other,
            )

        return NotImplemented

    @force_document
    def __rmul__(self, other: Number) -> "Transform":
        # scalar multiplication is commutative
        return self.__mul__(other)

    @force_document
    def __matmul__(self, other: "Transform") -> "Transform":
        """
        Compose two transforms into a single transform.

        Args:
            other (Transform): the right-hand side transform of the infix operator.

        Returns:
            A Transform representing the composed transform.
        """
        if isinstance(other, Transform):
            return self.__class__(
                a=self.a * other.a + self.b * other.c,
                b=self.a * other.b + self.b * other.d,
                c=self.c * other.a + self.d * other.c,
                d=self.c * other.b + self.d * other.d,
                e=self.e * other.a + self.f * other.c + other.e,
                f=self.e * other.b + self.f * other.d + other.f,
            )

        return NotImplemented

    def render(self, last_item: "Renderable") -> tuple[str, "Renderable"]:
        """
        Render the transform to its PDF output representation.

        Args:
            last_item: the last path element this transform applies to

        Returns:
            A tuple of `(str, last_item)`. `last_item` is returned unchanged.
        """
        return (
            f"{number_to_str(self.a)} {number_to_str(self.b)} "
            f"{number_to_str(self.c)} {number_to_str(self.d)} "
            f"{number_to_str(self.e)} {number_to_str(self.f)} cm",
            last_item,
        )

    def __str__(self) -> str:
        return (
            f"transform: ["
            f"{number_to_str(self.a)} {number_to_str(self.b)} 0; "
            f"{number_to_str(self.c)} {number_to_str(self.d)} 0; "
            f"{number_to_str(self.e)} {number_to_str(self.f)} 1]"
        )

    def row_norms(self) -> tuple[float, float]:
        """
        Returns (sqrt(a² + c²), sqrt(b² + d²)), i.e. the Euclidean norms of
        those rows. These values bound how much the transform can stretch geometry along the
        device X and Y axes, respectively, and are useful for inflating axis-aligned
        bounding boxes to account for stroke width under the CTM.
        """
        return (math.hypot(self.a, self.c), math.hypot(self.b, self.d))


__pdoc__["Transform.a"] = False
__pdoc__["Transform.b"] = False
__pdoc__["Transform.c"] = False
__pdoc__["Transform.d"] = False
__pdoc__["Transform.e"] = False
__pdoc__["Transform.f"] = False

ColorClass = (DeviceRGB, DeviceGray, DeviceCMYK)