-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathbaseContext.py
More file actions
3055 lines (2601 loc) · 112 KB
/
baseContext.py
File metadata and controls
3055 lines (2601 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import os
from typing import Any, Self
import AppKit # type: ignore
import CoreText # type: ignore
import Quartz # type: ignore
from fontTools.pens.basePen import AbstractPen, BasePen # type: ignore
from fontTools.pens.pointPen import AbstractPointPen # type: ignore
from packaging.version import Version
from drawBot.aliases import (
BoundingBox,
Point,
SomePath,
TransformTuple,
)
from drawBot.macOSVersion import macOSVersion
from drawBot.misc import DrawBotError, cmyk2rgb, memoize, transformationAtCenter, validateLanguageCode, warnings
from .tools import SFNTLayoutTypes, openType, variation
_FALLBACKFONT = "LucidaGrande"
_LINEJOINSTYLESMAP = dict(
miter=Quartz.kCGLineJoinMiter,
round=Quartz.kCGLineJoinRound,
bevel=Quartz.kCGLineJoinBevel,
)
_LINECAPSTYLESMAP = dict(
butt=Quartz.kCGLineCapButt,
square=Quartz.kCGLineCapSquare,
round=Quartz.kCGLineCapRound,
)
# context specific attributes
class ContextPropertyMixin:
def copyContextProperties(self, other):
# loop over all base classes
for cls in self.__class__.__bases__:
func = getattr(cls, "_copyContextProperties", None)
if func is not None:
func(self, other)
class contextProperty:
def __init__(self, doc, validator=None):
self.__doc__ = doc
if validator is not None:
validator = getattr(self, f"_{validator}")
self._validator = validator
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, cls=None):
if obj is None:
return self
return obj.__dict__.get(self.name)
def __set__(self, obj, value):
if self._validator:
self._validator(value)
obj.__dict__[self.name] = value
def __delete__(self, obj):
obj.__dict__.pop(self.name, None)
def _stringValidator(self, value):
if value is None:
return
if not isinstance(value, str):
raise DrawBotError(f"'{self.name}' must be a string.")
class SVGContextPropertyMixin:
svgID = contextProperty("The svg id, as a string.", "stringValidator")
svgClass = contextProperty("The svg class, as a string.", "stringValidator")
svgLink = contextProperty("The svg link, as a string.", "stringValidator")
def _copyContextProperties(self, other):
self.svgID = other.svgID
self.svgClass = other.svgClass
self.svgLink = other.svgLink
class BezierContour(list):
"""
A Bezier contour object.
"""
def __init__(self, *args, **kwargs):
super(BezierContour, self).__init__(*args, **kwargs)
self.open = True
def __repr__(self):
return "<BezierContour>"
def _get_clockwise(self):
from fontTools.pens.areaPen import AreaPen # type: ignore
pen = AreaPen()
pen.endPath = pen.closePath
self.drawToPen(pen)
return pen.value < 0
clockwise = property(_get_clockwise, doc="A boolean representing if the contour has a clockwise direction.")
def drawToPointPen(self, pointPen):
pointPen.beginPath()
for i, segment in enumerate(self):
if len(segment) == 1:
segmentType = "line"
if i == 0 and self.open:
segmentType = "move"
pointPen.addPoint(segment[0], segmentType=segmentType)
else:
pointPen.addPoint(segment[0])
pointPen.addPoint(segment[1])
pointPen.addPoint(segment[2], segmentType="curve")
pointPen.endPath()
def drawToPen(self, pen):
for i, segment in enumerate(self):
if i == 0:
pen.moveTo(*segment)
elif len(segment) == 1:
pen.lineTo(*segment)
else:
pen.curveTo(*segment)
if self.open:
pen.endPath()
else:
pen.closePath()
def _get_points(self):
return tuple([point for segment in self for point in segment])
points = property(
_get_points,
doc="Return an immutable list of all the points in the contour as point coordinate `(x, y)` tuples.",
)
class BezierPath(BasePen, SVGContextPropertyMixin, ContextPropertyMixin):
"""
Return a BezierPath object.
This is a reusable object, if you want to draw the same over and over again.
.. downloadcode:: bezierPath.py
# create a bezier path
path = BezierPath()
# move to a point
path.moveTo((100, 100))
# line to a point
path.lineTo((100, 200))
path.lineTo((200, 200))
# close the path
path.closePath()
# loop over a range of 10
for i in range(10):
# set a random color with alpha value of .3
fill(random(), random(), random(), .3)
# in each loop draw the path
drawPath(path)
# translate the canvas
translate(50, 50)
path.text("Hello world", font="Helvetica", fontSize=30, offset=(210, 210))
print("All Points:")
print(path.points)
print("On Curve Points:")
print(path.onCurvePoints)
print("Off Curve Points:")
print(path.offCurvePoints)
# print out all points from all segments in all contours
for contour in path.contours:
for segment in contour:
for x, y in segment:
print((x, y))
print(["contour is closed", "contour is open"][contour.open])
# translate the path
path.translate(0, -100)
# draw the path again
drawPath(path)
# translate the path
path.translate(-300, 0)
path.scale(2)
# draw the path again
drawPath(path)
"""
contourClass = BezierContour
_instructionSegmentTypeMap = {
AppKit.NSMoveToBezierPathElement: "move",
AppKit.NSLineToBezierPathElement: "line",
AppKit.NSCurveToBezierPathElement: "curve",
}
def __init__(self, path=None, glyphSet=None):
if path is None:
self._path = AppKit.NSBezierPath.alloc().init()
else:
self._path = path
BasePen.__init__(self, glyphSet)
def __repr__(self):
return "<BezierPath>"
# pen support
def moveTo(self, point: Point):
"""
Move to a point `x`, `y`.
"""
super(BezierPath, self).moveTo(point)
def _moveTo(self, pt):
self._path.moveToPoint_(pt)
def lineTo(self, point: Point):
"""
Line to a point `x`, `y`.
"""
super(BezierPath, self).lineTo(point)
def _lineTo(self, pt):
self._path.lineToPoint_(pt)
def curveTo(self, *points: Point):
"""
Draw a cubic bezier with an arbitrary number of control points.
The last point specified is on-curve, all others are off-curve
(control) points.
"""
super(BezierPath, self).curveTo(*points)
def qCurveTo(self, *points: Point):
"""
Draw a whole string of quadratic curve segments.
The last point specified is on-curve, all others are off-curve
(control) points.
"""
super(BezierPath, self).qCurveTo(*points)
def _curveToOne(self, pt1, pt2, pt3):
"""
Curve to a point `x3`, `y3`.
With given bezier handles `x1`, `y1` and `x2`, `y2`.
"""
self._path.curveToPoint_controlPoint1_controlPoint2_(pt3, pt1, pt2)
def closePath(self):
"""
Close the path.
"""
self._path.closePath()
def beginPath(self, identifier=None):
"""
Begin using the path as a so called point pen and start a new subpath.
"""
from fontTools.pens.pointPen import PointToSegmentPen
self._pointToSegmentPen = PointToSegmentPen(self)
self._pointToSegmentPen.beginPath()
def addPoint(
self,
point: Point,
segmentType: str | None = None,
smooth: bool = False,
name: str | None = None,
identifier=None,
**kwargs,
):
"""
Use the path as a point pen and add a point to the current subpath. `beginPath` must
have been called prior to adding points with `addPoint` calls.
"""
if not hasattr(self, "_pointToSegmentPen"):
raise DrawBotError("path.beginPath() must be called before the path can be used as a point pen")
self._pointToSegmentPen.addPoint(
point,
segmentType=segmentType,
smooth=smooth,
name=name,
identifier=identifier,
**kwargs,
)
def endPath(self):
"""
End the current subpath. Calling this method has two distinct meanings depending
on the context:
When the bezier path is used as a segment pen (using `moveTo`, `lineTo`, etc.),
the current subpath will be finished as an open contour.
When the bezier path is used as a point pen (using `beginPath`, `addPoint` and
`endPath`), the path will process all the points added with `addPoint`, finishing
the current subpath.
"""
if hasattr(self, "_pointToSegmentPen"):
# its been used in a point pen world
pointToSegmentPen = self._pointToSegmentPen
del self._pointToSegmentPen
pointToSegmentPen.endPath()
else:
# with NSBezierPath, nothing special needs to be done for an open subpath.
pass
def addComponent(self, glyphName: str, transformation: TransformTuple):
"""
Add a sub glyph. The 'transformation' argument must be a 6-tuple
containing an affine transformation, or a Transform object from the
fontTools.misc.transform module. More precisely: it should be a
sequence containing 6 numbers.
A `glyphSet` is required during initialization of the BezierPath object.
"""
super(BezierPath, self).addComponent(glyphName, transformation)
def drawToPen(self, pen: AbstractPen):
"""
Draw the bezier path into a pen
"""
contours = self.contours
for contour in contours:
contour.drawToPen(pen)
def drawToPointPen(self, pointPen: AbstractPointPen):
"""
Draw the bezier path into a point pen.
"""
contours = self.contours
for contour in contours:
contour.drawToPointPen(pointPen)
def arc(
self,
center: Point,
radius: float,
startAngle: float,
endAngle: float,
clockwise: bool,
):
"""
Arc with `center` and a given `radius`, from `startAngle` to `endAngle`, going clockwise if `clockwise` is True and counter clockwise if `clockwise` is False.
"""
self._path.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_clockwise_(
center, radius, startAngle, endAngle, clockwise
)
def arcTo(self, point1: Point, point2: Point, radius: float):
"""
Arc defined by a circle inscribed inside the angle specified by three points:
the current point, `point1`, and `point2`. The arc is drawn between the two points of the circle that are tangent to the two legs of the angle.
"""
self._path.appendBezierPathWithArcFromPoint_toPoint_radius_(point1, point2, radius)
def rect(self, x: float, y: float, w: float, h: float):
"""
Add a rectangle at possition `x`, `y` with a size of `w`, `h`
"""
self._path.appendBezierPathWithRect_(((x, y), (w, h)))
def oval(self, x: float, y: float, w: float, h: float):
"""
Add a oval at possition `x`, `y` with a size of `w`, `h`
"""
self._path.appendBezierPathWithOvalInRect_(((x, y), (w, h)))
self.closePath()
def line(self, point1: Point, point2: Point):
"""
Add a line between two given points.
"""
self.moveTo(point1)
self.lineTo(point2)
def polygon(self, *points: Point, **kwargs):
"""
Draws a polygon with n-amount of points.
Optionally a `close` argument can be provided to open or close the path.
As default a `polygon` is a closed path.
"""
if len(points) <= 1:
raise TypeError("polygon() expects more than a single point")
doClose = kwargs.get("close", True)
if (len(kwargs) == 1 and "close" not in kwargs) or len(kwargs) > 1:
raise TypeError("unexpected keyword argument for this function")
self.moveTo(points[0])
for x, y in points[1:]:
self.lineTo((x, y))
if doClose:
self.closePath()
def text(
self,
txt,
offset: tuple[float, float] | None = None,
font=_FALLBACKFONT,
fontSize: float = 10,
align: str | None = None,
fontNumber: int = 0,
):
"""
Draws a `txt` with a `font` and `fontSize` at an `offset` in the bezier path.
If a font path is given the font will be installed and used directly.
Optionally an alignment can be set.
Possible `align` values are: `"left"`, `"center"` and `"right"`.
The default alignment is `left`.
Optionally `txt` can be a `FormattedString`.
"""
if not isinstance(txt, (str, FormattedString)):
raise TypeError("expected 'str' or 'FormattedString', got '%s'" % type(txt).__name__)
if align and align not in BaseContext._textAlignMap.keys():
raise DrawBotError("align must be %s" % (", ".join(BaseContext._textAlignMap.keys())))
context = BaseContext()
context.font(font, fontSize, fontNumber)
attributedString = context.attributedString(txt, align)
if offset:
x, y = offset
else:
x = y = 0
for subTxt, box in makeTextBoxes(
attributedString, (x, y), align=align, plainText=not isinstance(txt, FormattedString)
):
self.textBox(subTxt, box, font=font, fontSize=fontSize, align=align)
def textBox(
self,
txt,
box: BoundingBox,
font: str | SomePath = _FALLBACKFONT,
fontSize: float = 10,
align: str | None = None,
hyphenation: bool | None = None,
fontNumber: int = 0,
):
"""
Draws a `txt` with a `font` and `fontSize` in a `box` in the bezier path.
If a font path is given the font will be installed and used directly.
Optionally an alignment can be set.
Possible `align` values are: `"left"`, `"center"` and `"right"`.
The default alignment is `left`.
Optionally `hyphenation` can be provided.
Optionally `txt` can be a `FormattedString`.
Optionally `box` can be a `BezierPath`.
"""
if not isinstance(txt, (str, FormattedString)):
raise TypeError("expected 'str' or 'FormattedString', got '%s'" % type(txt).__name__)
if align and align not in BaseContext._textAlignMap.keys():
raise DrawBotError("align must be %s" % (", ".join(BaseContext._textAlignMap.keys())))
context = BaseContext()
context.font(font, fontSize, fontNumber)
context.hyphenation(hyphenation)
path, (x, y) = context._getPathForFrameSetter(box)
attributedString = context.attributedString(txt, align)
setter = newFramesetterWithAttributedString(attributedString)
frame = CoreText.CTFramesetterCreateFrame(setter, (0, 0), path, None)
ctLines = CoreText.CTFrameGetLines(frame)
origins = CoreText.CTFrameGetLineOrigins(frame, (0, len(ctLines)), None)
for i, (originX, originY) in enumerate(origins):
ctLine = ctLines[i]
ctRuns = CoreText.CTLineGetGlyphRuns(ctLine)
for ctRun in ctRuns:
attributes = CoreText.CTRunGetAttributes(ctRun)
font = attributes.get(AppKit.NSFontAttributeName)
baselineShift = attributes.get(AppKit.NSBaselineOffsetAttributeName, 0)
glyphCount = CoreText.CTRunGetGlyphCount(ctRun)
for i in range(glyphCount):
glyph = CoreText.CTRunGetGlyphs(ctRun, (i, 1), None)[0]
ax, ay = CoreText.CTRunGetPositions(ctRun, (i, 1), None)[0]
if glyph:
self._path.moveToPoint_((x + originX + ax, y + originY + ay + baselineShift))
self._path.appendBezierPathWithGlyph_inFont_(glyph, font)
self.optimizePath()
return context.clippedText(txt, box, align)
def traceImage(
self,
path: SomePath,
threshold: float = 0.2,
blur: float | None = None,
invert: bool = False,
turd: int = 2,
tolerance: float = 0.2,
offset: tuple[float, float] = (0, 0),
):
"""
Convert a given image to a vector outline.
Optionally some tracing options can be provide:
* `threshold`: the threshold used to bitmap an image
* `blur`: the image can be blurred
* `invert`: invert to the image
* `turd`: the size of small turd that can be ignored
* `tolerance`: the precision tolerance of the vector outline
* `offset`: add the traced vector outline with an offset to the BezierPath
"""
from .tools import traceImage
traceImage.TraceImage(path, self, threshold, blur, invert, turd, tolerance, offset)
def getNSBezierPath(self) -> AppKit.NSBezierPath:
"""
Return the nsBezierPath.
"""
return self._path
def _getCGPath(self):
path = Quartz.CGPathCreateMutable()
count = self._path.elementCount()
for i in range(count):
instruction, points = self._path.elementAtIndex_associatedPoints_(i)
if instruction == AppKit.NSMoveToBezierPathElement:
Quartz.CGPathMoveToPoint(path, None, points[0].x, points[0].y)
elif instruction == AppKit.NSLineToBezierPathElement:
Quartz.CGPathAddLineToPoint(path, None, points[0].x, points[0].y)
elif instruction == AppKit.NSCurveToBezierPathElement:
Quartz.CGPathAddCurveToPoint(
path, None, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y
)
elif instruction == AppKit.NSClosePathBezierPathElement:
Quartz.CGPathCloseSubpath(path)
return path
def _setCGPath(self, cgpath):
self._path = AppKit.NSBezierPath.alloc().init()
def _addPoints(arg, element):
instruction, points = element.type, element.points
if instruction == Quartz.kCGPathElementMoveToPoint:
self._path.moveToPoint_(points[0])
elif instruction == Quartz.kCGPathElementAddLineToPoint:
self._path.lineToPoint_(points[0])
elif instruction == Quartz.kCGPathElementAddCurveToPoint:
self._path.curveToPoint_controlPoint1_controlPoint2_(points[2], points[0], points[1])
elif instruction == Quartz.kCGPathElementCloseSubpath:
self._path.closePath()
Quartz.CGPathApply(cgpath, None, _addPoints)
def setNSBezierPath(self, path: AppKit.NSBezierPath):
"""
Set a nsBezierPath.
"""
self._path = path
def pointInside(self, xy: Point) -> bool:
"""
Check if a point `x`, `y` is inside a path.
"""
x, y = xy
return self._path.containsPoint_((x, y))
def bounds(self) -> BoundingBox | None:
"""
Return the bounding box of the path in the form
`(x minimum, y minimum, x maximum, y maximum)`` or,
in the case of empty path `None`.
"""
if self._path.isEmpty():
return None
(x, y), (w, h) = self._path.bounds()
return x, y, x + w, y + h
def controlPointBounds(self) -> BoundingBox | None:
"""
Return the bounding box of the path including the offcurve points
in the form `(x minimum, y minimum, x maximum, y maximum)`` or,
in the case of empty path `None`.
"""
(x, y), (w, h) = self._path.controlPointBounds()
return x, y, x + w, y + h
def optimizePath(self):
count = self._path.elementCount()
if not count or self._path.elementAtIndex_(count - 1) != AppKit.NSMoveToBezierPathElement:
return
optimizedPath = AppKit.NSBezierPath.alloc().init()
for i in range(count - 1):
instruction, points = self._path.elementAtIndex_associatedPoints_(i)
if instruction == AppKit.NSMoveToBezierPathElement:
optimizedPath.moveToPoint_(*points)
elif instruction == AppKit.NSLineToBezierPathElement:
optimizedPath.lineToPoint_(*points)
elif instruction == AppKit.NSCurveToBezierPathElement:
p1, p2, p3 = points
optimizedPath.curveToPoint_controlPoint1_controlPoint2_(p3, p1, p2)
elif instruction == AppKit.NSClosePathBezierPathElement:
optimizedPath.closePath()
self._path = optimizedPath
def copy(self) -> Self:
"""
Copy the bezier path.
"""
new = self.__class__()
new._path = self._path.copy()
new.copyContextProperties(self)
return new
def reverse(self):
"""
Reverse the path direction
"""
self._path = self._path.bezierPathByReversingPath()
def appendPath(self, otherPath: Self):
"""
Append a path.
"""
self._path.appendBezierPath_(otherPath.getNSBezierPath())
def __add__(self, otherPath: Self) -> Self:
new = self.copy()
new.appendPath(otherPath)
return new
def __iadd__(self, other: Self) -> Self:
self.appendPath(other)
return self
# transformations
def translate(self, x: float = 0, y: float = 0):
"""
Translate the path with a given offset.
"""
self.transform((1, 0, 0, 1, x, y))
def rotate(self, angle: float, center: Point = (0, 0)):
"""
Rotate the path around the `center` point (which is the origin by default) with a given angle in degrees.
"""
angle = math.radians(angle)
c = math.cos(angle)
s = math.sin(angle)
self.transform((c, s, -s, c, 0, 0), center)
def scale(self, x: float = 1, y: float | None = None, center: Point = (0, 0)):
"""
Scale the path with a given `x` (horizontal scale) and `y` (vertical scale).
If only 1 argument is provided a proportional scale is applied.
The center of scaling can optionally be set via the `center` keyword argument. By default this is the origin.
"""
if y is None:
y = x
self.transform((x, 0, 0, y, 0, 0), center)
def skew(self, angle1: float, angle2: float = 0, center: Point = (0, 0)):
"""
Skew the path with given `angle1` and `angle2`.
If only one argument is provided a proportional skew is applied.
The center of skewing can optionally be set via the `center` keyword argument. By default this is the origin.
"""
angle1 = math.radians(angle1)
angle2 = math.radians(angle2)
self.transform((1, math.tan(angle2), math.tan(angle1), 1, 0, 0), center)
def transform(self, transformMatrix: TransformTuple, center: Point = (0, 0)):
"""
Transform a path with a transform matrix (xy, xx, yy, yx, x, y).
"""
if center != (0, 0):
transformMatrix = transformationAtCenter(transformMatrix, center)
aT = AppKit.NSAffineTransform.alloc().init()
aT.setTransformStruct_(transformMatrix[:])
self._path.transformUsingAffineTransform_(aT)
# boolean operations
def _contoursForBooleanOperations(self):
# contours are very temporaly objects
# redirect drawToPointPen to drawPoints
contours = self.contours
for contour in contours:
contour.drawPoints = contour.drawToPointPen
if contour.open:
raise DrawBotError("open contours are not supported during boolean operations")
return contours
def union(self, other: Self) -> Self:
"""
Return the union between two bezier paths.
"""
assert isinstance(other, self.__class__)
import booleanOperations # type: ignore
contours = self._contoursForBooleanOperations() + other._contoursForBooleanOperations()
result = self.__class__()
booleanOperations.union(contours, result)
return result
def removeOverlap(self) -> Self:
"""
Remove all overlaps in a bezier path.
"""
import booleanOperations
contours = self._contoursForBooleanOperations()
result = self.__class__()
booleanOperations.union(contours, result)
self.setNSBezierPath(result.getNSBezierPath())
return self
def difference(self, other: Self) -> Self:
"""
Return the difference between two bezier paths.
"""
assert isinstance(other, self.__class__)
import booleanOperations
subjectContours = self._contoursForBooleanOperations()
clipContours = other._contoursForBooleanOperations()
result = self.__class__()
booleanOperations.difference(subjectContours, clipContours, result)
return result
def intersection(self, other: Self) -> Self:
"""
Return the intersection between two bezier paths.
"""
assert isinstance(other, self.__class__)
import booleanOperations
subjectContours = self._contoursForBooleanOperations()
clipContours = other._contoursForBooleanOperations()
result = self.__class__()
booleanOperations.intersection(subjectContours, clipContours, result)
return result
def xor(self, other: Self) -> Self:
"""
Return the xor between two bezier paths.
"""
assert isinstance(other, self.__class__)
import booleanOperations
subjectContours = self._contoursForBooleanOperations()
clipContours = other._contoursForBooleanOperations()
result = self.__class__()
booleanOperations.xor(subjectContours, clipContours, result)
return result
def intersectionPoints(self, other: Self | None = None) -> list[Point]:
"""
Return a list of intersection points as `x`, `y` tuples.
Optionaly provide an other path object to find intersection points.
"""
import booleanOperations
contours = self._contoursForBooleanOperations()
if other is not None:
assert isinstance(other, self.__class__)
contours += other._contoursForBooleanOperations()
return booleanOperations.getIntersections(contours)
def expandStroke(
self, width: float, lineCap: str = "round", lineJoin: str = "round", miterLimit: float = 10
) -> Self:
"""
Returns a new bezier path with an expanded stroke around the original path,
with a given `width`. Note: the new path will not contain the original path.
The following optional arguments are available with respect to line caps and joins:
* `lineCap`: Possible values are `"butt"`, `"square"` or `"round"`
* `lineJoin`: Possible values are `"bevel"`, `"miter"` or `"round"`
* `miterLimit`: The miter limit to use for `"miter"` lineJoin option
"""
if lineJoin not in _LINEJOINSTYLESMAP:
raise DrawBotError("lineJoin must be 'bevel', 'miter' or 'round'")
if lineCap not in _LINECAPSTYLESMAP:
raise DrawBotError("lineCap must be 'butt', 'square' or 'round'")
strokedCGPath = Quartz.CGPathCreateCopyByStrokingPath(
self._getCGPath(), None, width, _LINECAPSTYLESMAP[lineCap], _LINEJOINSTYLESMAP[lineJoin], miterLimit
)
result = self.__class__()
result._setCGPath(strokedCGPath)
return result
def dashStroke(self, *dash: float, offset: float = 0) -> Self:
"""
Return a new bezier path with a dashed stroke of the original path,
with a given `dash`.
The following optional arguments are:
* `offset`: set the offset of the first dash.
"""
dashedCGPath = Quartz.CGPathCreateCopyByDashingPath(self._getCGPath(), None, offset, dash, len(dash))
result = self.__class__()
result._setCGPath(dashedCGPath)
return result
def __mod__(self, other: Self) -> Self:
return self.difference(other)
__rmod__ = __mod__
def __imod__(self, other: Self) -> Self:
result = self.difference(other)
self.setNSBezierPath(result.getNSBezierPath())
return self
def __or__(self, other: Self) -> Self:
return self.union(other)
__ror__ = __or__
def __ior__(self, other: Self) -> Self:
result = self.union(other)
self.setNSBezierPath(result.getNSBezierPath())
return self
def __and__(self, other: Self) -> Self:
return self.intersection(other)
__rand__ = __and__
def __iand__(self, other: Self) -> Self:
result = self.intersection(other)
self.setNSBezierPath(result.getNSBezierPath())
return self
def __xor__(self, other: Self) -> Self:
return self.xor(other)
__rxor__ = __xor__
def __ixor__(self, other: Self) -> Self:
result = self.xor(other)
self.setNSBezierPath(result.getNSBezierPath())
return self
def _points(self, onCurve=True, offCurve=True):
points = []
if not onCurve and not offCurve:
return points
for index in range(self._path.elementCount()):
instruction, pts = self._path.elementAtIndex_associatedPoints_(index)
if not onCurve:
pts = pts[:-1]
elif not offCurve:
pts = pts[-1:]
points.extend([(p.x, p.y) for p in pts])
return tuple(points)
def _get_points(self):
return self._points()
points = property(
_get_points, doc="Return an immutable list of all points in the BezierPath as point coordinate `(x, y)` tuples."
)
def _get_onCurvePoints(self):
return self._points(offCurve=False)
onCurvePoints = property(
_get_onCurvePoints,
doc="Return an immutable list of all on curve points in the BezierPath as point coordinate `(x, y)` tuples.",
)
def _get_offCurvePoints(self):
return self._points(onCurve=False)
offCurvePoints = property(
_get_offCurvePoints,
doc="Return an immutable list of all off curve points in the BezierPath as point coordinate `(x, y)` tuples.",
)
def _get_contours(self):
contours = []
for index in range(self._path.elementCount()):
instruction, pts = self._path.elementAtIndex_associatedPoints_(index)
if instruction == AppKit.NSMoveToBezierPathElement:
contours.append(self.contourClass())
if instruction == AppKit.NSClosePathBezierPathElement:
contours[-1].open = False
if pts:
contours[-1].append([(p.x, p.y) for p in pts])
if len(contours) >= 2 and len(contours[-1]) == 1 and contours[-1][0] == contours[-2][0]:
contours.pop()
return tuple(contours)
contours = property(
_get_contours,
doc="Return an immutable list of contours with all point coordinates sorted in segments. A contour object has an `open` attribute.",
)
def __len__(self) -> int:
return len(self.contours)
def __getitem__(self, index):
return self.contours[index]
def __iter__(self):
contours = self.contours
count = len(contours)
index = 0
while index < count:
contour = contours[index]
yield contour
index += 1
class Color:
colorSpace = AppKit.NSColorSpace.genericRGBColorSpace()
def __init__(self, r=None, g=None, b=None, a=1):
self._color = None
if r is None:
return
if isinstance(r, AppKit.NSColor):
self._color = r
elif g is None and b is None:
self._color = AppKit.NSColor.colorWithCalibratedRed_green_blue_alpha_(r, r, r, a)
elif b is None:
self._color = AppKit.NSColor.colorWithCalibratedRed_green_blue_alpha_(r, r, r, g)
else:
self._color = AppKit.NSColor.colorWithCalibratedRed_green_blue_alpha_(r, g, b, a)
self._color = self._color.colorUsingColorSpace_(self.colorSpace)
def set(self):
self._color.set()
def setStroke(self):
self._color.setStroke()
def getNSObject(self):
return self._color
def copy(self):
new = self.__class__()
new._color = self._color.copy()
return new
@classmethod
def getColorsFromList(cls, inputColors):
outputColors = []
for color in inputColors:
color = cls.getColor(color)
outputColors.append(color)
return outputColors
@classmethod
def getColor(cls, color):
if isinstance(color, cls.__class__):
return color
elif isinstance(color, (tuple, list)):
return cls(*color)
elif isinstance(color, AppKit.NSColor):
return cls(color)
raise DrawBotError("Not a valid color: %s" % color)
class CMYKColor(Color):
colorSpace = AppKit.NSColorSpace.genericCMYKColorSpace()
def __init__(self, c=None, m=None, y=None, k=None, a=1):
if c is None:
return
if isinstance(c, AppKit.NSColor):