Skip to content

Commit 2a252a0

Browse files
Remove Unused Variables in smoothPath (#83)
Fixes a few warnings in `smoothPath`, and guards against a divide-by-zero assertion failure.
1 parent 5114e0d commit 2a252a0

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

Sources/CodeEditTextView/Extensions/NSBezierPath+SmoothPath.swift

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -60,19 +60,13 @@ extension NSBezierPath {
6060
let distance1 = sqrt(vector1.x * vector1.x + vector1.y * vector1.y)
6161
let distance2 = sqrt(vector2.x * vector2.x + vector2.y * vector2.y)
6262

63-
// TODO: Check if .zero should get used or just skipped
64-
if distance1.isZero || distance2.isZero { continue }
63+
if distance1.isZero || distance2.isZero {
64+
// Dividing by 0 will result in `NaN` points.
65+
continue
66+
}
6567
let unitVector1 = distance1 > 0 ? NSPoint(x: vector1.x / distance1, y: vector1.y / distance1) : NSPoint.zero
6668
let unitVector2 = distance2 > 0 ? NSPoint(x: vector2.x / distance2, y: vector2.y / distance2) : NSPoint.zero
6769

68-
// This uses the dot product formula: cos(θ) = (u1 • u2),
69-
// where u1 and u2 are unit vectors. The result will range from -1 to 1:
70-
let angleCosine = unitVector1.x * unitVector2.x + unitVector1.y * unitVector2.y
71-
72-
// If the cosine of the angle is less than 0.5 (i.e., angle > ~60 degrees),
73-
// the radius is reduced to half to avoid overlapping or excessive smoothing.
74-
let clampedRadius = angleCosine < 0.5 ? radius /** 0.5 */: radius // Adjust for sharp angles
75-
7670
// Calculate the corner start and end
7771
let cornerStart = NSPoint(x: p1.x - unitVector1.x * radius, y: p1.y - unitVector1.y * radius)
7872
let cornerEnd = NSPoint(x: p1.x + unitVector2.x * radius, y: p1.y + unitVector2.y * radius)
@@ -95,6 +89,14 @@ extension NSBezierPath {
9589
// Calculate the vectors and unit vectors
9690
let finalVector = NSPoint(x: firstPoint.x - lastPoint.x, y: firstPoint.y - lastPoint.y)
9791
let distance = sqrt(finalVector.x * finalVector.x + finalVector.y * finalVector.y)
92+
93+
// Dividing by 0 after this will cause an assertion failure. Something went wrong with the given points
94+
// this could mean we're rounding a 0-width and 0-height rect.
95+
guard distance != 0 else {
96+
path.line(to: lastPoint)
97+
return path
98+
}
99+
98100
let unitVector = NSPoint(x: finalVector.x / distance, y: finalVector.y / distance)
99101

100102
// Calculate the final corner start and initial corner end

0 commit comments

Comments
 (0)