@g9tm/app-diagnostic-lynx 0.2.0 → 0.2.2

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.
@@ -23,6 +23,7 @@ with the command that proved it and the date. Nothing here is claimed from a Nod
23
23
  | Voice | two notes (permission granted beforehand) | two `.m4a` of ~79 KB |
24
24
  | Window screenshot | the gesture's shot | a 363 KB JPEG of the window, the map included |
25
25
  | `sendRange` on the host's client | a whole tester report through a local fake gateway over HTTPS (self-signed, trusted only by the host's dev-host trust) | 10 PUTs of 64 KB read natively; a dropped answer → retry → 416 → resumed at the gateway's offset; the hash matched at finalize. The host hook `httpClient` is what made the TLS trust apply |
26
+ | N-AD-03 — a pinch on the map with the gesture armed (DOOGEE, 2026-11-13, a tester report) | 8 real two-finger pinches on the map in the «any screen» mode | 7.0.24 HELD the first finger and replayed late: at the 350 ms limit MapLibre never began its scale, so the pinch failed now and then. The hold now never applies over an excluded surface, in any mode (`TouchCore`: `!downExcluded`); after it 8/8 pinches zoomed and MapLibre's `scale-begin` is in the app log |
26
27
 
27
28
  ## Pending
28
29
 
@@ -30,4 +31,3 @@ with the command that proved it and the date. Nothing here is claimed from a Nod
30
31
  | --- | --- | --- |
31
32
  | **N-AD-01b** The same on a phone (the gesture with real fingers, the microphone with a real voice) | An emulator injects touches into the decor view and records silence | A Didban session on a lab phone (P7.7) |
32
33
  | **N-AD-02** iOS (`ios/src`) | Not written yet in this package: the app's `AGMedia.mm` / `AGFiles.mm` move here with neutral names | A build on the Mac through a Didban session (the Mac is reserved for Didban) |
33
- | **N-AD-03** The gesture's pinch replay on a real map (MapLibre) | A replay a slop late must still zoom | Emulator with two-finger input, then a phone |
package/README.md CHANGED
@@ -1,42 +1,42 @@
1
- # @g9tm/app-diagnostic-lynx
2
-
3
- The Lynx native half of [`@g9tm/app-diagnostic`](../app-diagnostic): what the tester mode and the live channel need from the
4
- device, with no product name anywhere.
5
-
6
- | Method | What |
7
- | --- | --- |
8
- | `capabilities` / `state` | what this device can record; which recorder runs now (a recorder outlives a script reload) |
9
- | `startScreen` / `stopScreen` | the app's OWN window as an H.264 MP4 (≤ 960 px, adaptive 4-20 fps, 10 minutes at most, no system consent) |
10
- | `startVoice` / `stopVoice` | a spoken note as AAC `.m4a`; the microphone permission is asked at the first note |
11
- | `screenshot` | the window as the user sees it, a map's surface included, as JPEG |
12
- | `sendRange` | one HTTP request whose body is a byte range of a file, read natively (the resumable report upload) |
13
- | `watchTouches` | the tester gesture: multi-finger taps and first touches as the global event `g9:diagnostic-touch`; with `consume`, a two-finger touch is held away from the views and replayed when it is a pinch or a pan (E-20) |
14
-
15
- The contract (methods, envelopes, error codes, the event) is `types/g9-app-diagnostic-module.d.ts`; `npm run codegen`-style
16
- regeneration is `lynx-autolink-codegen` then `node scripts/android-bridge-types.mjs --fix`.
17
-
18
- ## Host hooks (Android)
19
-
20
- Set before the first call, typically in `Application.onCreate`:
21
-
22
- ```kotlin
23
- G9AppDiagnosticHost.httpClient = { myOkHttpClient } // its trust and proxy rules for the range PUT
24
- G9AppDiagnosticHost.allowedRoots = { listOf(it.filesDir, it.cacheDir) }
25
- G9AppDiagnosticHost.isExcludedView = { it.javaClass.simpleName == "MapHost" } // the «except the map» mode
26
- ```
27
-
28
- The host's activity needs no edit: the gesture wraps the activity window's callback itself.
29
-
30
- ## JS
31
-
32
- ```ts
33
- import { createDiagnosticNative, nativeSendRange, onDiagnosticTouch } from '@g9tm/app-diagnostic-lynx';
34
- const native = createDiagnosticNative();
35
- await native.watchTouches({ taps: true, touches: false, consume: true, excludeSurfaces: false });
36
- const off = onDiagnosticTouch(lynx.getJSModule('GlobalEventEmitter'), (e) => pair(e));
37
- ```
38
-
39
- ## Checks
40
-
41
- `npm test` (JS face) · `npm run test:android-jvm` (the gesture's decisions) · `npm run check:android-module` (the module
42
- against Lynx 4.1.0 and the bridge's signatures). What is proven and what is not: [Native-Validation-Pending.md](Native-Validation-Pending.md).
1
+ # @g9tm/app-diagnostic-lynx
2
+
3
+ The Lynx native half of [`@g9tm/app-diagnostic`](../app-diagnostic): what the tester mode and the live channel need from the
4
+ device, with no product name anywhere.
5
+
6
+ | Method | What |
7
+ | --- | --- |
8
+ | `capabilities` / `state` | what this device can record; which recorder runs now (a recorder outlives a script reload) |
9
+ | `startScreen` / `stopScreen` | the app's OWN window as an H.264 MP4 (≤ 960 px, adaptive 4-20 fps, 10 minutes at most, no system consent) |
10
+ | `startVoice` / `stopVoice` | a spoken note as AAC `.m4a`; the microphone permission is asked at the first note |
11
+ | `screenshot` | the window as the user sees it, a map's surface included, as JPEG |
12
+ | `sendRange` | one HTTP request whose body is a byte range of a file, read natively (the resumable report upload) |
13
+ | `watchTouches` | the tester gesture: multi-finger taps (with the fingers' midpoint `cx`, `cy`) and first touches as the global event `g9:diagnostic-touch`; with `touches`, also a `seq` trace of every touch that could have been a tap (why it was or was not one); with `consume`, a two-finger touch is held away from the views and replayed when it is a pinch or a pan (E-20). A finger «moved» only when it left its own landing point |
14
+
15
+ The contract (methods, envelopes, error codes, the event) is `types/g9-app-diagnostic-module.d.ts`; `npm run codegen`-style
16
+ regeneration is `lynx-autolink-codegen` then `node scripts/android-bridge-types.mjs --fix`.
17
+
18
+ ## Host hooks (Android)
19
+
20
+ Set before the first call, typically in `Application.onCreate`:
21
+
22
+ ```kotlin
23
+ G9AppDiagnosticHost.httpClient = { myOkHttpClient } // its trust and proxy rules for the range PUT
24
+ G9AppDiagnosticHost.allowedRoots = { listOf(it.filesDir, it.cacheDir) }
25
+ G9AppDiagnosticHost.isExcludedView = { it.javaClass.simpleName == "MapHost" } // the «except the map» mode
26
+ ```
27
+
28
+ The host's activity needs no edit: the gesture wraps the activity window's callback itself.
29
+
30
+ ## JS
31
+
32
+ ```ts
33
+ import { createDiagnosticNative, nativeSendRange, onDiagnosticTouch } from '@g9tm/app-diagnostic-lynx';
34
+ const native = createDiagnosticNative();
35
+ await native.watchTouches({ taps: true, touches: false, consume: true, excludeSurfaces: false });
36
+ const off = onDiagnosticTouch(lynx.getJSModule('GlobalEventEmitter'), (e) => pair(e));
37
+ ```
38
+
39
+ ## Checks
40
+
41
+ `npm test` (JS face) · `npm run test:android-jvm` (the gesture's decisions) · `npm run check:android-module` (the module
42
+ against Lynx 4.1.0 and the bridge's signatures). What is proven and what is not: [Native-Validation-Pending.md](Native-Validation-Pending.md).
@@ -1,45 +1,45 @@
1
- // @g9tm/app-diagnostic-lynx for Android. Linked into a host by Lynx Autolink from node_modules; the host's settings supply
2
- // the plugin versions (AGP, Kotlin), like @g9tm/syncdata-lynx.
3
- plugins {
4
- id("com.android.library")
5
- id("org.jetbrains.kotlin.android")
6
- id("org.jetbrains.kotlin.kapt")
7
- }
8
-
9
- android {
10
- namespace = "com.g9tm.appdiagnostic"
11
- compileSdk = 36
12
-
13
- defaultConfig {
14
- minSdk = 26
15
- consumerProguardFiles("consumer-rules.pro")
16
- }
17
-
18
- compileOptions {
19
- sourceCompatibility = JavaVersion.VERSION_17
20
- targetCompatibility = JavaVersion.VERSION_17
21
- }
22
-
23
- testOptions { unitTests.isReturnDefaultValues = true }
24
- }
25
-
26
- kotlin { jvmToolchain(17) }
27
-
28
- val lynx = "4.1.0"
29
-
30
- dependencies {
31
- compileOnly("org.lynxsdk.lynx:lynx:$lynx")
32
- compileOnly("org.lynxsdk.lynx:service-api:$lynx")
33
- kapt("org.lynxsdk.lynx:lynx-processor:$lynx")
34
- // The generated spec imports androidx.annotation and lynx-processor's output uses @Keep, but Lynx's POMs declare it
35
- // at runtime scope only: without this line kapt fails in the host ("cannot access Keep").
36
- compileOnly("androidx.annotation:annotation:1.9.1")
37
- // The microphone permission goes through the host activity's ActivityResultRegistry (every ComponentActivity has one).
38
- compileOnly("androidx.activity:activity:1.10.1")
39
- implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
40
- // The range PUT; a host passes its own client (G9AppDiagnosticHost.httpClient) so its trust and proxy rules apply.
41
- implementation("com.squareup.okhttp3:okhttp:4.12.0")
42
-
43
- // The JVM suite (../jvm) also runs as Android local unit tests.
44
- testImplementation("junit:junit:4.13.2")
45
- }
1
+ // @g9tm/app-diagnostic-lynx for Android. Linked into a host by Lynx Autolink from node_modules; the host's settings supply
2
+ // the plugin versions (AGP, Kotlin), like @g9tm/syncdata-lynx.
3
+ plugins {
4
+ id("com.android.library")
5
+ id("org.jetbrains.kotlin.android")
6
+ id("org.jetbrains.kotlin.kapt")
7
+ }
8
+
9
+ android {
10
+ namespace = "com.g9tm.appdiagnostic"
11
+ compileSdk = 36
12
+
13
+ defaultConfig {
14
+ minSdk = 26
15
+ consumerProguardFiles("consumer-rules.pro")
16
+ }
17
+
18
+ compileOptions {
19
+ sourceCompatibility = JavaVersion.VERSION_17
20
+ targetCompatibility = JavaVersion.VERSION_17
21
+ }
22
+
23
+ testOptions { unitTests.isReturnDefaultValues = true }
24
+ }
25
+
26
+ kotlin { jvmToolchain(17) }
27
+
28
+ val lynx = "4.2.0"
29
+
30
+ dependencies {
31
+ compileOnly("org.lynxsdk.lynx:lynx:$lynx")
32
+ compileOnly("org.lynxsdk.lynx:service-api:$lynx")
33
+ kapt("org.lynxsdk.lynx:lynx-processor:$lynx")
34
+ // The generated spec imports androidx.annotation and lynx-processor's output uses @Keep, but Lynx's POMs declare it
35
+ // at runtime scope only: without this line kapt fails in the host ("cannot access Keep").
36
+ compileOnly("androidx.annotation:annotation:1.9.1")
37
+ // The microphone permission goes through the host activity's ActivityResultRegistry (every ComponentActivity has one).
38
+ compileOnly("androidx.activity:activity:1.10.1")
39
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
40
+ // The range PUT; a host passes its own client (G9AppDiagnosticHost.httpClient) so its trust and proxy rules apply.
41
+ implementation("com.squareup.okhttp3:okhttp:4.12.0")
42
+
43
+ // The JVM suite (../jvm) also runs as Android local unit tests.
44
+ testImplementation("junit:junit:4.13.2")
45
+ }
@@ -1,2 +1,2 @@
1
- # The module and its generated spec are found by name through Lynx's registry (LynxLibraryProviderImpl).
2
- -keep class com.g9tm.appdiagnostic.** { *; }
1
+ # The module and its generated spec are found by name through Lynx's registry (LynxLibraryProviderImpl).
2
+ -keep class com.g9tm.appdiagnostic.** { *; }
@@ -1,5 +1,5 @@
1
- <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
- <!-- The tester's spoken note. Asked at the first note, never at start-up. -->
3
- <uses-permission android:name="android.permission.RECORD_AUDIO" />
4
- <application />
5
- </manifest>
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <!-- The tester's spoken note. Asked at the first note, never at start-up. -->
3
+ <uses-permission android:name="android.permission.RECORD_AUDIO" />
4
+ <application />
5
+ </manifest>
@@ -1,131 +1,131 @@
1
- package com.g9tm.appdiagnostic
2
-
3
- import android.app.Activity
4
- import android.app.Application
5
- import android.content.Context
6
- import android.content.ContextWrapper
7
- import android.os.Bundle
8
- import android.view.View
9
- import com.lynx.react.bridge.JavaOnlyArray
10
- import com.lynx.tasm.behavior.LynxContext
11
- import java.io.File
12
- import java.lang.ref.WeakReference
13
- import kotlinx.coroutines.Dispatchers
14
- import kotlinx.coroutines.delay
15
- import kotlinx.coroutines.withContext
16
- import okhttp3.OkHttpClient
17
-
18
- /** A failure with a code from the module's contract (types/g9-app-diagnostic-module.d.ts). */
19
- class G9DiagnosticException(val code: String, message: String, cause: Throwable? = null) : Exception(message, cause)
20
-
21
- /**
22
- * What the package needs from the app that hosts it, and the few hooks a host may set — before the first call, typically in
23
- * `Application.onCreate`. Nothing here names a product: every default is neutral.
24
- *
25
- * - [httpClient]: the client a range request goes out on. The host's own, so its trust (a development certificate) and its
26
- * proxy rules are the ones every other request has. Default: a plain client.
27
- * - [allowedRoots]: the folders a recording, a screenshot or a sent file may be in. Default: the app's files and cache.
28
- * - [isExcludedView]: a surface the gesture leaves native in the «except the map» mode (the host's map view). Default: none.
29
- *
30
- * The current activity is tracked here (the recorders draw it, the gesture watches its window); the module's events go to
31
- * every live Lynx context.
32
- */
33
- object G9AppDiagnosticHost {
34
- @Volatile var httpClient: () -> OkHttpClient = { defaultClient }
35
-
36
- @Volatile var allowedRoots: (Context) -> List<File> = { listOf(it.filesDir, it.cacheDir) }
37
-
38
- @Volatile var isExcludedView: (View) -> Boolean = { false }
39
-
40
- private val defaultClient by lazy { OkHttpClient() }
41
-
42
- @Volatile private var application: Application? = null
43
- @Volatile private var current: WeakReference<Activity>? = null
44
- private val contexts = ArrayList<WeakReference<LynxContext>>()
45
-
46
- /** Called by every module instance: the application, its activity and its Lynx context. Idempotent. */
47
- internal fun attach(lynx: LynxContext) {
48
- synchronized(contexts) {
49
- contexts.removeAll { it.get() == null || it.get() === lynx }
50
- contexts += WeakReference(lynx)
51
- }
52
- activityOf(lynx)?.let { if (!it.isFinishing) current = WeakReference(it) }
53
- if (application != null) return
54
- val app = lynx.applicationContext as? Application ?: return
55
- synchronized(this) {
56
- if (application != null) return
57
- application = app
58
- app.registerActivityLifecycleCallbacks(
59
- object : Application.ActivityLifecycleCallbacks {
60
- override fun onActivityResumed(activity: Activity) {
61
- current = WeakReference(activity)
62
- TouchWatcher.attach(activity)
63
- }
64
-
65
- override fun onActivityDestroyed(activity: Activity) {
66
- if (current?.get() === activity) current = null
67
- }
68
-
69
- override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
70
-
71
- override fun onActivityStarted(activity: Activity) {}
72
-
73
- override fun onActivityPaused(activity: Activity) {}
74
-
75
- override fun onActivityStopped(activity: Activity) {}
76
-
77
- override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
78
- },
79
- )
80
- }
81
- }
82
-
83
- internal val app: Application
84
- get() = application ?: throw G9DiagnosticException("unavailable", "The module is not attached to an application")
85
-
86
- internal fun activityNow(): Activity? = current?.get()?.takeIf { !it.isFinishing && !it.isDestroyed }
87
-
88
- /** The activity on screen, waiting a few seconds for one (an app coming back to the foreground). */
89
- internal suspend fun awaitActivity(): Activity {
90
- repeat(50) {
91
- activityNow()?.let { return it }
92
- delay(100)
93
- }
94
- throw G9DiagnosticException("unavailable", "No activity on screen")
95
- }
96
-
97
- /** A folder or file the caller named, if it is inside the folders the host allows. */
98
- internal fun inside(path: String): File {
99
- val file = File(path).canonicalFile
100
- val roots = allowedRoots(app).map { it.canonicalPath.trimEnd('/') }
101
- if (roots.none { file.path.startsWith("$it/") }) throw G9DiagnosticException("invalid", "Outside the app folders: $path")
102
- return file
103
- }
104
-
105
- /** A global event to every live Lynx context (JSON text, the one argument). */
106
- internal fun emit(name: String, json: String) {
107
- val targets = synchronized(contexts) { contexts.mapNotNull { it.get() } }
108
- for (lynx in targets) {
109
- try {
110
- lynx.sendGlobalEvent(name, JavaOnlyArray().apply { pushString(json) })
111
- } catch (_: Throwable) {
112
- // A context being torn down: the next one still gets it.
113
- }
114
- }
115
- }
116
-
117
- internal suspend fun <T> onMain(work: () -> T): T = withContext(Dispatchers.Main) { work() }
118
-
119
- private fun activityOf(context: Context?): Activity? {
120
- var c = context
121
- repeat(10) {
122
- when (c) {
123
- is Activity -> return c as Activity
124
- is LynxContext -> c = (c as LynxContext).baseContext
125
- is ContextWrapper -> c = (c as ContextWrapper).baseContext
126
- else -> return null
127
- }
128
- }
129
- return null
130
- }
131
- }
1
+ package com.g9tm.appdiagnostic
2
+
3
+ import android.app.Activity
4
+ import android.app.Application
5
+ import android.content.Context
6
+ import android.content.ContextWrapper
7
+ import android.os.Bundle
8
+ import android.view.View
9
+ import com.lynx.react.bridge.JavaOnlyArray
10
+ import com.lynx.tasm.behavior.LynxContext
11
+ import java.io.File
12
+ import java.lang.ref.WeakReference
13
+ import kotlinx.coroutines.Dispatchers
14
+ import kotlinx.coroutines.delay
15
+ import kotlinx.coroutines.withContext
16
+ import okhttp3.OkHttpClient
17
+
18
+ /** A failure with a code from the module's contract (types/g9-app-diagnostic-module.d.ts). */
19
+ class G9DiagnosticException(val code: String, message: String, cause: Throwable? = null) : Exception(message, cause)
20
+
21
+ /**
22
+ * What the package needs from the app that hosts it, and the few hooks a host may set — before the first call, typically in
23
+ * `Application.onCreate`. Nothing here names a product: every default is neutral.
24
+ *
25
+ * - [httpClient]: the client a range request goes out on. The host's own, so its trust (a development certificate) and its
26
+ * proxy rules are the ones every other request has. Default: a plain client.
27
+ * - [allowedRoots]: the folders a recording, a screenshot or a sent file may be in. Default: the app's files and cache.
28
+ * - [isExcludedView]: a surface the gesture leaves native in the «except the map» mode (the host's map view). Default: none.
29
+ *
30
+ * The current activity is tracked here (the recorders draw it, the gesture watches its window); the module's events go to
31
+ * every live Lynx context.
32
+ */
33
+ object G9AppDiagnosticHost {
34
+ @Volatile var httpClient: () -> OkHttpClient = { defaultClient }
35
+
36
+ @Volatile var allowedRoots: (Context) -> List<File> = { listOf(it.filesDir, it.cacheDir) }
37
+
38
+ @Volatile var isExcludedView: (View) -> Boolean = { false }
39
+
40
+ private val defaultClient by lazy { OkHttpClient() }
41
+
42
+ @Volatile private var application: Application? = null
43
+ @Volatile private var current: WeakReference<Activity>? = null
44
+ private val contexts = ArrayList<WeakReference<LynxContext>>()
45
+
46
+ /** Called by every module instance: the application, its activity and its Lynx context. Idempotent. */
47
+ internal fun attach(lynx: LynxContext) {
48
+ synchronized(contexts) {
49
+ contexts.removeAll { it.get() == null || it.get() === lynx }
50
+ contexts += WeakReference(lynx)
51
+ }
52
+ activityOf(lynx)?.let { if (!it.isFinishing) current = WeakReference(it) }
53
+ if (application != null) return
54
+ val app = lynx.applicationContext as? Application ?: return
55
+ synchronized(this) {
56
+ if (application != null) return
57
+ application = app
58
+ app.registerActivityLifecycleCallbacks(
59
+ object : Application.ActivityLifecycleCallbacks {
60
+ override fun onActivityResumed(activity: Activity) {
61
+ current = WeakReference(activity)
62
+ TouchWatcher.attach(activity)
63
+ }
64
+
65
+ override fun onActivityDestroyed(activity: Activity) {
66
+ if (current?.get() === activity) current = null
67
+ }
68
+
69
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
70
+
71
+ override fun onActivityStarted(activity: Activity) {}
72
+
73
+ override fun onActivityPaused(activity: Activity) {}
74
+
75
+ override fun onActivityStopped(activity: Activity) {}
76
+
77
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
78
+ },
79
+ )
80
+ }
81
+ }
82
+
83
+ internal val app: Application
84
+ get() = application ?: throw G9DiagnosticException("unavailable", "The module is not attached to an application")
85
+
86
+ internal fun activityNow(): Activity? = current?.get()?.takeIf { !it.isFinishing && !it.isDestroyed }
87
+
88
+ /** The activity on screen, waiting a few seconds for one (an app coming back to the foreground). */
89
+ internal suspend fun awaitActivity(): Activity {
90
+ repeat(50) {
91
+ activityNow()?.let { return it }
92
+ delay(100)
93
+ }
94
+ throw G9DiagnosticException("unavailable", "No activity on screen")
95
+ }
96
+
97
+ /** A folder or file the caller named, if it is inside the folders the host allows. */
98
+ internal fun inside(path: String): File {
99
+ val file = File(path).canonicalFile
100
+ val roots = allowedRoots(app).map { it.canonicalPath.trimEnd('/') }
101
+ if (roots.none { file.path.startsWith("$it/") }) throw G9DiagnosticException("invalid", "Outside the app folders: $path")
102
+ return file
103
+ }
104
+
105
+ /** A global event to every live Lynx context (JSON text, the one argument). */
106
+ internal fun emit(name: String, json: String) {
107
+ val targets = synchronized(contexts) { contexts.mapNotNull { it.get() } }
108
+ for (lynx in targets) {
109
+ try {
110
+ lynx.sendGlobalEvent(name, JavaOnlyArray().apply { pushString(json) })
111
+ } catch (_: Throwable) {
112
+ // A context being torn down: the next one still gets it.
113
+ }
114
+ }
115
+ }
116
+
117
+ internal suspend fun <T> onMain(work: () -> T): T = withContext(Dispatchers.Main) { work() }
118
+
119
+ private fun activityOf(context: Context?): Activity? {
120
+ var c = context
121
+ repeat(10) {
122
+ when (c) {
123
+ is Activity -> return c as Activity
124
+ is LynxContext -> c = (c as LynxContext).baseContext
125
+ is ContextWrapper -> c = (c as ContextWrapper).baseContext
126
+ else -> return null
127
+ }
128
+ }
129
+ return null
130
+ }
131
+ }
@@ -1,67 +1,67 @@
1
- package com.g9tm.appdiagnostic
2
-
3
- import android.os.SystemClock
4
- import android.view.InputDevice
5
- import android.view.MotionEvent
6
- import android.view.View
7
- import kotlinx.coroutines.Dispatchers
8
- import kotlinx.coroutines.delay
9
- import kotlinx.coroutines.withContext
10
-
11
- /**
12
- * The operator's remote control as REAL touches (E-13): `MotionEvent`s with a finger's tool type and the touchscreen
13
- * source, dispatched into the window's decor view — the input system's own entry point — with real time between DOWN,
14
- * MOVEs and UP. Whatever is on top (a sheet, the map's own touch handling, a native view) gets it as it gets a finger, in
15
- * every build; a logical tap (finding a JS handler by position) misses native views and gestures. The decor view hands the
16
- * events to the window's callback first, so the tester gesture's watcher sees them too.
17
- *
18
- * Points are dp from the window's top-left. A separate window on top (a system permission dialog) is not in this tree and
19
- * is not reached. The caller (the live channel) admits a remote command only with the user's consent.
20
- */
21
- internal object RemoteTouch {
22
- private const val FRAME_MS = 16L
23
-
24
- suspend fun perform(kind: String, xDp: Double, yDp: Double, toXDp: Double, toYDp: Double, durationMs: Long): Boolean {
25
- if (kind !in setOf("tap", "longPress", "drag")) throw G9DiagnosticException("invalid", "touch: kind is tap, longPress or drag (got '$kind')")
26
- val activity = G9AppDiagnosticHost.awaitActivity()
27
- return withContext(Dispatchers.Main) {
28
- val root = activity.window.decorView
29
- val density = activity.resources.displayMetrics.density
30
- val x = (xDp * density).toFloat()
31
- val y = (yDp * density).toFloat()
32
- if (x < 0 || y < 0 || x >= root.width || y >= root.height) throw G9DiagnosticException("invalid", "touch: ($xDp, $yDp) dp is outside the window")
33
- val hold = durationMs.coerceIn(1L, 10_000L)
34
- val downTime = SystemClock.uptimeMillis()
35
- val handled = dispatch(root, downTime, MotionEvent.ACTION_DOWN, x, y)
36
- var upX = x
37
- var upY = y
38
- if (kind == "drag") {
39
- val tx = (toXDp * density).toFloat()
40
- val ty = (toYDp * density).toFloat()
41
- val steps = (hold / FRAME_MS).coerceAtLeast(1)
42
- for (i in 1..steps) {
43
- delay(FRAME_MS)
44
- val f = i.toFloat() / steps
45
- dispatch(root, downTime, MotionEvent.ACTION_MOVE, x + (tx - x) * f, y + (ty - y) * f)
46
- }
47
- upX = tx
48
- upY = ty
49
- } else {
50
- delay(hold)
51
- }
52
- dispatch(root, downTime, MotionEvent.ACTION_UP, upX, upY)
53
- handled
54
- }
55
- }
56
-
57
- private fun dispatch(root: View, downTime: Long, action: Int, x: Float, y: Float): Boolean {
58
- val props = arrayOf(MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_FINGER })
59
- val coords = arrayOf(MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f; size = 1f })
60
- val event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action, 1, props, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
61
- return try {
62
- root.dispatchTouchEvent(event)
63
- } finally {
64
- event.recycle()
65
- }
66
- }
67
- }
1
+ package com.g9tm.appdiagnostic
2
+
3
+ import android.os.SystemClock
4
+ import android.view.InputDevice
5
+ import android.view.MotionEvent
6
+ import android.view.View
7
+ import kotlinx.coroutines.Dispatchers
8
+ import kotlinx.coroutines.delay
9
+ import kotlinx.coroutines.withContext
10
+
11
+ /**
12
+ * The operator's remote control as REAL touches (E-13): `MotionEvent`s with a finger's tool type and the touchscreen
13
+ * source, dispatched into the window's decor view — the input system's own entry point — with real time between DOWN,
14
+ * MOVEs and UP. Whatever is on top (a sheet, the map's own touch handling, a native view) gets it as it gets a finger, in
15
+ * every build; a logical tap (finding a JS handler by position) misses native views and gestures. The decor view hands the
16
+ * events to the window's callback first, so the tester gesture's watcher sees them too.
17
+ *
18
+ * Points are dp from the window's top-left. A separate window on top (a system permission dialog) is not in this tree and
19
+ * is not reached. The caller (the live channel) admits a remote command only with the user's consent.
20
+ */
21
+ internal object RemoteTouch {
22
+ private const val FRAME_MS = 16L
23
+
24
+ suspend fun perform(kind: String, xDp: Double, yDp: Double, toXDp: Double, toYDp: Double, durationMs: Long): Boolean {
25
+ if (kind !in setOf("tap", "longPress", "drag")) throw G9DiagnosticException("invalid", "touch: kind is tap, longPress or drag (got '$kind')")
26
+ val activity = G9AppDiagnosticHost.awaitActivity()
27
+ return withContext(Dispatchers.Main) {
28
+ val root = activity.window.decorView
29
+ val density = activity.resources.displayMetrics.density
30
+ val x = (xDp * density).toFloat()
31
+ val y = (yDp * density).toFloat()
32
+ if (x < 0 || y < 0 || x >= root.width || y >= root.height) throw G9DiagnosticException("invalid", "touch: ($xDp, $yDp) dp is outside the window")
33
+ val hold = durationMs.coerceIn(1L, 10_000L)
34
+ val downTime = SystemClock.uptimeMillis()
35
+ val handled = dispatch(root, downTime, MotionEvent.ACTION_DOWN, x, y)
36
+ var upX = x
37
+ var upY = y
38
+ if (kind == "drag") {
39
+ val tx = (toXDp * density).toFloat()
40
+ val ty = (toYDp * density).toFloat()
41
+ val steps = (hold / FRAME_MS).coerceAtLeast(1)
42
+ for (i in 1..steps) {
43
+ delay(FRAME_MS)
44
+ val f = i.toFloat() / steps
45
+ dispatch(root, downTime, MotionEvent.ACTION_MOVE, x + (tx - x) * f, y + (ty - y) * f)
46
+ }
47
+ upX = tx
48
+ upY = ty
49
+ } else {
50
+ delay(hold)
51
+ }
52
+ dispatch(root, downTime, MotionEvent.ACTION_UP, upX, upY)
53
+ handled
54
+ }
55
+ }
56
+
57
+ private fun dispatch(root: View, downTime: Long, action: Int, x: Float, y: Float): Boolean {
58
+ val props = arrayOf(MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_FINGER })
59
+ val coords = arrayOf(MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f; size = 1f })
60
+ val event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action, 1, props, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
61
+ return try {
62
+ root.dispatchTouchEvent(event)
63
+ } finally {
64
+ event.recycle()
65
+ }
66
+ }
67
+ }