peachsim 0.1.687 → 0.1.688

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.
Files changed (116) hide show
  1. package/cli/cloud-client.ts +3 -3
  2. package/cli/command-registry.ts +2 -0
  3. package/cli/commands/control.ts +1 -0
  4. package/cli/commands/debug.ts +10 -33
  5. package/cli/commands/do-chain.ts +56 -6
  6. package/cli/commands/inspect/core.ts +2 -0
  7. package/cli/commands/inspect/list.ts +2 -1
  8. package/cli/commands/inspect/settling.ts +17 -3
  9. package/cli/commands/inspect/shared.ts +2 -0
  10. package/cli/commands/inspect/wait-idle.ts +2 -2
  11. package/cli/commands/inspect/wait-ready.ts +3 -3
  12. package/cli/commands/inspect.ts +33 -7
  13. package/cli/commands/location.ts +164 -0
  14. package/cli/commands/platform.ts +1 -1
  15. package/cli/drivers/playwright-sim-host.ts +46 -25
  16. package/cli/main.ts +6 -0
  17. package/detox/index.ts +13 -8
  18. package/dist-lib/agent-daemon-client.cjs +1 -1
  19. package/dist-lib/agent-events.cjs +1 -1
  20. package/dist-lib/agent-identity.cjs +1 -1
  21. package/dist-lib/agent-sessions.cjs +1 -1
  22. package/dist-lib/attached-projects.cjs +1 -1
  23. package/dist-lib/auth/shared-session.cjs +1 -1
  24. package/dist-lib/backend-origin.cjs +1 -1
  25. package/dist-lib/beta.cjs +1 -1
  26. package/dist-lib/beta.mjs +1 -1
  27. package/dist-lib/bridge-constants.cjs +4 -3
  28. package/dist-lib/bridge-contract-input.cjs +12 -1
  29. package/dist-lib/bridge-contract-input.mjs +12 -1
  30. package/dist-lib/bridge-contract.cjs +4 -3
  31. package/dist-lib/bridge-contract.mjs +4 -3
  32. package/dist-lib/capture-contract.cjs +1 -1
  33. package/dist-lib/capture-contract.mjs +1 -1
  34. package/dist-lib/cli-constants.cjs +1 -1
  35. package/dist-lib/cloud-contract.cjs +2 -1
  36. package/dist-lib/cloud-contract.mjs +2 -1
  37. package/dist-lib/cloud-test-args.cjs +1 -1
  38. package/dist-lib/cloud-test-args.mjs +1 -1
  39. package/dist-lib/cloud.cjs +2 -1
  40. package/dist-lib/cloud.mjs +2 -1
  41. package/dist-lib/config.cjs +1 -1
  42. package/dist-lib/detox/index.cjs +1197 -65
  43. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  44. package/dist-lib/home-paths.cjs +1 -1
  45. package/dist-lib/host/bridge-host.cjs +362 -108
  46. package/dist-lib/host/fetch-proxy-handler.cjs +50 -40
  47. package/dist-lib/host/fetch-proxy-overrides.cjs +50 -6
  48. package/dist-lib/host/fetch-proxy-overrides.mjs +48 -5
  49. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  50. package/dist-lib/host/websocket-proxy.cjs +1 -1
  51. package/dist-lib/index.cjs +29 -11
  52. package/dist-lib/jump-to-source-babel.cjs +1 -1
  53. package/dist-lib/jump-to-source-native.cjs +1 -1
  54. package/dist-lib/kotlin-host.cjs +89 -13
  55. package/dist-lib/menu.cjs +1 -1
  56. package/dist-lib/menu.mjs +1 -1
  57. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  58. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  59. package/dist-lib/metro-production-bundle.cjs +1 -1
  60. package/dist-lib/metro-production-bundle.mjs +1 -1
  61. package/dist-lib/metro.cjs +5 -3
  62. package/dist-lib/native-app-identity.cjs +8 -3
  63. package/dist-lib/native-app-identity.mjs +8 -3
  64. package/dist-lib/native-firebase-metadata.cjs +1 -1
  65. package/dist-lib/native-firebase-metadata.mjs +1 -1
  66. package/dist-lib/plist.cjs +1 -1
  67. package/dist-lib/plist.mjs +1 -1
  68. package/dist-lib/profiles.cjs +1 -1
  69. package/dist-lib/public-brand.cjs +1 -1
  70. package/dist-lib/react-native-host-modules.cjs +1 -1
  71. package/dist-lib/react-native-host-modules.mjs +1 -1
  72. package/dist-lib/render-mode.cjs +1 -1
  73. package/dist-lib/scripts/dev-server-scanner.cjs +2 -2
  74. package/dist-lib/sdk.cjs +21 -6
  75. package/dist-lib/sdk.mjs +21 -6
  76. package/dist-lib/skills.cjs +401 -130
  77. package/dist-lib/swift-compile.cjs +277 -22
  78. package/dist-lib/swift-compile.mjs +275 -22
  79. package/dist-lib/swift-package.cjs +1 -1
  80. package/dist-lib/swift-package.mjs +1 -1
  81. package/dist-lib/swift-submit.cjs +2 -2
  82. package/dist-lib/swift-submit.mjs +2 -2
  83. package/dist-lib/swift-toolchain.cjs +10 -10
  84. package/dist-lib/swift.cjs +1 -1
  85. package/dist-lib/vite-swift.cjs +280 -44
  86. package/dist-lib/vite.cjs +1 -1
  87. package/kotlin/AppSources/android/content/res/Configuration.kt +2 -0
  88. package/kotlin/AppSources/android/content/res/Resources.kt +6 -3
  89. package/kotlin/AppSources/android/util/DisplayMetrics.kt +12 -0
  90. package/kotlin/AppSources/androidx/compose/ui/res/PainterResources.kt +70 -0
  91. package/kotlin/AppSources/dev/peach/app/PeachApp.kt +12 -10
  92. package/kotlin/AppSources/dev/peach/app/PeachDrawable.kt +95 -0
  93. package/kotlin/fixtures/kotlin-app-variants/Bitmaps.kt +50 -0
  94. package/kotlin/fixtures/kotlin-app-variants/Drawables.kt +53 -0
  95. package/package.json +2 -2
  96. package/scripts/dev-server-scanner.ts +3 -1
  97. package/skills/contrast/SKILL.md +1 -0
  98. package/src/android-drawables.ts +315 -0
  99. package/src/android-theme.ts +9 -0
  100. package/src/bridge-constants.ts +3 -2
  101. package/src/bridge-contract-input.ts +11 -0
  102. package/src/bridge-contract.ts +45 -3
  103. package/src/cloud-contract.ts +1 -0
  104. package/src/host/fetch-proxy-handler.ts +13 -49
  105. package/src/host/fetch-proxy-overrides.ts +69 -12
  106. package/src/kotlin-app.ts +6 -0
  107. package/src/kotlin-host.ts +103 -15
  108. package/src/native-app-identity.ts +16 -3
  109. package/src/swift-compile.ts +366 -24
  110. package/src/swift-distribution-contract.ts +11 -4
  111. package/src/swift-distribution.lock.json +11 -9
  112. package/src/swift-distribution.ts +4 -4
  113. package/src/swift-icu.ts +8 -11
  114. package/src/swift-submit.ts +13 -1
  115. package/src/swift-toolchain.ts +17 -9
  116. package/src/vite-plugin.ts +86 -34
@@ -39,6 +39,8 @@ import mounts
39
39
  import preparePeachDevice
40
40
  import robotoFamily
41
41
  import org.json.JSONObject
42
+ import android.util.DisplayMetrics
43
+ import kotlin.math.roundToInt
42
44
 
43
45
  // what the manifest, Gradle files and theme resolved: the launcher component
44
46
  // the intent names (an alias stays the alias), the activity class it runs, what
@@ -160,7 +162,10 @@ internal fun peachStartApp(
160
162
  try {
161
163
  require(backend == "graphite" || backend == "raster")
162
164
  preparePeachDevice(locale)
163
- processResources = Resources(deviceConfiguration(night, locale))
165
+ val metrics = DisplayMetrics()
166
+ metrics.densityDpi = (density * DisplayMetrics.DENSITY_DEFAULT).roundToInt()
167
+ metrics.density = metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT.toFloat()
168
+ processResources = Resources(deviceConfiguration(night, locale), metrics)
164
169
  val application = spec.createApplication()
165
170
  application.onCreate()
166
171
  val app = AppProcess(
@@ -216,7 +221,7 @@ private fun launchActivity(app: AppProcess, lastNonConfigurationInstance: Any?):
216
221
  }
217
222
  // the theme the activity is created under: a relaunch after a night
218
223
  // change takes the other one
219
- val theme = if (isNight(processResources.configuration)) spec.nightWindow else spec.dayWindow
224
+ val theme = if (processResources.configuration.isNight()) spec.nightWindow else spec.dayWindow
220
225
  window = Window(activity, theme, host)
221
226
  activity.attach(
222
227
  app.application,
@@ -234,10 +239,10 @@ private fun launchActivity(app: AppProcess, lastNonConfigurationInstance: Any?):
234
239
  app.paused = false
235
240
  app.stopped = false
236
241
  app.state = null
237
- app.reportedNight = isNight(activity.resources.configuration)
242
+ app.reportedNight = activity.resources.configuration.isNight()
238
243
  mount = PeachComposeMount(
239
244
  app.density, app.fontScale, app.locale, app.gpu, app.stencilBits, app.fonts, app.invalidate,
240
- night = isNight(activity.resources.configuration),
245
+ night = activity.resources.configuration.isNight(),
241
246
  owners = componentActivity?.let(::ActivityOwners),
242
247
  insets = DeviceInsets(window, app.insets) { app.ime },
243
248
  clockRunning = { componentActivity == null || componentActivity.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) },
@@ -327,21 +332,18 @@ internal fun peachAppTask(foreground: Boolean) {
327
332
  // configChanges uiMode. true when it relaunched.
328
333
  private fun reportConfiguration(app: AppProcess): Boolean {
329
334
  val configuration = processResources.configuration
330
- if (isNight(configuration) == app.reportedNight) return false
335
+ if (configuration.isNight() == app.reportedNight) return false
331
336
  if (!app.spec.handlesUiMode) {
332
337
  relaunch(app)
333
338
  return true
334
339
  }
335
- app.reportedNight = isNight(configuration)
340
+ app.reportedNight = configuration.isNight()
336
341
  app.activity.performConfigurationChanged(Configuration().apply { setTo(configuration) })
337
342
  app.configuration.value = Configuration().apply { setTo(configuration) }
338
343
  app.mount.night = app.reportedNight
339
344
  return false
340
345
  }
341
346
 
342
- private fun isNight(configuration: Configuration) =
343
- configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
344
-
345
347
  // the software keyboard moved: its inset reaches the window's content
346
348
  internal fun peachAppIme(bottom: Int) {
347
349
  val app = runningApp()
@@ -356,7 +358,7 @@ internal fun peachAppIme(bottom: Int) {
356
358
  internal fun peachAppNight(night: Boolean) {
357
359
  val app = runningApp()
358
360
  val configuration = processResources.configuration
359
- if (isNight(configuration) == night) return
361
+ if (configuration.isNight() == night) return
360
362
  configuration.setTo(deviceConfiguration(night, app.locale))
361
363
  app.application.onConfigurationChanged(Configuration().apply { setTo(configuration) })
362
364
  if (!app.stopped) reportConfiguration(app)
@@ -0,0 +1,95 @@
1
+ package dev.peach.app
2
+
3
+ import androidx.compose.ui.graphics.Brush
4
+ import androidx.compose.ui.graphics.Color
5
+ import androidx.compose.ui.graphics.ImageBitmap
6
+ import androidx.compose.ui.graphics.SolidColor
7
+ import androidx.compose.ui.graphics.toComposeImageBitmap
8
+ import androidx.compose.ui.graphics.vector.ImageVector
9
+ import kotlin.io.encoding.Base64
10
+ import kotlin.io.encoding.ExperimentalEncodingApi
11
+ import org.jetbrains.skia.BlendMode
12
+ import org.jetbrains.skia.FilterMipmap
13
+ import org.jetbrains.skia.FilterMode
14
+ import org.jetbrains.skia.Image
15
+ import org.jetbrains.skia.MipmapMode
16
+ import org.jetbrains.skia.Paint
17
+ import org.jetbrains.skia.Rect
18
+ import org.jetbrains.skia.Surface
19
+
20
+ // one file a drawable resource resolves to under a density (ResTable_config's
21
+ // value, 0 for an unqualified directory) and a platform version: a vector the
22
+ // build translated into ImageVector.Builder calls for a day or night
23
+ // configuration, a non-vector XML drawable, or an encoded bitmap
24
+ internal sealed class PeachDrawable(val path: String, val density: Int, val version: Int) {
25
+ class Vector(path: String, density: Int, version: Int, val build: (night: Boolean) -> ImageVector) :
26
+ PeachDrawable(path, density, version)
27
+ class Xml(path: String, density: Int, version: Int) : PeachDrawable(path, density, version)
28
+ class Bitmap(path: String, density: Int, version: Int, val ninePatch: Boolean, val data: String) :
29
+ PeachDrawable(path, density, version)
30
+ }
31
+
32
+ private const val DENSITY_DEFAULT = 0
33
+ private const val DENSITY_MEDIUM = 160
34
+ private const val DENSITY_ANY = 0xfffe
35
+ private const val DENSITY_NONE = 0xffff
36
+
37
+ // the file the resource table picks for the display's density, then the
38
+ // highest platform version
39
+ internal fun peachDrawable(files: List<PeachDrawable>, densityDpi: Int): PeachDrawable =
40
+ files.reduce { best, file -> if (isBetter(file, best, densityDpi)) file else best }
41
+
42
+ // ResTable_config::isBetterThan's density rule: anydpi wins, then between two
43
+ // densities on one side of the request the nearer, across it the larger
44
+ // unless the smaller is close enough
45
+ private fun isBetter(a: PeachDrawable, b: PeachDrawable, requested: Int): Boolean {
46
+ if (a.density != b.density) {
47
+ val thisDensity = if (a.density == DENSITY_DEFAULT) DENSITY_MEDIUM else a.density
48
+ val otherDensity = if (b.density == DENSITY_DEFAULT) DENSITY_MEDIUM else b.density
49
+ if (thisDensity == DENSITY_ANY) return true
50
+ if (otherDensity == DENSITY_ANY) return false
51
+ var high = thisDensity
52
+ var low = otherDensity
53
+ var bigger = true
54
+ if (low > high) {
55
+ high = otherDensity
56
+ low = thisDensity
57
+ bigger = false
58
+ }
59
+ if (requested >= high) return bigger
60
+ if (low >= requested) return !bigger
61
+ return if ((2 * low - requested) * high > requested * requested) !bigger else bigger
62
+ }
63
+ return a.version > b.version
64
+ }
65
+
66
+ // ImageDecoder.computeDensity, which resources decode drawables through: a
67
+ // bitmap drawn for a higher density than the display's is scaled down, its
68
+ // size rounded, through a linear filtered draw with the source blend; one
69
+ // drawn for a lower density, or nodpi, keeps its pixels, as from API 28 the
70
+ // upscale is left to draw time, which BitmapPainter does not do
71
+ @OptIn(ExperimentalEncodingApi::class)
72
+ internal fun peachDecodeBitmap(drawable: PeachDrawable.Bitmap, targetDensity: Int): ImageBitmap {
73
+ if (drawable.ninePatch)
74
+ throw UnsupportedOperationException("peach kotlin: the nine-patch drawable ${drawable.path} is not drawn yet")
75
+ val image = Image.makeFromEncoded(Base64.decode(drawable.data))
76
+ val density = if (drawable.density == DENSITY_DEFAULT) DENSITY_MEDIUM else drawable.density
77
+ if (drawable.density == DENSITY_NONE || density <= targetDensity) return image.toComposeImageBitmap()
78
+ val scale = targetDensity.toFloat() / density
79
+ val width = maxOf((image.width * scale + 0.5f).toInt(), 1)
80
+ val height = maxOf((image.height * scale + 0.5f).toInt(), 1)
81
+ val surface = Surface.makeRasterN32Premul(width, height)
82
+ surface.canvas.scale(width.toFloat() / image.width, height.toFloat() / image.height)
83
+ surface.canvas.drawImageRect(
84
+ image,
85
+ Rect.makeWH(image.width.toFloat(), image.height.toFloat()),
86
+ Rect.makeWH(image.width.toFloat(), image.height.toFloat()),
87
+ FilterMipmap(FilterMode.LINEAR, MipmapMode.NONE),
88
+ Paint().apply { blendMode = BlendMode.SRC },
89
+ false,
90
+ )
91
+ return surface.makeImageSnapshot().toComposeImageBitmap()
92
+ }
93
+
94
+ // ComplexColorCompat.willDraw: a transparent solid color draws nothing
95
+ internal fun peachBrush(argb: Int): Brush? = if (argb != 0) SolidColor(Color(argb)) else null
@@ -0,0 +1,50 @@
1
+ package dev.contrast.kotlinapp
2
+
3
+ import androidx.compose.foundation.Image
4
+ import androidx.compose.foundation.background
5
+ import androidx.compose.foundation.layout.Arrangement
6
+ import androidx.compose.foundation.layout.Column
7
+ import androidx.compose.foundation.layout.Row
8
+ import androidx.compose.foundation.layout.fillMaxSize
9
+ import androidx.compose.foundation.layout.padding
10
+ import androidx.compose.foundation.layout.safeDrawingPadding
11
+ import androidx.compose.foundation.layout.size
12
+ import androidx.compose.material3.Text
13
+ import androidx.compose.runtime.Composable
14
+ import androidx.compose.ui.Modifier
15
+ import androidx.compose.ui.graphics.Color
16
+ import androidx.compose.ui.graphics.ImageBitmap
17
+ import androidx.compose.ui.graphics.painter.Painter
18
+ import androidx.compose.ui.res.imageResource
19
+ import androidx.compose.ui.res.painterResource
20
+ import androidx.compose.ui.unit.dp
21
+
22
+ // bitmap drawables: each one's size after the decoder scales it from its
23
+ // density bucket to the display's, drawn at that size and stretched
24
+ @Composable
25
+ fun BitmapsScreen() {
26
+ val photo = painterResource(R.drawable.photo)
27
+ val plain = ImageBitmap.imageResource(R.drawable.plain)
28
+ val raw = painterResource(R.drawable.raw)
29
+ val near = painterResource(R.drawable.near)
30
+ val far = painterResource(R.drawable.far)
31
+ fun size(painter: Painter) = "${painter.intrinsicSize.width.toInt()}x${painter.intrinsicSize.height.toInt()}"
32
+ Column(
33
+ Modifier.fillMaxSize().background(Color(0xFFE8EEF8)).safeDrawingPadding().padding(16.dp),
34
+ verticalArrangement = Arrangement.spacedBy(16.dp),
35
+ ) {
36
+ Text("Bitmaps: ${size(photo)} ${plain.width}x${plain.height} ${size(raw)} ${size(near)} ${size(far)}")
37
+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
38
+ Image(photo, "photo")
39
+ Image(plain, "plain")
40
+ Image(raw, "raw")
41
+ Image(near, "near")
42
+ Image(far, "far")
43
+ }
44
+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
45
+ Image(photo, "photo large", Modifier.size(120.dp, 90.dp))
46
+ Image(plain, "plain large", Modifier.size(120.dp, 90.dp))
47
+ Image(raw, "raw large", Modifier.size(120.dp, 90.dp))
48
+ }
49
+ }
50
+ }
@@ -0,0 +1,53 @@
1
+ package dev.contrast.kotlinapp
2
+
3
+ import android.content.res.Resources
4
+ import androidx.compose.foundation.Image
5
+ import androidx.compose.foundation.background
6
+ import androidx.compose.foundation.isSystemInDarkTheme
7
+ import androidx.compose.foundation.layout.Arrangement
8
+ import androidx.compose.foundation.layout.Column
9
+ import androidx.compose.foundation.layout.Row
10
+ import androidx.compose.foundation.layout.fillMaxSize
11
+ import androidx.compose.foundation.layout.padding
12
+ import androidx.compose.foundation.layout.safeDrawingPadding
13
+ import androidx.compose.foundation.layout.size
14
+ import androidx.compose.material3.Text
15
+ import androidx.compose.runtime.Composable
16
+ import androidx.compose.runtime.remember
17
+ import androidx.compose.ui.Modifier
18
+ import androidx.compose.ui.graphics.Color
19
+ import androidx.compose.ui.graphics.vector.ImageVector
20
+ import androidx.compose.ui.platform.LocalResources
21
+ import androidx.compose.ui.res.painterResource
22
+ import androidx.compose.ui.res.vectorResource
23
+ import androidx.compose.ui.unit.dp
24
+
25
+ // vector drawables through painterResource and vectorResource: fills and
26
+ // strokes, groups with transforms and a clip path, trim, tint, a platform
27
+ // version override and a color values-night redefines
28
+ @Composable
29
+ fun DrawablesScreen() {
30
+ val resources = LocalResources.current
31
+ remember(resources) {
32
+ check(R.drawable.only_v99 != 0)
33
+ check(runCatching {
34
+ ImageVector.vectorResource(res = resources, resId = R.drawable.only_v99)
35
+ }.exceptionOrNull() is Resources.NotFoundException)
36
+ }
37
+ Column(
38
+ Modifier.fillMaxSize().background(Color(0xFFE8EEF8)).safeDrawingPadding().padding(16.dp),
39
+ verticalArrangement = Arrangement.spacedBy(16.dp),
40
+ ) {
41
+ Text("Drawables: dark " + isSystemInDarkTheme())
42
+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
43
+ Image(painterResource(R.drawable.ic_heart), "heart", Modifier.size(96.dp))
44
+ Image(painterResource(R.drawable.ic_group), "group", Modifier.size(96.dp))
45
+ Image(painterResource(R.drawable.ic_trim), "trim", Modifier.size(96.dp))
46
+ }
47
+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
48
+ Image(ImageVector.vectorResource(R.drawable.ic_tinted), "tinted", Modifier.size(96.dp))
49
+ Image(painterResource(R.drawable.ic_versioned), "versioned", Modifier.size(96.dp))
50
+ Image(painterResource(R.drawable.ic_heart), "intrinsic")
51
+ }
52
+ }
53
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peachsim",
3
- "version": "0.1.687",
3
+ "version": "0.1.688",
4
4
  "description": "Vite and Metro plugins, testing drivers, and SDK exports for peach.",
5
5
  "author": "Tamagui LLC",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -349,7 +349,7 @@
349
349
  "peach-kit": "workspace:*",
350
350
  "peach-cloud-box": "workspace:*",
351
351
  "peach-engine": "workspace:*",
352
- "typescript": "7.0.2",
352
+ "typescript": "7.1.0-dev.20261003.1",
353
353
  "vite": "^8.2.2",
354
354
  "json5": "^2.2.3",
355
355
  "yaml": "^2.8.3"
@@ -1328,5 +1328,7 @@ export async function scanDevServers(
1328
1328
  if (!livePids.has(pid)) cwdByPid.delete(pid)
1329
1329
  }
1330
1330
 
1331
- return results.filter((r) => !isSootSimSelfServer(r))
1331
+ // cached ports land before freshly probed ones, so arrival order changes
1332
+ // whenever a cache entry expires; port order keeps the dock from reshuffling
1333
+ return results.filter((r) => !isSootSimSelfServer(r)).sort((a, b) => a.port - b.port)
1332
1334
  }
@@ -28,6 +28,7 @@ automation, inspecting the render tree, and managing sims.
28
28
  | `peach film` | record a flow on the flat canvas, play it back on the 3d device stage under a camera cinematic, save a clip |
29
29
  | `peach storage` | manage guest app storage and launch profiles |
30
30
  | `peach permissions` | inspect and change simulated operating-system permissions |
31
+ | `peach location` | control the simulator's simulated device location |
31
32
  | `peach perf` | CPU, React render, shell frame, and scroll-layer profiling |
32
33
  | `peach describe` | curated human-readable UI summary (default inspection tool) |
33
34
  | `peach find` | locate nodes by text / testID / role / type / predicate |
@@ -0,0 +1,315 @@
1
+ // an Android module's drawables as painterResource loads them on the device:
2
+ // every name, with files under the platform versions the device meets, each with
3
+ // the density it was drawn for, for the device to choose between. a vector
4
+ // XML is the ImageVector.Builder calls compose's XmlVectorParser makes from
5
+ // it (attribute defaults, group and clip-path nesting, colors resolved for
6
+ // day and night), any other XML drawable the non-vector XML painterResource
7
+ // refuses. a qualifier Peach does not resolve, or an attribute value it does
8
+ // not read (a theme attribute, a dimension resource, a gradient), is rejected
9
+ // by name.
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+ import { attributeColor, type ThemeSources } from './android-theme'
13
+ import { parseXml, type XmlElement } from './android-xml'
14
+
15
+ export interface DayNight {
16
+ day: number
17
+ night: number
18
+ }
19
+
20
+ export type VectorCall =
21
+ | {
22
+ call: 'path'
23
+ name: string
24
+ pathData: string
25
+ fillType: 'NonZero' | 'EvenOdd'
26
+ fill: DayNight
27
+ fillAlpha: number
28
+ stroke: DayNight
29
+ strokeAlpha: number
30
+ strokeWidth: number
31
+ cap: 'Butt' | 'Round' | 'Square'
32
+ join: 'Miter' | 'Round' | 'Bevel'
33
+ miter: number
34
+ trimStart: number
35
+ trimEnd: number
36
+ trimOffset: number
37
+ }
38
+ | {
39
+ call: 'group'
40
+ name: string
41
+ rotate: number
42
+ pivotX: number
43
+ pivotY: number
44
+ scaleX: number
45
+ scaleY: number
46
+ translateX: number
47
+ translateY: number
48
+ }
49
+ | { call: 'clip'; name: string; pathData: string }
50
+ | { call: 'clear' }
51
+
52
+ export interface VectorDrawable {
53
+ width: number
54
+ height: number
55
+ viewportWidth: number
56
+ viewportHeight: number
57
+ // null when unset or a theme attribute, which XmlVectorParser ignores
58
+ tint: DayNight | null
59
+ tintMode: 'SrcOver' | 'SrcIn' | 'SrcAtop' | 'Modulate' | 'Screen' | 'Plus'
60
+ autoMirror: boolean
61
+ calls: VectorCall[]
62
+ }
63
+
64
+ // one file a drawable name resolves to under a density and platform version
65
+ export type DrawableFile = { file: string; density: number; version: number } & (
66
+ | { kind: 'vector'; vector: VectorDrawable }
67
+ | { kind: 'xml' }
68
+ | { kind: 'bitmap'; ninePatch: boolean }
69
+ )
70
+
71
+ // a name's files; the device picks one for its display density at runtime
72
+ export interface AndroidDrawable {
73
+ name: string
74
+ files: DrawableFile[]
75
+ }
76
+
77
+ // the device the oracle measures runs API 37
78
+ const DEVICE_API = 37
79
+ // ResTable_config's density values, as the resource table records them
80
+ const BUCKETS: Record<string, number> = {
81
+ ldpi: 120,
82
+ mdpi: 160,
83
+ tvdpi: 213,
84
+ hdpi: 240,
85
+ xhdpi: 320,
86
+ xxhdpi: 480,
87
+ xxxhdpi: 640,
88
+ anydpi: 0xfffe,
89
+ nodpi: 0xffff,
90
+ }
91
+ const DRAWABLE_DIR = /^drawable(?:-([a-z]+|\d+dpi))?(?:-v(\d+))?$/
92
+ const BITMAP = /\.(?:9\.png|png|jpe?g|webp|gif)$/
93
+
94
+ export function readAndroidDrawables(
95
+ moduleDir: string,
96
+ sources: { day: ThemeSources; night: ThemeSources },
97
+ ): AndroidDrawable[] {
98
+ const res = path.join(moduleDir, 'src/main/res')
99
+ const byName = new Map<string, DrawableFile[]>()
100
+ for (const dir of fs.existsSync(res) ? fs.readdirSync(res).sort() : []) {
101
+ if (!dir.startsWith('drawable')) continue
102
+ const match = DRAWABLE_DIR.exec(dir)
103
+ const qualifier = match?.[1]
104
+ // an unqualified directory is the default density, 0
105
+ const density =
106
+ qualifier === undefined
107
+ ? 0
108
+ : (BUCKETS[qualifier] ??
109
+ (/^\d+dpi$/.test(qualifier) ? Number.parseInt(qualifier, 10) : -1))
110
+ if (!match || density === -1)
111
+ throw new Error(
112
+ `${res}/${dir}: drawables under this qualifier are not resolved by peach kotlin yet`,
113
+ )
114
+ const version = Number(match[2] ?? 0)
115
+ for (const entry of fs.readdirSync(path.join(res, dir)).sort()) {
116
+ if (!entry.endsWith('.xml') && !BITMAP.test(entry)) continue
117
+ const name = entry.replace(BITMAP, '').replace(/\.xml$/, '')
118
+ const file = path.join(res, dir, entry)
119
+ const files = byName.get(name) ?? []
120
+ // aapt retains the identifier even when no file matches the device.
121
+ byName.set(name, files)
122
+ if (version > DEVICE_API) continue
123
+ if (BITMAP.test(entry))
124
+ files.push({
125
+ file,
126
+ density,
127
+ version,
128
+ kind: 'bitmap',
129
+ ninePatch: entry.endsWith('.9.png'),
130
+ })
131
+ else {
132
+ const root = parseXml(fs.readFileSync(file, 'utf8'), file).children[0]
133
+ files.push(
134
+ root?.name === 'vector'
135
+ ? {
136
+ file,
137
+ density,
138
+ version,
139
+ kind: 'vector',
140
+ vector: readVector(root, file, sources),
141
+ }
142
+ : { file, density, version, kind: 'xml' },
143
+ )
144
+ }
145
+ }
146
+ }
147
+ return [...byName.entries()]
148
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
149
+ .map(([name, files]) => ({ name, files }))
150
+ }
151
+
152
+ function readVector(
153
+ root: XmlElement,
154
+ file: string,
155
+ sources: { day: ThemeSources; night: ThemeSources },
156
+ ): VectorDrawable {
157
+ const read = (element: XmlElement) => {
158
+ for (const child of element.children)
159
+ if (child.name.startsWith('aapt:'))
160
+ throw new Error(
161
+ `${file}: <${element.name}> has an inline ${child.name} (a gradient), not resolved by peach kotlin yet`,
162
+ )
163
+ const raw = (key: string) => element.attributes[`android:${key}`]
164
+ const reference = (key: string, value: string) => {
165
+ if (/^[@?]/.test(value))
166
+ throw new Error(
167
+ `${file}: <${element.name}> ${key}="${value}" is a reference, not resolved by peach kotlin yet`,
168
+ )
169
+ }
170
+ const float = (key: string, fallback: number) => {
171
+ const value = raw(key)
172
+ if (value === undefined) return fallback
173
+ reference(key, value)
174
+ const number = Number(value)
175
+ if (!Number.isFinite(number))
176
+ throw new Error(`${file}: <${element.name}> ${key}="${value}" is not a number`)
177
+ return number
178
+ }
179
+ const dimension = (key: string) => {
180
+ const value = raw(key)
181
+ if (value === undefined) return 0
182
+ reference(key, value)
183
+ const match = /^(-?[\d.]+)(?:dp|dip)$/.exec(value)
184
+ if (!match)
185
+ throw new Error(
186
+ `${file}: <${element.name}> ${key}="${value}" is not in dp, the unit peach kotlin reads`,
187
+ )
188
+ return Number(match[1])
189
+ }
190
+ const choice = <Value extends string>(
191
+ key: string,
192
+ values: Record<string, Value>,
193
+ fallback: Value,
194
+ ) => {
195
+ const value = raw(key)
196
+ if (value === undefined) return fallback
197
+ const chosen = values[value]
198
+ if (!chosen)
199
+ throw new Error(
200
+ `${file}: <${element.name}> ${key}="${value}" is not one of ${Object.keys(values).join(', ')}`,
201
+ )
202
+ return chosen
203
+ }
204
+ const color = (key: string): DayNight => {
205
+ const value = raw(key)
206
+ if (value === undefined) return { day: 0, night: 0 }
207
+ if (value.startsWith('?'))
208
+ throw new Error(
209
+ `${file}: <${element.name}> ${key}="${value}" is a theme attribute, not resolved by peach kotlin yet`,
210
+ )
211
+ return {
212
+ day: attributeColor(value, sources.day),
213
+ night: attributeColor(value, sources.night),
214
+ }
215
+ }
216
+ return { raw, float, dimension, choice, color }
217
+ }
218
+ const vector = read(root)
219
+ const viewportWidth = vector.float('viewportWidth', 0)
220
+ const viewportHeight = vector.float('viewportHeight', 0)
221
+ if (viewportWidth <= 0) throw new Error(`${file}: <vector> requires viewportWidth > 0`)
222
+ if (viewportHeight <= 0)
223
+ throw new Error(`${file}: <vector> requires viewportHeight > 0`)
224
+ const tint = vector.raw('tint')
225
+ const calls: VectorCall[] = []
226
+ // parseCurrentVectorNode: a clip-path opens a group closed with its
227
+ // enclosing group, so each group end clears its clip-path groups too
228
+ const walk = (element: XmlElement, nested: number): number => {
229
+ const node = read(element)
230
+ if (element.name === 'path') {
231
+ const pathData = node.raw('pathData')
232
+ if (pathData === undefined) throw new Error(`${file}: <path> has no pathData`)
233
+ calls.push({
234
+ call: 'path',
235
+ name: node.raw('name') ?? '',
236
+ pathData,
237
+ fillType: node.choice(
238
+ 'fillType',
239
+ { nonZero: 'NonZero', evenOdd: 'EvenOdd' },
240
+ 'NonZero',
241
+ ),
242
+ fill: node.color('fillColor'),
243
+ fillAlpha: node.float('fillAlpha', 1),
244
+ stroke: node.color('strokeColor'),
245
+ strokeAlpha: node.float('strokeAlpha', 1),
246
+ strokeWidth: node.float('strokeWidth', 1),
247
+ cap: node.choice(
248
+ 'strokeLineCap',
249
+ { butt: 'Butt', round: 'Round', square: 'Square' },
250
+ 'Butt',
251
+ ),
252
+ join: node.choice(
253
+ 'strokeLineJoin',
254
+ { miter: 'Miter', round: 'Round', bevel: 'Bevel' },
255
+ 'Miter',
256
+ ),
257
+ miter: node.float('strokeMiterLimit', 4),
258
+ trimStart: node.float('trimPathStart', 0),
259
+ trimEnd: node.float('trimPathEnd', 1),
260
+ trimOffset: node.float('trimPathOffset', 0),
261
+ })
262
+ return nested
263
+ }
264
+ if (element.name === 'clip-path') {
265
+ calls.push({
266
+ call: 'clip',
267
+ name: node.raw('name') ?? '',
268
+ pathData: node.raw('pathData') ?? '',
269
+ })
270
+ return nested + 1
271
+ }
272
+ if (element.name === 'group') {
273
+ calls.push({
274
+ call: 'group',
275
+ name: node.raw('name') ?? '',
276
+ rotate: node.float('rotation', 0),
277
+ pivotX: node.float('pivotX', 0),
278
+ pivotY: node.float('pivotY', 0),
279
+ scaleX: node.float('scaleX', 1),
280
+ scaleY: node.float('scaleY', 1),
281
+ translateX: node.float('translateX', 0),
282
+ translateY: node.float('translateY', 0),
283
+ })
284
+ let inner = 0
285
+ for (const child of element.children) inner = walk(child, inner)
286
+ for (let index = 0; index <= inner; index++) calls.push({ call: 'clear' })
287
+ return nested
288
+ }
289
+ // the pull parser still reaches the children of a tag it ignores
290
+ return element.children.reduce((inner, child) => walk(child, inner), nested)
291
+ }
292
+ // clip-path groups left open at the root close in build()
293
+ root.children.reduce((nested, child) => walk(child, nested), 0)
294
+ return {
295
+ width: vector.dimension('width'),
296
+ height: vector.dimension('height'),
297
+ viewportWidth,
298
+ viewportHeight,
299
+ tint: tint === undefined || tint.startsWith('?') ? null : vector.color('tint'),
300
+ tintMode: vector.choice(
301
+ 'tintMode',
302
+ {
303
+ src_over: 'SrcOver',
304
+ src_in: 'SrcIn',
305
+ src_atop: 'SrcAtop',
306
+ multiply: 'Modulate',
307
+ screen: 'Screen',
308
+ add: 'Plus',
309
+ },
310
+ 'SrcIn',
311
+ ),
312
+ autoMirror: vector.raw('autoMirrored') === 'true',
313
+ calls,
314
+ }
315
+ }
@@ -195,3 +195,12 @@ export function resourceColor(
195
195
  ref = { namespace: nextNamespace, name: next[2] }
196
196
  }
197
197
  }
198
+
199
+ // a color an app XML attribute writes directly: a hex literal or a reference
200
+ // to an app or framework color resource
201
+ export function attributeColor(value: string, sources: ThemeSources): number {
202
+ if (value.startsWith('#')) return color(value)
203
+ const ref = /^@(?:(android):)?color\/(.+)$/.exec(value)
204
+ if (!ref?.[2]) throw new Error(`the color ${value} is not resolved by peach kotlin yet`)
205
+ return resourceColor(ref[1] ? 'android' : 'app', ref[2], sources)
206
+ }
@@ -97,8 +97,9 @@ export function resolveSootsimBridgePortForRuntimeLocation(
97
97
  const hrefUrl = parseHrefUrl(input.href)
98
98
  const httpPort = parsePort(input.httpPort) ?? parsePort(hrefUrl?.port)
99
99
  if (httpPort === null) return DEFAULT_SOOTSIM_BRIDGE_PORT
100
+ const hostedShell = hrefUrl && /^\/(?:simulator|sootsim)(?:\/|$)/.test(hrefUrl.pathname)
100
101
  if (
101
- hrefUrl?.pathname.startsWith('/sootsim') &&
102
+ hostedShell &&
102
103
  (hrefUrl.searchParams.has('embed') || hrefUrl.searchParams.has('nativePreview'))
103
104
  ) {
104
105
  return resolveSootsimBridgePortForHttpPort({
@@ -107,7 +108,7 @@ export function resolveSootsimBridgePortForRuntimeLocation(
107
108
  })
108
109
  }
109
110
  if (
110
- hrefUrl?.pathname.startsWith('/sootsim') &&
111
+ hostedShell &&
111
112
  httpPort >= SOOTSIM_SITE_DEV_HTTP_BASE_PORT &&
112
113
  httpPort <= SOOTSIM_SITE_DEV_HTTP_BASE_PORT + MAX_LOCAL_DEV_PORT_OFFSET
113
114
  ) {
@@ -192,6 +192,17 @@ export function parsePerformStep(value: unknown, index: number): SimPerformStep
192
192
  }
193
193
  case 'type':
194
194
  return { type, text: stringValue(step.text, `${path}.text`) }
195
+ case 'typeInto': {
196
+ const nodeId = numberValue(step.nodeId, `${path}.nodeId`)
197
+ if (!Number.isSafeInteger(nodeId) || nodeId === 0) {
198
+ validationFailure(`${path}.nodeId`, 'must be a nonzero safe integer')
199
+ }
200
+ return {
201
+ type,
202
+ text: stringValue(step.text, `${path}.text`),
203
+ nodeId,
204
+ }
205
+ }
195
206
  case 'key':
196
207
  return { type, key: stringValue(step.key, `${path}.key`) }
197
208
  case 'dismissKeyboard':