@nativue/core 0.16.0 → 0.18.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.
package/AGENTS.md CHANGED
@@ -45,10 +45,13 @@ Global, with no import: `View`, `Text`, `Image`, `ImageBackground`, `Pressable`,
45
45
  `:style="{ padding: 16, borderRadius: 12, backgroundColor: '#ffffff' }"`. Arrays merge, later wins:
46
46
  `:style="[styles.card, selected && styles.selected]"`.
47
47
  - `StyleSheet.create({...})` (from `vue`) groups and types a screen's styles.
48
+ - Gradients: `backgroundImage: 'linear-gradient(135deg, #4af2ae, #10b39b)'` or `radial-gradient(...)`,
49
+ as in CSS, on a `View`; with Tailwind, `bg-linear-to-r from-emerald-400 to-teal-600`.
48
50
  - Every view is a flexbox container stacking its children in a **column** by default; `flex: 1` takes
49
51
  the space left. Percentages (`'50%'`) work for sizes.
50
- - Text styles (`color`, `fontSize`, `fontWeight`, `textAlign`, `textDecorationLine`) go on the
51
- `<Text>` itself: native views don't inherit them from their parents.
52
+ - Text styles (`color`, `fontSize`, `fontWeight`, `fontStyle`, `textAlign`, `textDecorationLine`,
53
+ `textTransform`, `letterSpacing`, `lineHeight`, `lineClamp`) go on the `<Text>` itself: native views
54
+ don't inherit them from their parents.
52
55
  - Pressed and focused states: `pressed-style` on `Pressable`, `focused-style` on `TextInput`.
53
56
  - Dark mode: `useColorScheme()` (from `vue`) gives `'light'` or `'dark'`, live.
54
57
  - Platform: `Platform.OS` is `'ios'` or `'android'`; `Platform.select({ ios, android })`.
@@ -106,7 +109,11 @@ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `Lay
106
109
  - Tab and header icons (`tabBarIcon`, a header item's `icon`): an `@nativue/icons` component,
107
110
  `svgIcon(viewBox, elements)` from `@nativue/svg`, an image `{ uri }`, or an SF Symbol name (iOS).
108
111
  - Official packages: `@nativue/svg`, `@nativue/icons` (icon components), `@nativue/tailwind`, `@nativue/haptics`,
109
- `@nativue/clipboard` (copy text), `@nativue/notifications` (local notifications), `@nativue/sqlite`.
112
+ `@nativue/clipboard` (copy text), `@nativue/notifications` (local notifications), `@nativue/sqlite`,
113
+ `@nativue/image-picker` (`ImagePicker.pick({ limit, mediaTypes })`,
114
+ `openCamera({ mediaTypes, videoMaxDuration, videoQuality })`; call `getPendingResult()` on start, for
115
+ what was picked or taken while Android closed the app),
116
+ `@nativue/secure-store` (secrets: `SecureStore.setItem(key, value)`, `getItem`, `deleteItem`).
110
117
  A package with native code needs the app
111
118
  rebuilt with `npm run ios` or `npm run android`, not just a reload.
112
119
  - Notifications: `Notifications.schedule({ title, body, data }, { seconds } | { date } | { hour, minute } | null)`
@@ -0,0 +1,111 @@
1
+ package dev.nativue
2
+
3
+ import android.graphics.LinearGradient
4
+ import android.graphics.Matrix
5
+ import android.graphics.PointF
6
+ import android.graphics.RadialGradient
7
+ import android.graphics.Shader
8
+ import kotlin.math.abs
9
+ import kotlin.math.cos
10
+ import kotlin.math.hypot
11
+ import kotlin.math.max
12
+ import kotlin.math.min
13
+ import kotlin.math.sin
14
+ import kotlin.math.sqrt
15
+
16
+ /**
17
+ * backgroundImage: a CSS gradient (src/gradients.ts) as a shader for a box [width] by [height] pixels, where
18
+ * CSS puts it, as iOS's CSSGradient does. Lengths arrive in dp.
19
+ */
20
+ object BackgroundGradients {
21
+ fun shader(gradient: Map<*, *>, width: Float, height: Float, density: Float): Shader? {
22
+ val colors = (gradient["colors"] as? List<*>).orEmpty().mapNotNull(::androidColor).toIntArray()
23
+ val positions = (gradient["positions"] as? List<*>).orEmpty().mapNotNull { (it as? Number)?.toFloat() }.toFloatArray()
24
+ if (colors.size < 2 || colors.size != positions.size || width <= 0 || height <= 0) return null
25
+
26
+ if (gradient["type"] != "radial") {
27
+ val (start, end) = linear(gradient, width, height)
28
+
29
+ return LinearGradient(start.x, start.y, end.x, end.y, colors, positions, Shader.TileMode.CLAMP)
30
+ }
31
+
32
+ val (center, radii) = radial(gradient, width, height, density)
33
+ val radiusX = max(radii.x, 0.01f)
34
+
35
+ // Android's is a circle: stretched into the ellipse.
36
+ return RadialGradient(center.x, center.y, radiusX, colors, positions, Shader.TileMode.CLAMP).apply {
37
+ setLocalMatrix(Matrix().apply { setScale(1f, max(radii.y, 0.01f) / radiusX, center.x, center.y) })
38
+ }
39
+ }
40
+
41
+ /** The gradient line: through the center, as long as the box is along it, so its ends touch the corners. */
42
+ private fun linear(gradient: Map<*, *>, width: Float, height: Float): Pair<PointF, PointF> {
43
+ val sides = (gradient["to"] as? List<*>)?.map { it.toString() }
44
+ val angle = (gradient["angle"] as? Number)?.toDouble()?.let(Math::toRadians)
45
+ var directionX = 0f
46
+ var directionY = 1f
47
+
48
+ if (sides != null) {
49
+ val x = if ("right" in sides) 1f else if ("left" in sides) -1f else 0f
50
+ val y = if ("bottom" in sides) 1f else if ("top" in sides) -1f else 0f
51
+ // To a corner: perpendicular to the diagonal between the two corners next to it.
52
+ val isCorner = x != 0f && y != 0f
53
+
54
+ directionX = if (isCorner) x * height else x
55
+ directionY = if (isCorner) y * width else y
56
+ } else if (angle != null) {
57
+ // 0 points up, 90 right.
58
+ directionX = sin(angle).toFloat()
59
+ directionY = -cos(angle).toFloat()
60
+ }
61
+
62
+ val length = hypot(directionX, directionY)
63
+ if (length == 0f) return PointF(0f, 0f) to PointF(0f, height)
64
+
65
+ val unitX = directionX / length
66
+ val unitY = directionY / length
67
+ val halfLine = (abs(width * unitX) + abs(height * unitY)) / 2
68
+
69
+ return PointF(width / 2 - unitX * halfLine, height / 2 - unitY * halfLine) to
70
+ PointF(width / 2 + unitX * halfLine, height / 2 + unitY * halfLine)
71
+ }
72
+
73
+ /** The center and the radii: given, or reaching the extent keyword's side or corner. */
74
+ private fun radial(gradient: Map<*, *>, width: Float, height: Float, density: Float): Pair<PointF, PointF> {
75
+ val center = PointF(
76
+ length(gradient["center"], 0, width, density, 0.5f),
77
+ length(gradient["center"], 1, height, density, 0.5f),
78
+ )
79
+ val isCircle = gradient["shape"] == "circle"
80
+
81
+ if (gradient["radii"] != null) {
82
+ val radiusX = length(gradient["radii"], 0, width, density, 0.5f)
83
+ val radiusY = if (isCircle) radiusX else length(gradient["radii"], 1, height, density, 0.5f)
84
+
85
+ return center to PointF(radiusX, radiusY)
86
+ }
87
+
88
+ val extent = gradient["extent"] as? String ?: "farthest-corner"
89
+ val pick = { first: Float, second: Float -> if (extent.startsWith("closest")) min(first, second) else max(first, second) }
90
+ val sideX = pick(abs(center.x), abs(width - center.x))
91
+ val sideY = pick(abs(center.y), abs(height - center.y))
92
+
93
+ val radii = when {
94
+ extent.endsWith("corner") && isCircle -> hypot(sideX, sideY).let { PointF(it, it) }
95
+ // An ellipse through the corner, shaped like the one that would touch the sides.
96
+ extent.endsWith("corner") -> PointF(sideX * sqrt(2f), sideY * sqrt(2f))
97
+ isCircle -> pick(sideX, sideY).let { PointF(it, it) }
98
+ else -> PointF(sideX, sideY)
99
+ }
100
+
101
+ return center to radii
102
+ }
103
+
104
+ /** [[fraction, dp], ...][index], in pixels of a side [side] long. */
105
+ private fun length(value: Any?, index: Int, side: Float, density: Float, defaultFraction: Float): Float {
106
+ val pair = ((value as? List<*>)?.getOrNull(index) as? List<*>)?.mapNotNull { (it as? Number)?.toFloat() }
107
+ if (pair == null || pair.size != 2) return defaultFraction * side
108
+
109
+ return pair[0] * side + pair[1] * density
110
+ }
111
+ }
@@ -4,18 +4,25 @@ import android.graphics.Canvas
4
4
  import android.graphics.ColorFilter
5
5
  import android.graphics.Outline
6
6
  import android.graphics.Paint
7
+ import android.graphics.Path
7
8
  import android.graphics.PixelFormat
8
9
  import android.graphics.RectF
9
10
  import android.graphics.drawable.Drawable
11
+ import android.os.Build
10
12
  import kotlin.math.max
11
13
 
12
14
  /**
13
- * A view's box: background color, rounded corners, border and a shadow drawn like iOS layers draw
14
- * theirs (color, opacity, blur radius, offset), outside the view's bounds. Sizes in pixels.
15
+ * A view's box: background color and gradients, rounded corners, border and a shadow drawn like iOS layers
16
+ * draw theirs (color, opacity, blur radius, offset), outside the view's bounds. Sizes in pixels.
15
17
  */
16
18
  class BoxDrawable : Drawable() {
17
19
  var backgroundColor = 0
20
+ /** backgroundImage (BackgroundGradients), the first on top; their lengths in dp, hence the density. */
21
+ var gradients: List<Map<*, *>> = emptyList()
22
+ var density = 1f
18
23
  var cornerRadius = 0f
24
+ /** Corners with their own radius, over cornerRadius: top left, top right, bottom right, bottom left. */
25
+ val cornerRadii = arrayOfNulls<Float>(4)
19
26
  var borderWidth = 0f
20
27
  var borderColor = 0
21
28
 
@@ -28,33 +35,62 @@ class BoxDrawable : Drawable() {
28
35
  private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG)
29
36
  private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
30
37
  private val rect = RectF()
38
+ private val boxPath = Path()
39
+ private val borderPath = Path()
40
+
41
+ /** Whether a corner has its own radius: the box is then a path, not a rounded rectangle. */
42
+ val hasCornerRadii: Boolean
43
+ get() = cornerRadii.any { it != null }
31
44
 
32
45
  override fun draw(canvas: Canvas) {
33
46
  rect.set(bounds)
47
+ val box = roundedPath(boxPath, rect, inset = 0f)
34
48
 
49
+ fillPaint.shader = null
35
50
  fillPaint.color = backgroundColor
36
- applyShadow()
37
- if (backgroundColor ushr 24 != 0) canvas.drawRoundRect(rect, cornerRadius, cornerRadius, fillPaint)
51
+ applyShadow(castsShadow = backgroundColor ushr 24 != 0)
52
+ if (backgroundColor ushr 24 != 0) canvas.drawPath(box, fillPaint)
53
+
54
+ // The bottom one casts the shadow when there's no background color.
55
+ gradients.asReversed().forEachIndexed { index, gradient ->
56
+ fillPaint.shader = BackgroundGradients.shader(gradient, rect.width(), rect.height(), density) ?: return@forEachIndexed
57
+ fillPaint.color = 0xFF000000.toInt()
58
+ applyShadow(castsShadow = index == 0 && backgroundColor ushr 24 == 0)
59
+ canvas.drawPath(box, fillPaint)
60
+ }
61
+ fillPaint.shader = null
38
62
 
39
63
  if (borderWidth > 0) {
40
64
  // The stroke is centered on the path: inset by half so it stays inside, like iOS borders.
41
65
  rect.inset(borderWidth / 2, borderWidth / 2)
42
66
  borderPaint.color = borderColor
43
67
  borderPaint.strokeWidth = borderWidth
44
- val radius = max(0f, cornerRadius - borderWidth / 2)
45
- canvas.drawRoundRect(rect, radius, radius, borderPaint)
68
+ canvas.drawPath(roundedPath(borderPath, rect, inset = borderWidth / 2), borderPaint)
46
69
  }
47
70
  }
48
71
 
72
+ /** [path] set to [bounds] with its corners rounded, each radius less [inset]. */
73
+ private fun roundedPath(path: Path, bounds: RectF, inset: Float): Path {
74
+ val radii = FloatArray(8) { index -> max(0f, (cornerRadii[index / 2] ?: cornerRadius) - inset) }
75
+
76
+ path.reset()
77
+ path.addRoundRect(bounds, radii, Path.Direction.CW)
78
+
79
+ return path
80
+ }
81
+
82
+ /** The box's shape, which a ContainerView clips its children to where its outline can't. */
83
+ fun outlinePath(): Path = roundedPath(Path(), RectF(bounds), inset = 0f)
84
+
49
85
  /**
50
86
  * Core Animation blurs with a sigma of half the shadow radius; Skia's blur radius r gives a sigma of
51
87
  * 0.57735 r + 0.5. The shadow takes the fill's alpha, like iOS (an invisible box casts none).
52
88
  */
53
- private fun applyShadow() {
89
+ private fun applyShadow(castsShadow: Boolean) {
54
90
  val sigma = shadowRadius / 2
55
91
  val alpha = ((shadowColor ushr 24) * shadowOpacity).toInt().coerceIn(0, 255)
56
92
 
57
- if (alpha == 0 || backgroundColor ushr 24 == 0) {
93
+ if (alpha == 0 || !castsShadow) {
58
94
  fillPaint.clearShadowLayer()
59
95
  return
60
96
  }
@@ -65,7 +101,11 @@ class BoxDrawable : Drawable() {
65
101
 
66
102
  /** `overflow: 'hidden'` clips to this outline, so rounded corners clip their content. */
67
103
  override fun getOutline(outline: Outline) {
68
- outline.setRoundRect(bounds, cornerRadius)
104
+ if (!hasCornerRadii) return outline.setRoundRect(bounds, cornerRadius)
105
+
106
+ val path = outlinePath()
107
+
108
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) outline.setPath(path) else @Suppress("DEPRECATION") outline.setConvexPath(path)
69
109
  }
70
110
 
71
111
  override fun setAlpha(alpha: Int) {}
@@ -880,7 +880,7 @@ class Bridge(private val activity: ComponentActivity, private val rootView: Root
880
880
  private fun setText(text: String, id: Int) {
881
881
  val node = nodesById[id] ?: return
882
882
 
883
- (node.view as? TextView)?.text = text
883
+ (node.view as? TextView)?.text = node.withLineHeight(text)
884
884
  node.markContentChanged()
885
885
  }
886
886
 
@@ -1167,7 +1167,7 @@ class Bridge(private val activity: ComponentActivity, private val rootView: Root
1167
1167
  }
1168
1168
 
1169
1169
  private companion object {
1170
- const val TAG = "Nativue"
1170
+ const val TAG = "nativue"
1171
1171
  const val JAVASCRIPT_STACK_SIZE = 8L * 1024 * 1024
1172
1172
  const val SYMBOLICATE_TIMEOUT_MS = 2000
1173
1173
  const val RECONNECT_DELAY_MS = 2000L
@@ -23,6 +23,10 @@ class NativeNode(val view: View, measuresContent: Boolean) {
23
23
 
24
24
  var fontSize = DEFAULT_FONT_SIZE
25
25
  var fontWeight = 400
26
+ var isItalic = false
27
+ /** Points, or ems of the font size ('1.5em'); null for the font's own. */
28
+ var letterSpacing: Any? = null
29
+ var lineHeight: Any? = null
26
30
 
27
31
  /** WindowInsets types that pad this node (safe area, keyboard), 0 for none, and the last padding. */
28
32
  var insetTypes = 0
@@ -3,6 +3,10 @@ package dev.nativue
3
3
  import android.content.Context
4
4
  import android.graphics.Paint
5
5
  import android.graphics.Typeface
6
+ import android.text.SpannableString
7
+ import android.text.Spanned
8
+ import android.text.TextUtils
9
+ import android.text.style.LineHeightSpan
6
10
  import android.util.TypedValue
7
11
  import android.view.Gravity
8
12
  import android.view.View
@@ -19,6 +23,7 @@ import com.facebook.yoga.YogaNode
19
23
  import com.facebook.yoga.YogaOverflow
20
24
  import com.facebook.yoga.YogaPositionType
21
25
  import com.facebook.yoga.YogaWrap
26
+ import kotlin.math.roundToInt
22
27
 
23
28
  /**
24
29
  * Receives only the properties that changed: the JS renderer diffs style objects before sending. A removed
@@ -48,7 +53,14 @@ private fun NativeNode.applyVisualProperty(property: String, value: Any?) {
48
53
 
49
54
  when (property) {
50
55
  "backgroundColor" -> updateBox { backgroundColor = androidColor(value) ?: 0 }
56
+ "backgroundImage" -> updateBox {
57
+ gradients = (value as? List<*>)?.filterIsInstance<Map<*, *>>().orEmpty()
58
+ density = view.resources.displayMetrics.density
59
+ }
51
60
  "borderRadius" -> updateBox { cornerRadius = pixels(value) }
61
+ "borderTopLeftRadius", "borderTopRightRadius", "borderBottomRightRadius", "borderBottomLeftRadius" -> updateBox {
62
+ cornerRadii[CORNERS.indexOf(property)] = value?.let { pixels(it) }
63
+ }
52
64
  "borderWidth" -> updateBox { borderWidth = pixels(value) }
53
65
  "borderColor" -> updateBox { borderColor = androidColor(value) ?: 0 }
54
66
  "shadowColor" -> updateBox { shadowColor = androidColor(value) ?: 0xFF000000.toInt() }
@@ -69,6 +81,26 @@ private fun NativeNode.applyVisualProperty(property: String, value: Any?) {
69
81
  }
70
82
  "textAlign" -> textView?.gravity = textGravities[value] ?: Gravity.START
71
83
  "textDecorationLine" -> textView?.let { it.paintFlags = decoratedPaintFlags(it.paintFlags, value as? String) }
84
+ "fontStyle" -> textView?.let {
85
+ isItalic = value == "italic"
86
+ it.typeface = typefaceOfWeight(it.context, fontWeight, isItalic)
87
+ markContentChanged()
88
+ }
89
+ "letterSpacing" -> {
90
+ letterSpacing = value
91
+ updateTextSpacing()
92
+ }
93
+ "lineHeight" -> {
94
+ lineHeight = value
95
+ updateTextSpacing()
96
+ }
97
+ "lineClamp" -> textView?.let {
98
+ val lines = number(value)?.toInt() ?: 0
99
+
100
+ it.maxLines = if (lines > 0) lines else Int.MAX_VALUE
101
+ it.ellipsize = if (lines > 0) TextUtils.TruncateAt.END else null
102
+ markContentChanged()
103
+ }
72
104
  }
73
105
  }
74
106
 
@@ -120,8 +152,8 @@ private fun degrees(value: Any?): Float {
120
152
  }
121
153
 
122
154
  /** The system font at a weight (100 to 900). */
123
- fun typefaceOfWeight(context: Context, weight: Int): Typeface =
124
- TypefaceCompat.create(context, Typeface.DEFAULT, weight, false)
155
+ fun typefaceOfWeight(context: Context, weight: Int, isItalic: Boolean = false): Typeface =
156
+ TypefaceCompat.create(context, Typeface.DEFAULT, weight, isItalic)
125
157
 
126
158
  /** Font size and weight can change independently, so the node remembers both. */
127
159
  private fun NativeNode.applyFont(changes: Map<String, Any?>) {
@@ -129,7 +161,7 @@ private fun NativeNode.applyFont(changes: Map<String, Any?>) {
129
161
  if ("fontWeight" in changes) fontWeight = changes["fontWeight"]?.let(::fontWeightOf) ?: 400
130
162
 
131
163
  val textView = view as? TextView ?: return
132
- textView.typeface = typefaceOfWeight(textView.context, fontWeight)
164
+ textView.typeface = typefaceOfWeight(textView.context, fontWeight, isItalic)
133
165
  updateFontSize()
134
166
  }
135
167
 
@@ -141,9 +173,52 @@ fun NativeNode.updateFontSize() {
141
173
  val textView = view as? TextView ?: return
142
174
  textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize)
143
175
 
176
+ if (letterSpacing != null || lineHeight != null) updateTextSpacing()
144
177
  markContentChanged()
145
178
  }
146
179
 
180
+ /** letterSpacing and lineHeight, which can be in ems of the font size: set again when that size changes. */
181
+ private fun NativeNode.updateTextSpacing() {
182
+ val textLabel = view as? TextLabel ?: return
183
+
184
+ // Android's is in ems already.
185
+ textLabel.letterSpacing = ems(letterSpacing) ?: number(letterSpacing)?.let { pixels(it) / textLabel.textSize } ?: 0f
186
+ textLabel.text = withLineHeight(textLabel.text.toString())
187
+ markContentChanged()
188
+ }
189
+
190
+ /** A <Text>'s text, its lines as tall as lineHeight when it has one. */
191
+ fun NativeNode.withLineHeight(text: String): CharSequence {
192
+ val textSize = (view as? TextLabel)?.textSize ?: return text
193
+ val height = ems(lineHeight)?.let { it * textSize } ?: number(lineHeight)?.let { pixels(it) } ?: return text
194
+
195
+ return SpannableString(text).apply {
196
+ setSpan(CenteredLineHeightSpan(height.roundToInt()), 0, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
197
+ }
198
+ }
199
+
200
+ /** "1.5em" as 1.5; null for anything else. */
201
+ private fun ems(value: Any?): Float? = (value as? String)?.takeIf { it.endsWith("em") }?.dropLast(2)?.toFloatOrNull()
202
+
203
+ /** Each line [height] pixels tall, the text centered in it, as CSS lays out a line height. */
204
+ private class CenteredLineHeightSpan(private val height: Int) : LineHeightSpan {
205
+ override fun chooseHeight(
206
+ text: CharSequence,
207
+ start: Int,
208
+ end: Int,
209
+ spanStart: Int,
210
+ lineHeight: Int,
211
+ metrics: Paint.FontMetricsInt,
212
+ ) {
213
+ val extra = height - (metrics.descent - metrics.ascent)
214
+
215
+ metrics.ascent -= extra / 2
216
+ metrics.descent += extra - extra / 2
217
+ metrics.top = metrics.ascent
218
+ metrics.bottom = metrics.descent
219
+ }
220
+ }
221
+
147
222
  private fun NativeNode.pixels(value: Any?): Float = (number(value) ?: 0f) * view.resources.displayMetrics.density
148
223
 
149
224
  fun number(value: Any?): Float? = (value as? Number)?.toFloat()
@@ -157,6 +232,9 @@ fun androidColor(value: Any?): Int? {
157
232
 
158
233
  // ---------- CSS value tables ----------
159
234
 
235
+ // In BoxDrawable.cornerRadii's order.
236
+ private val CORNERS = listOf("borderTopLeftRadius", "borderTopRightRadius", "borderBottomRightRadius", "borderBottomLeftRadius")
237
+
160
238
  private val edgesBySuffix = mapOf(
161
239
  "" to YogaEdge.ALL,
162
240
  "Horizontal" to YogaEdge.HORIZONTAL,
@@ -4,7 +4,11 @@ import android.annotation.SuppressLint
4
4
  import android.content.Context
5
5
  import android.graphics.Bitmap
6
6
  import android.graphics.BitmapFactory
7
+ import android.graphics.Canvas
8
+ import android.graphics.Matrix
7
9
  import android.graphics.Rect
10
+ import android.media.ExifInterface
11
+ import android.os.Build
8
12
  import android.os.Handler
9
13
  import android.os.Looper
10
14
  import android.os.SystemClock
@@ -14,9 +18,9 @@ import android.view.MotionEvent
14
18
  import android.view.View
15
19
  import android.view.ViewConfiguration
16
20
  import android.view.ViewGroup
21
+ import android.view.inputmethod.InputMethodManager
17
22
  import android.widget.FrameLayout
18
23
  import android.widget.HorizontalScrollView
19
- import android.view.inputmethod.InputMethodManager
20
24
  import android.widget.ImageView
21
25
  import android.widget.ProgressBar
22
26
  import android.widget.ScrollView
@@ -26,9 +30,9 @@ import java.io.IOException
26
30
  import java.net.URL
27
31
  import java.security.MessageDigest
28
32
  import java.util.concurrent.Executors
33
+ import kotlin.math.abs
29
34
  import kotlin.math.min
30
35
  import kotlin.math.roundToInt
31
- import kotlin.math.abs
32
36
 
33
37
  /**
34
38
  * A view whose children Yoga places (NativeNode.applyFrames): Android's own layout passes keep them
@@ -68,6 +72,19 @@ open class ContainerView(context: Context) : ViewGroup(context) {
68
72
  override fun onInterceptTouchEvent(event: MotionEvent): Boolean =
69
73
  gestureReporter?.isRecognizing == true || super.onInterceptTouchEvent(event)
70
74
 
75
+ /** Before Android 13 only a rounded rectangle outline clips: corners with their own radius clip here. */
76
+ override fun dispatchDraw(canvas: Canvas) {
77
+ val box = background as? BoxDrawable
78
+ if (!clipToOutline || box?.hasCornerRadii != true || Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
79
+ return super.dispatchDraw(canvas)
80
+ }
81
+
82
+ canvas.save()
83
+ canvas.clipPath(box.outlinePath())
84
+ super.dispatchDraw(canvas)
85
+ canvas.restore()
86
+ }
87
+
71
88
  /** Without an exact size (inside a scroll view), the size set in its layout params. */
72
89
  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
73
90
  setMeasuredDimension(
@@ -614,7 +631,7 @@ class RemoteImageView(context: Context) : ImageView(context) {
614
631
  val cachedBytes = if (readsDisk) diskCache.read(source) else null
615
632
  val downloadedBytes = if (cachedBytes == null) runCatching { download(source) }.getOrNull() else null
616
633
  val bytes = cachedBytes ?: downloadedBytes
617
- val bitmap = bytes?.let { BitmapFactory.decodeByteArray(it, 0, it.size) }
634
+ val bitmap = bytes?.let(::decodeUpright)
618
635
  if (bitmap == null) {
619
636
  mainThread.post(onFailed)
620
637
  return@execute
@@ -627,6 +644,29 @@ class RemoteImageView(context: Context) : ImageView(context) {
627
644
  }
628
645
  }
629
646
 
647
+ /** Turned as its EXIF orientation says, as cameras save photos sideways and leave the turn to the viewer. */
648
+ private fun decodeUpright(bytes: ByteArray): Bitmap? {
649
+ val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return null
650
+ val orientation = runCatching {
651
+ ExifInterface(bytes.inputStream()).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
652
+ }.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
653
+ val turn = Matrix().apply {
654
+ when (orientation) {
655
+ ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> postScale(-1f, 1f)
656
+ ExifInterface.ORIENTATION_ROTATE_180 -> postRotate(180f)
657
+ ExifInterface.ORIENTATION_FLIP_VERTICAL -> postScale(1f, -1f)
658
+ ExifInterface.ORIENTATION_TRANSPOSE -> postRotate(90f).also { postScale(-1f, 1f) }
659
+ ExifInterface.ORIENTATION_ROTATE_90 -> postRotate(90f)
660
+ ExifInterface.ORIENTATION_TRANSVERSE -> postRotate(270f).also { postScale(-1f, 1f) }
661
+ ExifInterface.ORIENTATION_ROTATE_270 -> postRotate(270f)
662
+ }
663
+ }
664
+
665
+ if (turn.isIdentity) return bitmap
666
+
667
+ return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, turn, true)
668
+ }
669
+
630
670
  private fun store(bitmap: Bitmap, downloadedBytes: ByteArray?, source: String, diskCache: ImageDiskCache, cachePolicy: String) {
631
671
  if (cachePolicy == "none") return
632
672
 
@@ -544,7 +544,7 @@ function nativueInfoPlist(app) {
544
544
  ],
545
545
  NSAppTransportSecurity: { NSAllowsLocalNetworking: true },
546
546
  NSLocalNetworkUsageDescription:
547
- 'Connects to the Nativue dev server on your Mac for hot reload.',
547
+ 'Connects to the nativue dev server on your Mac for hot reload.',
548
548
  UILaunchScreen: { UIColorName: 'LaunchBackground', UIImageName: 'LaunchLogo' },
549
549
  }
550
550
  }