@nativue/core 0.15.3 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,443 +0,0 @@
1
- package dev.nativue
2
-
3
- import android.content.Context
4
- import android.graphics.Bitmap
5
- import android.graphics.Canvas
6
- import android.graphics.Matrix
7
- import android.graphics.Paint
8
- import android.graphics.Path
9
- import android.graphics.PointF
10
- import android.graphics.RectF
11
- import android.view.View
12
- import kotlin.math.abs
13
- import kotlin.math.atan2
14
- import kotlin.math.ceil
15
- import kotlin.math.cos
16
- import kotlin.math.max
17
- import kotlin.math.min
18
- import kotlin.math.sin
19
- import kotlin.math.sqrt
20
- import kotlin.math.tan
21
-
22
- /**
23
- * View behind <Svg>: draws SVG elements ([tag, attributes] pairs, the shape of Lucide's icon nodes),
24
- * scaled from `viewBox` to its bounds like preserveAspectRatio="xMidYMid meet". Elements are stroked
25
- * with `color` (round caps and joins, as icon sets expect); those whose fill isn't "none" are also
26
- * filled with it. Mirrors ios/SvgView.swift.
27
- */
28
- // Limitation: Only the shapes icon sets use and a single color; add per-element colors, gradients or
29
- // transforms when a real-world SVG needs them.
30
- class SvgView(context: Context) : View(context) {
31
- var viewBox = RectF(0f, 0f, 24f, 24f)
32
- set(value) {
33
- field = value
34
- invalidate()
35
- }
36
-
37
- var strokeWidth = 2f
38
- set(value) {
39
- field = value
40
- invalidate()
41
- }
42
-
43
- var color = 0xFF000000.toInt()
44
- set(value) {
45
- field = value
46
- invalidate()
47
- }
48
-
49
- var elements: List<*> = emptyList<Any>()
50
- set(value) {
51
- field = value
52
- buildPaths()
53
- invalidate()
54
- }
55
-
56
- private var strokePath = Path()
57
- private var fillPath = Path()
58
- private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
59
- style = Paint.Style.STROKE
60
- strokeCap = Paint.Cap.ROUND
61
- strokeJoin = Paint.Join.ROUND
62
- }
63
- private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
64
-
65
- init {
66
- isClickable = false // a press on an icon presses what contains it
67
- }
68
-
69
- override fun onDraw(canvas: Canvas) {
70
- if (viewBox.width() <= 0 || viewBox.height() <= 0) return
71
-
72
- val scale = min(width / viewBox.width(), height / viewBox.height())
73
- val matrix = Matrix()
74
- matrix.setTranslate(-viewBox.left, -viewBox.top)
75
- matrix.postScale(scale, scale)
76
- matrix.postTranslate((width - viewBox.width() * scale) / 2, (height - viewBox.height() * scale) / 2)
77
-
78
- canvas.save()
79
- canvas.concat(matrix)
80
- fillPaint.color = color
81
- strokePaint.color = color
82
- strokePaint.strokeWidth = strokeWidth
83
- canvas.drawPath(fillPath, fillPaint)
84
- canvas.drawPath(strokePath, strokePaint)
85
- canvas.restore()
86
- }
87
-
88
- private fun buildPaths() {
89
- strokePath = Path()
90
- fillPath = Path()
91
-
92
- for (element in elements.filterIsInstance<List<*>>()) {
93
- val tag = element.firstOrNull() as? String ?: continue
94
- val attributes = element.lastOrNull() as? Map<*, *> ?: continue
95
- val shape = shape(tag, SvgAttributes(attributes)) ?: continue
96
-
97
- strokePath.addPath(shape)
98
- val fill = attributes["fill"] as? String
99
- if (fill != null && fill != "none") fillPath.addPath(shape)
100
- }
101
- }
102
-
103
- companion object {
104
- /** [minX, minY, width, height], as sent from JS. */
105
- fun rect(viewBox: Any?): RectF? {
106
- val numbers = (viewBox as? List<*>)?.mapNotNull { (it as? Number)?.toFloat() } ?: emptyList()
107
- if (numbers.size != 4) return null
108
-
109
- return RectF(numbers[0], numbers[1], numbers[0] + numbers[2], numbers[1] + numbers[3])
110
- }
111
-
112
- /** The elements drawn in [color] into a square bitmap of [size] pixels (tab bar icons). */
113
- fun bitmap(context: Context, elements: List<*>, viewBox: Any?, size: Int, color: Int): Bitmap {
114
- val svgView = SvgView(context)
115
- rect(viewBox)?.let { svgView.viewBox = it }
116
- svgView.elements = elements
117
- svgView.color = color
118
- svgView.layout(0, 0, size, size)
119
-
120
- val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
121
- svgView.draw(Canvas(bitmap))
122
-
123
- return bitmap
124
- }
125
-
126
- private fun shape(tag: String, attributes: SvgAttributes): Path? = when (tag) {
127
- "path" -> SvgPathParser(attributes.text("d")).parse()
128
-
129
- "circle" -> {
130
- val radius = attributes.number("r")
131
- Path().apply { addOval(ellipseBounds(attributes, radius, radius), Path.Direction.CW) }
132
- }
133
-
134
- "ellipse" -> Path().apply {
135
- addOval(ellipseBounds(attributes, attributes.number("rx"), attributes.number("ry")), Path.Direction.CW)
136
- }
137
-
138
- "rect" -> roundedRect(attributes)
139
-
140
- "line" -> Path().apply {
141
- moveTo(attributes.number("x1"), attributes.number("y1"))
142
- lineTo(attributes.number("x2"), attributes.number("y2"))
143
- }
144
-
145
- "polyline", "polygon" -> Path().apply {
146
- SvgPathParser(attributes.text("points")).points().forEachIndexed { index, point ->
147
- if (index == 0) moveTo(point.x, point.y) else lineTo(point.x, point.y)
148
- }
149
- if (tag == "polygon") close()
150
- }
151
-
152
- else -> null
153
- }
154
-
155
- private fun ellipseBounds(attributes: SvgAttributes, radiusX: Float, radiusY: Float): RectF {
156
- val centerX = attributes.number("cx")
157
- val centerY = attributes.number("cy")
158
-
159
- return RectF(centerX - radiusX, centerY - radiusY, centerX + radiusX, centerY + radiusY)
160
- }
161
-
162
- /** rx and ry default to each other, and can't exceed half the side (like SVG). */
163
- private fun roundedRect(attributes: SvgAttributes): Path {
164
- val left = attributes.number("x")
165
- val top = attributes.number("y")
166
- val rect = RectF(left, top, left + attributes.number("width"), top + attributes.number("height"))
167
- val radiusX = attributes.optionalNumber("rx") ?: attributes.optionalNumber("ry") ?: 0f
168
- val radiusY = attributes.optionalNumber("ry") ?: radiusX
169
-
170
- return Path().apply {
171
- addRoundRect(rect, min(radiusX, rect.width() / 2), min(radiusY, rect.height() / 2), Path.Direction.CW)
172
- }
173
- }
174
- }
175
- }
176
-
177
- /** Attribute values arrive as strings ("12") or numbers. */
178
- private class SvgAttributes(private val values: Map<*, *>) {
179
- fun text(name: String): String = values[name]?.toString() ?: ""
180
-
181
- fun optionalNumber(name: String): Float? = when (val value = values[name]) {
182
- is Number -> value.toFloat()
183
- is String -> value.toFloatOrNull()
184
- else -> null
185
- }
186
-
187
- fun number(name: String): Float = optionalNumber(name) ?: 0f
188
- }
189
-
190
- /**
191
- * Parses SVG path data ("M12 2a10 10 0 1 0 0 20z"): every command, absolute and relative, including
192
- * the compact forms optimizers emit ("l.486.9", arc flags written "01").
193
- */
194
- private class SvgPathParser(private val text: String) {
195
- private var index = 0
196
-
197
- /** "x,y x,y" (polyline / polygon points). */
198
- fun points(): List<PointF> {
199
- val points = mutableListOf<PointF>()
200
-
201
- while (true) {
202
- val x = number() ?: break
203
- val y = number() ?: break
204
- points.add(PointF(x, y))
205
- }
206
-
207
- return points
208
- }
209
-
210
- fun parse(): Path {
211
- val path = Path()
212
- var command = 'M'
213
- var current = PointF(0f, 0f)
214
- var subpathStart = PointF(0f, 0f)
215
- var lastCubicControl: PointF? = null
216
- var lastQuadraticControl: PointF? = null
217
-
218
- while (true) {
219
- skipSeparators()
220
- if (index >= text.length) break
221
-
222
- if (text[index].isLetter()) {
223
- command = text[index]
224
- index++
225
- } else if (command == 'Z' || command == 'z') {
226
- break // numbers can't follow a close
227
- }
228
-
229
- val isRelative = command.isLowerCase()
230
- val origin = if (isRelative) current else PointF(0f, 0f)
231
- var cubicControl: PointF? = null
232
- var quadraticControl: PointF? = null
233
-
234
- when (command.uppercaseChar()) {
235
- 'M' -> {
236
- val point = point(origin) ?: return path
237
- path.moveTo(point.x, point.y)
238
- current = point
239
- subpathStart = point
240
- command = if (isRelative) 'l' else 'L' // further pairs are lines
241
- }
242
-
243
- 'L' -> {
244
- val point = point(origin) ?: return path
245
- path.lineTo(point.x, point.y)
246
- current = point
247
- }
248
-
249
- 'H' -> {
250
- val x = number() ?: return path
251
- current = PointF(x + origin.x, current.y)
252
- path.lineTo(current.x, current.y)
253
- }
254
-
255
- 'V' -> {
256
- val y = number() ?: return path
257
- current = PointF(current.x, y + origin.y)
258
- path.lineTo(current.x, current.y)
259
- }
260
-
261
- 'C' -> {
262
- val control1 = point(origin) ?: return path
263
- val control2 = point(origin) ?: return path
264
- val end = point(origin) ?: return path
265
- path.cubicTo(control1.x, control1.y, control2.x, control2.y, end.x, end.y)
266
- cubicControl = control2
267
- current = end
268
- }
269
-
270
- 'S' -> {
271
- val control2 = point(origin) ?: return path
272
- val end = point(origin) ?: return path
273
- val control1 = lastCubicControl?.let { reflect(it, current) } ?: current
274
- path.cubicTo(control1.x, control1.y, control2.x, control2.y, end.x, end.y)
275
- cubicControl = control2
276
- current = end
277
- }
278
-
279
- 'Q' -> {
280
- val control = point(origin) ?: return path
281
- val end = point(origin) ?: return path
282
- path.quadTo(control.x, control.y, end.x, end.y)
283
- quadraticControl = control
284
- current = end
285
- }
286
-
287
- 'T' -> {
288
- val end = point(origin) ?: return path
289
- val control = lastQuadraticControl?.let { reflect(it, current) } ?: current
290
- path.quadTo(control.x, control.y, end.x, end.y)
291
- quadraticControl = control
292
- current = end
293
- }
294
-
295
- 'A' -> {
296
- val radiusX = number() ?: return path
297
- val radiusY = number() ?: return path
298
- val rotation = number() ?: return path
299
- val largeArc = flag() ?: return path
300
- val sweep = flag() ?: return path
301
- val end = point(origin) ?: return path
302
- addArc(path, current, end, radiusX, radiusY, rotation, largeArc, sweep)
303
- current = end
304
- }
305
-
306
- 'Z' -> {
307
- path.close()
308
- current = subpathStart
309
- }
310
-
311
- else -> return path
312
- }
313
-
314
- lastCubicControl = cubicControl
315
- lastQuadraticControl = quadraticControl
316
- }
317
-
318
- return path
319
- }
320
-
321
- private fun reflect(point: PointF, center: PointF) = PointF(2 * center.x - point.x, 2 * center.y - point.y)
322
-
323
- private fun point(origin: PointF): PointF? {
324
- val x = number() ?: return null
325
- val y = number() ?: return null
326
-
327
- return PointF(x + origin.x, y + origin.y)
328
- }
329
-
330
- private fun skipSeparators() {
331
- while (index < text.length && (text[index].isWhitespace() || text[index] == ',')) index++
332
- }
333
-
334
- private fun flag(): Boolean? {
335
- skipSeparators()
336
- if (index >= text.length || (text[index] != '0' && text[index] != '1')) return null
337
-
338
- index++
339
-
340
- return text[index - 1] == '1'
341
- }
342
-
343
- /** "-1.5e-3", ".5" and "1.5.5" (two numbers) all parse. */
344
- private fun number(): Float? {
345
- skipSeparators()
346
- val start = index
347
- var hasDot = false
348
-
349
- if (index < text.length && (text[index] == '-' || text[index] == '+')) index++
350
- while (index < text.length) {
351
- val character = text[index]
352
- when {
353
- character.isDigit() -> index++
354
- character == '.' && !hasDot -> {
355
- hasDot = true
356
- index++
357
- }
358
- character == 'e' || character == 'E' -> {
359
- index++
360
- if (index < text.length && (text[index] == '-' || text[index] == '+')) index++
361
- }
362
- else -> break
363
- }
364
- }
365
-
366
- return text.substring(start, index).toFloatOrNull()
367
- }
368
- }
369
-
370
- /** An elliptical arc as cubic Béziers, one per quarter turn at most (SVG spec, appendix B.2.4). */
371
- private fun addArc(
372
- path: Path,
373
- from: PointF,
374
- to: PointF,
375
- radiusX: Float,
376
- radiusY: Float,
377
- rotationDegrees: Float,
378
- largeArc: Boolean,
379
- sweep: Boolean,
380
- ) {
381
- if (from == to) return
382
- if (radiusX == 0f || radiusY == 0f) return path.lineTo(to.x, to.y)
383
-
384
- val angle = Math.toRadians(rotationDegrees.toDouble())
385
- val cosine = cos(angle)
386
- val sine = sin(angle)
387
-
388
- // The start point in the ellipse's own axes, relative to the chord's middle.
389
- val halfDeltaX = (from.x - to.x) / 2.0
390
- val halfDeltaY = (from.y - to.y) / 2.0
391
- val startX = cosine * halfDeltaX + sine * halfDeltaY
392
- val startY = -sine * halfDeltaX + cosine * halfDeltaY
393
-
394
- // Radii too small to reach the end are scaled up just enough.
395
- var rx = abs(radiusX.toDouble())
396
- var ry = abs(radiusY.toDouble())
397
- val radiiScale = (startX * startX) / (rx * rx) + (startY * startY) / (ry * ry)
398
- if (radiiScale > 1) {
399
- rx *= sqrt(radiiScale)
400
- ry *= sqrt(radiiScale)
401
- }
402
-
403
- val numerator = rx * rx * ry * ry - rx * rx * startY * startY - ry * ry * startX * startX
404
- val denominator = rx * rx * startY * startY + ry * ry * startX * startX
405
- var coefficient = sqrt(max(0.0, numerator / denominator))
406
- if (largeArc == sweep) coefficient = -coefficient
407
-
408
- val centerX = coefficient * rx * startY / ry
409
- val centerY = -coefficient * ry * startX / rx
410
- val ellipseCenterX = cosine * centerX - sine * centerY + (from.x + to.x) / 2.0
411
- val ellipseCenterY = sine * centerX + cosine * centerY + (from.y + to.y) / 2.0
412
-
413
- val startVectorX = (startX - centerX) / rx
414
- val startVectorY = (startY - centerY) / ry
415
- val endVectorX = (-startX - centerX) / rx
416
- val endVectorY = (-startY - centerY) / ry
417
- val startAngle = angleBetween(1.0, 0.0, startVectorX, startVectorY)
418
- var sweepAngle = angleBetween(startVectorX, startVectorY, endVectorX, endVectorY)
419
- if (!sweep && sweepAngle > 0) sweepAngle -= 2 * Math.PI
420
- if (sweep && sweepAngle < 0) sweepAngle += 2 * Math.PI
421
-
422
- val segmentCount = max(1, ceil(abs(sweepAngle) / (Math.PI / 2)).toInt())
423
- val segmentAngle = sweepAngle / segmentCount
424
- val handle = 4.0 / 3 * tan(segmentAngle / 4)
425
-
426
- // Unit-circle points mapped onto the rotated ellipse.
427
- fun onEllipse(x: Double, y: Double) = PointF(
428
- (ellipseCenterX + rx * cosine * x - ry * sine * y).toFloat(),
429
- (ellipseCenterY + rx * sine * x + ry * cosine * y).toFloat(),
430
- )
431
-
432
- for (segment in 0 until segmentCount) {
433
- val segmentStart = startAngle + segment * segmentAngle
434
- val segmentEnd = segmentStart + segmentAngle
435
- val control1 = onEllipse(cos(segmentStart) - handle * sin(segmentStart), sin(segmentStart) + handle * cos(segmentStart))
436
- val control2 = onEllipse(cos(segmentEnd) + handle * sin(segmentEnd), sin(segmentEnd) - handle * cos(segmentEnd))
437
- val end = onEllipse(cos(segmentEnd), sin(segmentEnd))
438
- path.cubicTo(control1.x, control1.y, control2.x, control2.y, end.x, end.y)
439
- }
440
- }
441
-
442
- private fun angleBetween(firstX: Double, firstY: Double, secondX: Double, secondY: Double): Double =
443
- atan2(firstX * secondY - firstY * secondX, firstX * secondX + firstY * secondY)