@blotch/angular-lynx-native 22.2.20 → 22.2.22

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 (70) hide show
  1. package/README.md +8 -4
  2. package/dist/android/build.d.ts +6 -1
  3. package/dist/android/build.d.ts.map +1 -1
  4. package/dist/android/build.js +14 -3
  5. package/dist/android/icon.d.ts +29 -0
  6. package/dist/android/icon.d.ts.map +1 -0
  7. package/dist/android/icon.js +142 -0
  8. package/dist/android/project.d.ts +2 -1
  9. package/dist/android/project.d.ts.map +1 -1
  10. package/dist/android/project.js +5 -2
  11. package/dist/android/run.d.ts +10 -1
  12. package/dist/android/run.d.ts.map +1 -1
  13. package/dist/android/run.js +46 -1
  14. package/dist/dev-build.d.ts +16 -0
  15. package/dist/dev-build.d.ts.map +1 -0
  16. package/dist/dev-build.js +44 -0
  17. package/dist/generate.d.ts +26 -7
  18. package/dist/generate.d.ts.map +1 -1
  19. package/dist/generate.js +25 -10
  20. package/dist/index.d.ts +13 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +77 -13
  23. package/dist/ios/build.d.ts +68 -12
  24. package/dist/ios/build.d.ts.map +1 -1
  25. package/dist/ios/build.js +210 -45
  26. package/dist/ios/iphone.d.ts +99 -0
  27. package/dist/ios/iphone.d.ts.map +1 -0
  28. package/dist/ios/iphone.js +207 -0
  29. package/dist/ios/project.d.ts +10 -1
  30. package/dist/ios/project.d.ts.map +1 -1
  31. package/dist/ios/project.js +27 -4
  32. package/dist/ios/run.d.ts +18 -3
  33. package/dist/ios/run.d.ts.map +1 -1
  34. package/dist/ios/run.js +34 -5
  35. package/dist/options.d.ts +49 -3
  36. package/dist/options.d.ts.map +1 -1
  37. package/dist/options.js +33 -1
  38. package/dist/permissions.d.ts.map +1 -1
  39. package/dist/permissions.js +6 -0
  40. package/dist/png.d.ts +38 -0
  41. package/dist/png.d.ts.map +1 -1
  42. package/dist/png.js +167 -0
  43. package/dist/run.d.ts +54 -6
  44. package/dist/run.d.ts.map +1 -1
  45. package/dist/run.js +16 -1
  46. package/package.json +5 -1
  47. package/templates/android/README.md +5 -1
  48. package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServer.kt +159 -0
  49. package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServerModules.kt +163 -0
  50. package/templates/android/app/src/debug/res/xml/network_security_config.xml +13 -0
  51. package/templates/android/app/src/main/AndroidManifest.xml +16 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/AssetsModule.kt +22 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +24 -1
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/ResourceFetchers.kt +12 -6
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareModule.kt +274 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +57 -0
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +95 -0
  58. package/templates/android/app/src/main/res/mipmap/ic_launcher_round.xml +6 -0
  59. package/templates/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +6 -0
  60. package/templates/android/app/src/main/res/xml/share_paths.xml +8 -0
  61. package/templates/android/app/src/release/java/dev/angularlynx/shell/DevServer.kt +24 -0
  62. package/templates/ios/App/AngularLynxWebGL.h +7 -0
  63. package/templates/ios/App/AngularLynxWebGL.m +27 -0
  64. package/templates/ios/App/AngularLynxWebGLContext.m +139 -0
  65. package/templates/ios/App/AssetsModule.swift +21 -3
  66. package/templates/ios/App/BundleResourceFetcher.swift +46 -2
  67. package/templates/ios/App/DevServer.swift +190 -0
  68. package/templates/ios/App/DevServerModules.swift +223 -0
  69. package/templates/ios/App/LynxViewController.swift +11 -1
  70. package/templates/ios/App/ShareModule.swift +215 -0
package/dist/run.d.ts CHANGED
@@ -2,20 +2,68 @@ import type { ResolvedApp } from './options.ts';
2
2
  /** `ng build --platform <platform> --run`'s options. */
3
3
  export type RunOptions = {
4
4
  /**
5
- * Where to open the app. On iOS, a simulator's name or UDID; on Android, a
6
- * virtual device's name or an adb serial. When it's left out, a running
7
- * simulator, emulator or phone, or else the newest iPhone simulator or the
8
- * first virtual device.
5
+ * Where to open the app. On iOS, a simulator's or a paired iPhone's name or
6
+ * UDID; on Android, a virtual device's name or an adb serial. When it's
7
+ * left out, a running simulator, emulator or Android phone, or else the
8
+ * newest iPhone simulator or the first virtual device.
9
9
  */
10
10
  readonly device?: string;
11
11
  };
12
+ /**
13
+ * `ng serve --platform <platform>`'s dev server, which the development app
14
+ * loads its bundle from instead of the copy inside it.
15
+ */
16
+ export type DevServerOptions = {
17
+ /**
18
+ * The Lynx bundle's URL on the dev server, as the bundle itself names the
19
+ * server: rspeedy builds it with this host in its asset URLs and its live
20
+ * reload socket (`dev.assetPrefix`), and the QR code for Lynx Explorer
21
+ * carries it. Usually the Mac's address on the local network, so a phone
22
+ * on the same Wi-Fi reaches it.
23
+ */
24
+ readonly bundleUrl: string;
25
+ };
12
26
  /**
13
27
  * A simulator, emulator or phone picked for `--run`. Picking it and starting
14
28
  * it come before the native build, so a device that doesn't exist fails in
15
29
  * seconds, and a simulator or emulator boots while Xcode or Gradle compiles.
16
30
  */
17
31
  export type RunTarget = {
18
- /** Waits for the device to finish starting, then installs and opens the app. */
19
- readonly launch: (binary: string, app: ResolvedApp) => Promise<void>;
32
+ /**
33
+ * The real iPhone the app runs on, which takes a development-signed build
34
+ * for the device rather than the simulator app.
35
+ */
36
+ readonly iPhone?: {
37
+ readonly udid: string;
38
+ readonly name: string;
39
+ };
40
+ /**
41
+ * The simulator the app runs on, which a development build is compiled for
42
+ * alone, rather than for every simulator.
43
+ */
44
+ readonly simulator?: {
45
+ readonly udid: string;
46
+ };
47
+ /**
48
+ * Waits for the device to finish starting, then installs and opens the
49
+ * app. With `devServer`, the app is told to load its bundle from there.
50
+ */
51
+ readonly launch: (binary: string, app: ResolvedApp, devServer?: DevServerOptions) => Promise<void>;
20
52
  };
53
+ /**
54
+ * The launch argument (iOS) and intent extra (Android) that hand the
55
+ * development app its dev server, and the one that names the host the bundle
56
+ * was built with, when the app reaches the server under another (Android's
57
+ * `localhost`, through `adb reverse`). The shells' DevServer reads them.
58
+ */
59
+ export declare const DEV_SERVER_ARGUMENT = "AngularLynxDevServer";
60
+ export declare const DEV_SERVER_ORIGIN_ARGUMENT = "AngularLynxDevServerOrigin";
61
+ /**
62
+ * The launch arguments that point the development app at the dev server.
63
+ * iOS puts `-Name value` arguments in the app's UserDefaults (its argument
64
+ * domain), where DevServer.swift reads them. A simulator shares the Mac's
65
+ * network, and an iPhone on the same Wi-Fi reaches the Mac's address, so
66
+ * both load the bundle from the URL it was built with.
67
+ */
68
+ export declare const iosDevServerArguments: (devServer: DevServerOptions | undefined) => string[];
21
69
  //# sourceMappingURL=run.d.ts.map
package/dist/run.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,wDAAwD;AACxD,MAAM,MAAM,UAAU,GAAG;IACvB;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,gFAAgF;IAChF,QAAQ,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACtE,CAAC"}
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,wDAAwD;AACxD,MAAM,MAAM,UAAU,GAAG;IACvB;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B;;;;;;OAMG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACnE;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC/C;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,CACf,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,WAAW,EAChB,SAAS,CAAC,EAAE,gBAAgB,KACzB,OAAO,CAAC,IAAI,CAAC,CAAC;CACpB,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,yBAAyB,CAAC;AAC1D,eAAO,MAAM,0BAA0B,+BAA+B,CAAC;AAEvE;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,GAChC,WAAW,gBAAgB,GAAG,SAAS,KACtC,MAAM,EAC0D,CAAC"}
package/dist/run.js CHANGED
@@ -1 +1,16 @@
1
- export {};
1
+ /**
2
+ * The launch argument (iOS) and intent extra (Android) that hand the
3
+ * development app its dev server, and the one that names the host the bundle
4
+ * was built with, when the app reaches the server under another (Android's
5
+ * `localhost`, through `adb reverse`). The shells' DevServer reads them.
6
+ */
7
+ export const DEV_SERVER_ARGUMENT = 'AngularLynxDevServer';
8
+ export const DEV_SERVER_ORIGIN_ARGUMENT = 'AngularLynxDevServerOrigin';
9
+ /**
10
+ * The launch arguments that point the development app at the dev server.
11
+ * iOS puts `-Name value` arguments in the app's UserDefaults (its argument
12
+ * domain), where DevServer.swift reads them. A simulator shares the Mac's
13
+ * network, and an iPhone on the same Wi-Fi reaches the Mac's address, so
14
+ * both load the bundle from the URL it was built with.
15
+ */
16
+ export const iosDevServerArguments = (devServer) => devServer ? [`-${DEV_SERVER_ARGUMENT}`, devServer.bundleUrl] : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotch/angular-lynx-native",
3
- "version": "22.2.20",
3
+ "version": "22.2.22",
4
4
  "description": "Builds AngularLynx apps into iOS and Android binaries",
5
5
  "homepage": "https://github.com/Blotch-Smart-Frames/AngularLynx#readme",
6
6
  "bugs": {
@@ -43,9 +43,13 @@
43
43
  "build:angle-ios-frameworks": "scripts/build-angle-ios-frameworks.sh",
44
44
  "publish:local": "yalc publish --push"
45
45
  },
46
+ "dependencies": {
47
+ "pngjs": "^7.0.0"
48
+ },
46
49
  "devDependencies": {
47
50
  "@bacons/xcode": "1.0.0-alpha.33",
48
51
  "@types/node": "^22.0.0",
52
+ "@types/pngjs": "^6.0.5",
49
53
  "typescript": "~6.0.0"
50
54
  },
51
55
  "engines": {
@@ -67,9 +67,13 @@ iOS's `LocalStorageModule.swift` uses a `UserDefaults` suite and `SecureStorageM
67
67
 
68
68
  The module reads the picked photo on a background thread and calls back once with `{ base64, name, type }`, `{ canceled: true }` or `{ error, message }`. A JPEG, PNG, GIF or WebP goes back as it is unless the app passed `maxDimension` or `quality`; otherwise it's decoded with `BitmapFactory` at the smallest power-of-two reduction that covers the target, scaled, turned upright by its EXIF orientation (AndroidX `ExifInterface`, since `BitmapFactory` ignores it), drawn over white if it has transparency and compressed as a JPEG. iOS's `ImagePickerModule.swift` does the same with `PHPickerViewController` and ImageIO.
69
69
 
70
+ ## Share sheet
71
+
72
+ `NativeModules.AngularLynxShare.share(request, callback)` (`ShareModule.kt`, behind the runtime's `LynxShare`) writes the request's files (base64) under the cache's `angular-lynx-share/` folder, on a background thread, and opens an `ACTION_SEND` or `ACTION_SEND_MULTIPLE` chooser with their content:// URIs. They come from the manifest's `androidx.core.content.FileProvider` (authority `<applicationId>.angularlynx.share`, paths in `res/xml/share_paths.xml`), and the intent's `ClipData` and `FLAG_GRANT_READ_URI_PERMISSION` let the app picked read them. `MainActivity` registers it with itself as the param, since the module starts the chooser from it and watches its lifecycle. Android doesn't say whether sharing finished, so the module calls back `{ shared: true }` when the chooser's `IntentSender` reports the app picked, and `{ shared: false }` when the activity resumes without a pick. The last share's files stay until the next one, since the app picked may read them after the chooser closes. iOS's `ShareModule.swift` opens `UIActivityViewController` with the files as temporary files of their names, and leaves out Save Image when Info.plist has no `NSPhotoLibraryAddUsageDescription`.
73
+
70
74
  ## Canvas and WebGL
71
75
 
72
- `<canvas>` (issue #211) is the shell's: `CanvasUI.kt`, a `TextureView` registered as the `canvas` element (`addBehavior(CanvasUI.behavior())`), and `WebGLModule.kt`, the `AngularLynxWebGL` module the runtime's WebGL2 context sends its calls to. `MainActivity` turns on main-thread modules (`setEnableMTSModule(true)`), so the runtime, which runs on Lynx's main thread, calls the module synchronously with `lynx.module(name)`, on the UI thread. Each context (`WebGLContext.kt`) is an EGL context with OpenGL ES 3.0 and an offscreen default framebuffer, which `present` copies into the canvas's surface; `WebGLOps.kt` is generated from the runtime's opcodes (`npm run generate:webgl-ops -w packages/native`). `AssetsModule.kt` (`AngularLynxAssets`) reads a file the app bundles for the main thread's `fetch`, which has no page URL to resolve `/static/...` against.
76
+ `<canvas>` (issue #211) is the shell's: `CanvasUI.kt`, a `TextureView` registered as the `canvas` element (`addBehavior(CanvasUI.behavior())`), and `WebGLModule.kt`, the `AngularLynxWebGL` module the runtime's WebGL2 context sends its calls to. `MainActivity` turns on main-thread modules (`setEnableMTSModule(true)`), so the runtime, which runs on Lynx's main thread, calls the module synchronously with `lynx.module(name)`, on the UI thread. Each context (`WebGLContext.kt`) is an EGL context with OpenGL ES 3.0 and an offscreen default framebuffer, which `present` copies into the canvas's surface; `WebGLOps.kt` is generated from the runtime's opcodes (`npm run generate:webgl-ops -w packages/native`). `encodeImage`, behind `canvas.toBlob()` and `toDataURL()`, reads the default framebuffer and compresses it with `Bitmap.compress`, returning the file as base64. `AssetsModule.kt` (`AngularLynxAssets`) reads a file the app bundles for the main thread's `fetch`, which has no page URL to resolve `/static/...` against.
73
77
 
74
78
  Android's GLES has no 2D uploads from a `PIXEL_UNPACK_BUFFER` and no `glGetVertexAttribPointerv`, so those log a warning and answer 0.
75
79
 
@@ -0,0 +1,159 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.net.Uri
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import android.util.TypedValue
9
+ import android.view.Gravity
10
+ import android.view.View
11
+ import android.widget.FrameLayout
12
+ import android.widget.TextView
13
+ import com.lynx.tasm.LynxViewBuilder
14
+
15
+ /**
16
+ * `ng serve --platform android`: the development app loads its bundle from
17
+ * the dev server rather than from its assets (where it has none), and
18
+ * reloads it on every edit, as Lynx Explorer does.
19
+ *
20
+ * This is the debug build type's copy, the one `ng serve --platform android`
21
+ * builds; the release build's (src/release) does nothing.
22
+ *
23
+ * The builder opens the activity with two extras: `AngularLynxDevServer`, the
24
+ * bundle at `http://localhost:<port>/`, which `adb reverse` forwards to the
25
+ * computer whatever network the device is on, and
26
+ * `AngularLynxDevServerOrigin`, the address the bundle was built with (the
27
+ * computer's on the local network), whose URLs are sent to localhost too.
28
+ * They're kept, so opening the app from the launcher later loads from the
29
+ * same server.
30
+ */
31
+ object DevServer {
32
+ private const val EXTRA_URL = "AngularLynxDevServer"
33
+ private const val EXTRA_ORIGIN = "AngularLynxDevServerOrigin"
34
+ private const val PREFERENCES = "angular-lynx-dev-server"
35
+
36
+ private val main = Handler(Looper.getMainLooper())
37
+
38
+ /** The bundle on the dev server, e.g. `http://localhost:3000/main.lynx.bundle`. */
39
+ private var bundle: String? = null
40
+
41
+ /** The folder it's in, which every relative URL the bundle asks for resolves against. */
42
+ private var base: Uri? = null
43
+
44
+ /** The address the bundle was built with, e.g. `http://192.168.1.20:3000`. */
45
+ private var origin: Uri? = null
46
+
47
+ private var reload: (() -> Unit)? = null
48
+ private var status: TextView? = null
49
+ private val retry = Runnable { reload?.invoke() }
50
+
51
+ /** The URL MainActivity renders, or null when it was never given one. */
52
+ fun bundleUrl(activity: Activity): String? {
53
+ val preferences = activity.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
54
+ val launched = activity.intent?.getStringExtra(EXTRA_URL)
55
+ if (launched != null) {
56
+ preferences.edit()
57
+ .putString(EXTRA_URL, launched)
58
+ .putString(EXTRA_ORIGIN, activity.intent.getStringExtra(EXTRA_ORIGIN))
59
+ .apply()
60
+ }
61
+ bundle = preferences.getString(EXTRA_URL, null)
62
+ base = bundle?.let { Uri.parse(it.substring(0, it.lastIndexOf('/') + 1)) }
63
+ origin = preferences.getString(EXTRA_ORIGIN, null)?.let(Uri::parse)
64
+ return bundle
65
+ }
66
+
67
+ /**
68
+ * Adds the dev server's modules: the WebSocket rspeedy's live reload
69
+ * listens on, and the reload it asks for (DevServerModules.kt).
70
+ */
71
+ fun register(builder: LynxViewBuilder, reload: () -> Unit) {
72
+ if (bundle == null) return
73
+ this.reload = reload
74
+ builder.registerModule(DevWebSocketModule.NAME, DevWebSocketModule::class.java, null)
75
+ builder.registerModule(DevReloadModule.NAME, DevReloadModule::class.java, null)
76
+ }
77
+
78
+ /** Adds the dev server's status, hidden, over the page. */
79
+ fun attach(container: FrameLayout) {
80
+ val context = container.context
81
+ val view = TextView(context).apply {
82
+ gravity = Gravity.CENTER
83
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
84
+ val padding = (24 * resources.displayMetrics.density).toInt()
85
+ setPadding(padding, padding, padding, padding)
86
+ setBackgroundColor(context.getColor(R.color.window_background))
87
+ visibility = View.GONE
88
+ }
89
+ container.addView(view, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
90
+ status = view
91
+ if (bundle == null) {
92
+ show(
93
+ "This is the development build of the app, which loads the app from `ng serve`.\n\n" +
94
+ "Run `ng serve --platform android` to open it.",
95
+ )
96
+ }
97
+ }
98
+
99
+ /** Reloads the bundle from the dev server, from any thread. */
100
+ fun reloadBundle() {
101
+ main.post { reload?.invoke() }
102
+ }
103
+
104
+ /**
105
+ * Where a URL the bundle asks for is on the dev server, or null when the
106
+ * app isn't loading from one, or the URL is somewhere else (an API, a
107
+ * CDN, a data: or content: URL).
108
+ */
109
+ fun remoteUrl(url: String): String? {
110
+ val base = base ?: return null
111
+ val uri = Uri.parse(url)
112
+ val scheme = uri.scheme
113
+ if (scheme == "http" || scheme == "https" || scheme == "ws" || scheme == "wss") {
114
+ // The address the bundle was built with: the same server, which
115
+ // this device reaches at localhost.
116
+ if (origin?.encodedAuthority == uri.encodedAuthority) {
117
+ return uri.buildUpon().encodedAuthority(base.encodedAuthority).build().toString()
118
+ }
119
+ return if (uri.encodedAuthority == base.encodedAuthority) url else null
120
+ }
121
+ val path = when {
122
+ url.startsWith("asset:///") -> url.removePrefix("asset:///")
123
+ scheme == null -> url.removePrefix("./").trimStart('/')
124
+ else -> return null
125
+ }
126
+ return base.toString() + path
127
+ }
128
+
129
+ /**
130
+ * Called with the outcome of each load. When the bundle itself didn't
131
+ * load (the server is stopped, or `adb reverse` is gone after the device
132
+ * reconnected), the app says so rather than show nothing, and tries again
133
+ * every two seconds.
134
+ */
135
+ fun loaded(url: String, error: Throwable?) {
136
+ val bundle = bundle ?: return
137
+ if (url != bundle) return
138
+ main.post {
139
+ main.removeCallbacks(retry)
140
+ if (error == null) {
141
+ status?.visibility = View.GONE
142
+ return@post
143
+ }
144
+ show(
145
+ "Can't reach the dev server at ${base?.encodedAuthority}.\n\n${error.message}\n\n" +
146
+ "Is `ng serve --platform android` running? It forwards the port to this device again " +
147
+ "when it starts. Trying again…",
148
+ )
149
+ main.postDelayed(retry, 2000)
150
+ }
151
+ }
152
+
153
+ private fun show(message: String) {
154
+ val status = status ?: return
155
+ status.text = message
156
+ status.visibility = View.VISIBLE
157
+ status.bringToFront()
158
+ }
159
+ }
@@ -0,0 +1,163 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import com.lynx.jsbridge.LynxContextModule
4
+ import com.lynx.jsbridge.LynxMethod
5
+ import com.lynx.jsbridge.LynxModule
6
+ import com.lynx.react.bridge.Callback
7
+ import com.lynx.react.bridge.JavaOnlyArray
8
+ import com.lynx.react.bridge.JavaOnlyMap
9
+ import com.lynx.react.bridge.ReadableArray
10
+ import com.lynx.react.bridge.ReadableMap
11
+ import com.lynx.tasm.behavior.LynxContext
12
+ import okhttp3.OkHttpClient
13
+ import okhttp3.Request
14
+ import okhttp3.Response
15
+ import okhttp3.WebSocket
16
+ import okhttp3.WebSocketListener
17
+ import okio.ByteString
18
+ import org.json.JSONObject
19
+ import java.util.concurrent.ConcurrentHashMap
20
+ import java.util.concurrent.TimeUnit
21
+
22
+ /*
23
+ * The two native modules rspeedy's live reload needs, in the debug build
24
+ * only (see DevServer.kt). Lynx Explorer has them from Lynx DevTool, which
25
+ * the shell doesn't include: the dev server's client, which rspeedy puts in
26
+ * every development bundle, talks to the server over
27
+ * `NativeModules.LynxWebSocketModule` (through @lynx-js/websocket) and
28
+ * reloads the page with `NativeModules.LynxDevToolSetModule.invokeCdp`, a
29
+ * DevTool protocol `Page.reload`. These answer to the same names and calls,
30
+ * so the bundle runs here as it does in Lynx Explorer.
31
+ */
32
+
33
+ /**
34
+ * `NativeModules.LynxWebSocketModule`, as Lynx DevTool's
35
+ * (LynxWebSocket.java): `connect`, `send`, `ping` and `close`, each with the
36
+ * socket's ID, and the `websocketOpen`, `websocketMessage`, `websocketClosed`
37
+ * and `websocketFailed` global events @lynx-js/websocket listens for.
38
+ */
39
+ class DevWebSocketModule : LynxContextModule {
40
+ // Lynx creates a module through whichever of its constructors it finds.
41
+ constructor(context: LynxContext) : super(context)
42
+ constructor(context: LynxContext, param: Any?) : super(context, param)
43
+
44
+ private val sockets = ConcurrentHashMap<Int, WebSocket>()
45
+
46
+ // No read timeout: the dev server only writes when there's a new build.
47
+ private val client = OkHttpClient.Builder()
48
+ .connectTimeout(10, TimeUnit.SECONDS)
49
+ .readTimeout(0, TimeUnit.MILLISECONDS)
50
+ .build()
51
+
52
+ @LynxMethod
53
+ fun connect(url: String, protocols: ReadableArray?, options: ReadableMap?, socketID: Double) {
54
+ val id = socketID.toInt()
55
+ val request = Request.Builder()
56
+ // The address the bundle was built with reaches this device's
57
+ // localhost through adb reverse.
58
+ .url(DevServer.remoteUrl(url) ?: url)
59
+ .apply {
60
+ val names = (0 until (protocols?.size() ?: 0)).mapNotNull { protocols?.getString(it)?.trim() }
61
+ .filter { it.isNotEmpty() && !it.contains(',') }
62
+ if (names.isNotEmpty()) addHeader("Sec-WebSocket-Protocol", names.joinToString(","))
63
+ }
64
+ .build()
65
+ client.newWebSocket(request, object : WebSocketListener() {
66
+ override fun onOpen(webSocket: WebSocket, response: Response) {
67
+ sockets[id] = webSocket
68
+ emit("websocketOpen", "id" to id, "protocol" to (response.header("Sec-WebSocket-Protocol") ?: ""))
69
+ }
70
+
71
+ override fun onMessage(webSocket: WebSocket, text: String) =
72
+ emit("websocketMessage", "id" to id, "type" to "text", "data" to text)
73
+
74
+ override fun onMessage(webSocket: WebSocket, bytes: ByteString) =
75
+ emit("websocketMessage", "id" to id, "type" to "binary", "data" to bytes.base64())
76
+
77
+ override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
78
+ webSocket.close(code, reason)
79
+ }
80
+
81
+ override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
82
+ sockets.remove(id)
83
+ emit("websocketClosed", "id" to id, "code" to code, "reason" to reason)
84
+ }
85
+
86
+ // The connection failed or dropped (the server stopped): the dev
87
+ // server's client then tries again, with a growing delay.
88
+ override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
89
+ sockets.remove(id)
90
+ emit("websocketFailed", "id" to id, "message" to (t.message ?: t.toString()))
91
+ emit("websocketClosed", "id" to id, "code" to 1006, "reason" to (t.message ?: ""))
92
+ }
93
+ })
94
+ }
95
+
96
+ @LynxMethod
97
+ fun send(message: String, socketID: Double) {
98
+ sockets[socketID.toInt()]?.send(message)
99
+ }
100
+
101
+ @LynxMethod
102
+ fun ping(socketID: Double) {
103
+ sockets[socketID.toInt()]?.send(ByteString.EMPTY)
104
+ }
105
+
106
+ @LynxMethod
107
+ fun close(code: Double, reason: String, socketID: Double) {
108
+ sockets.remove(socketID.toInt())?.close(code.toInt(), reason)
109
+ }
110
+
111
+ override fun destroy() {
112
+ sockets.values.forEach { it.close(1001, "The page closed") }
113
+ sockets.clear()
114
+ super.destroy()
115
+ }
116
+
117
+ private fun emit(event: String, vararg params: Pair<String, Any>) {
118
+ val map = JavaOnlyMap()
119
+ for ((key, value) in params) {
120
+ when (value) {
121
+ is Int -> map.putInt(key, value)
122
+ else -> map.putString(key, value.toString())
123
+ }
124
+ }
125
+ mLynxContext.sendGlobalEvent(event, JavaOnlyArray().apply { pushMap(map) })
126
+ }
127
+
128
+ companion object {
129
+ const val NAME = "LynxWebSocketModule"
130
+ }
131
+ }
132
+
133
+ /**
134
+ * `NativeModules.LynxDevToolSetModule`, as far as rspeedy's live reload uses
135
+ * Lynx DevTool's: `invokeCdp` with a `Page.reload`, which renders the bundle
136
+ * from the dev server again, as Lynx DevTool's page reload does. It answers
137
+ * any other DevTool method with an error.
138
+ */
139
+ class DevReloadModule(context: android.content.Context, param: Any?) : LynxModule(context, param) {
140
+ @LynxMethod
141
+ fun invokeCdp(message: String, callback: Callback?) {
142
+ val request = runCatching { JSONObject(message) }.getOrDefault(JSONObject())
143
+ val id = request.opt("id") ?: 0
144
+ val method = request.optString("method")
145
+ val reply = JSONObject().put("id", id)
146
+ if (method == "Page.reload") {
147
+ DevServer.reloadBundle()
148
+ reply.put("result", JSONObject())
149
+ } else {
150
+ reply.put(
151
+ "error",
152
+ JSONObject()
153
+ .put("code", -32601)
154
+ .put("message", "$method needs Lynx DevTool, which this app doesn't have."),
155
+ )
156
+ }
157
+ callback?.invoke(reply.toString())
158
+ }
159
+
160
+ companion object {
161
+ const val NAME = "LynxDevToolSetModule"
162
+ }
163
+ }
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <!--
3
+ The debug build's network security config, in place of src/main's: plain
4
+ HTTP to any host. Only `ng serve` builds the debug build type (with the
5
+ platform option set to android). The dev
6
+ server is plain HTTP, and a development bundle names it by the computer's
7
+ address on the local network (rspeedy's dev.assetPrefix), which the app's
8
+ own fetch() of an imported file goes to directly. The release build keeps
9
+ src/main's, which allows plain HTTP to localhost alone.
10
+ -->
11
+ <network-security-config>
12
+ <base-config cleartextTrafficPermitted="true" />
13
+ </network-security-config>
@@ -22,6 +22,7 @@
22
22
  android:dataExtractionRules="@xml/data_extraction_rules"
23
23
  android:fullBackupContent="@xml/backup_rules"
24
24
  android:icon="@mipmap/ic_launcher"
25
+ android:roundIcon="@mipmap/ic_launcher_round"
25
26
  android:label="@string/app_name"
26
27
  android:networkSecurityConfig="@xml/network_security_config"
27
28
  android:supportsRtl="true"
@@ -47,6 +48,21 @@
47
48
  <!-- angular-lynx:deep-links -->
48
49
  </activity>
49
50
 
51
+ <!--
52
+ The files LynxShare shares (ShareModule), which the app picked in
53
+ the share sheet reads through content:// URIs of this provider.
54
+ It's not exported: each share grants the one app it goes to.
55
+ -->
56
+ <provider
57
+ android:name="androidx.core.content.FileProvider"
58
+ android:authorities="${applicationId}.angularlynx.share"
59
+ android:exported="false"
60
+ android:grantUriPermissions="true">
61
+ <meta-data
62
+ android:name="android.support.FILE_PROVIDER_PATHS"
63
+ android:resource="@xml/share_paths" />
64
+ </provider>
65
+
50
66
  <!--
51
67
  Lets Google Play services install the Photo Picker that
52
68
  LynxImagePicker opens (ImagePickerModule) on Android 10 and older,
@@ -4,8 +4,11 @@ import android.content.Context
4
4
  import com.lynx.jsbridge.LynxMethod
5
5
  import com.lynx.jsbridge.LynxModule
6
6
  import com.lynx.react.bridge.JavaOnlyArray
7
+ import com.lynx.tasm.core.LynxThreadPool
8
+ import okhttp3.Request
7
9
  import java.io.IOException
8
10
  import java.nio.ByteBuffer
11
+ import java.util.concurrent.FutureTask
9
12
 
10
13
  /**
11
14
  * The `AngularLynxAssets` module: a file the app bundles (`/static/...`),
@@ -26,6 +29,7 @@ class AssetsModule(context: Context, param: Any?) : LynxModule(context, param) {
26
29
  */
27
30
  @LynxMethod
28
31
  fun read(url: String): JavaOnlyArray? {
32
+ DevServer.remoteUrl(url)?.let { return readRemote(it) }
29
33
  val path = BundleAssets.assetPath(url) ?: return null
30
34
  return try {
31
35
  val bytes = BundleAssets.read(mContext, path)
@@ -35,6 +39,24 @@ class AssetsModule(context: Context, param: Any?) : LynxModule(context, param) {
35
39
  }
36
40
  }
37
41
 
42
+ /**
43
+ * The file on the dev server, in the debug build `ng serve --platform
44
+ * android` runs, which has the current copy. The call is synchronous, so
45
+ * the request is too, but on a thread of its own: Android doesn't allow
46
+ * network requests on the UI thread, where Lynx may call this.
47
+ */
48
+ private fun readRemote(url: String): JavaOnlyArray? = try {
49
+ val download = FutureTask {
50
+ http.newCall(Request.Builder().url(url).build()).execute().use { response ->
51
+ if (response.isSuccessful) response.body?.bytes() else null
52
+ }
53
+ }
54
+ LynxThreadPool.getBriefIOExecutor().execute(download)
55
+ download.get()?.let { wordsFromBytes(ByteBuffer.wrap(it), it.size) }
56
+ } catch (_: Exception) {
57
+ null
58
+ }
59
+
38
60
  companion object {
39
61
  const val NAME = "AngularLynxAssets"
40
62
  }
@@ -100,6 +100,9 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
100
100
  enableEdgeToEdge()
101
101
  super.onCreate(savedInstanceState)
102
102
 
103
+ // The bundle in the app's assets, or in the debug build `ng serve
104
+ // --platform android` runs, the dev server's (DevServer.kt).
105
+ val bundleUrl = DevServer.bundleUrl(this) ?: BundleAssets.MAIN_BUNDLE
103
106
  lynxView = LynxViewBuilder().apply {
104
107
  setTemplateProvider(AssetTemplateProvider(this@MainActivity))
105
108
  setTemplateResourceFetcher(AssetTemplateResourceFetcher(this@MainActivity))
@@ -118,6 +121,9 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
118
121
  // The photo picker behind LynxImagePicker (ImagePickerModule.kt), which
119
122
  // this activity launches.
120
123
  registerModule(ImagePickerModule.NAME, ImagePickerModule::class.java, imagePickerHost)
124
+ // The share sheet behind LynxShare (ShareModule.kt), which it opens
125
+ // from this activity.
126
+ registerModule(ShareModule.NAME, ShareModule::class.java, this@MainActivity)
121
127
  // <canvas>'s WebGL (WebGLModule.kt), which the runtime calls from
122
128
  // the main thread, where Angular runs: main-thread modules let
123
129
  // it get its answers synchronously, with lynx.module(name).
@@ -134,7 +140,23 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
134
140
  if (edgeToEdge) addBehavior(EdgeToEdgeOverlay.behavior())
135
141
  // The shell's own <canvas> (CanvasUI.kt): Lynx has none.
136
142
  addBehavior(CanvasUI.behavior())
143
+ // Live reload, in the debug build: it renders the bundle again
144
+ // after every edit.
145
+ DevServer.register(this) { lynxView.renderTemplateUrl(bundleUrl, "") }
137
146
  }.build(this)
147
+ // The LynxView is focusable, so it takes focus whenever the window
148
+ // isn't in touch mode: after any key press, from a hardware keyboard,
149
+ // a D-pad, the keyboard's Enter, or a key sent with adb.
150
+ // Android 14 keeps touch mode for the whole display, so an app opened
151
+ // afterwards starts out of it too. Android 8 and later then draw
152
+ // their default focus highlight over the focused view, here the whole
153
+ // page: a 12% black (`#1F000000`, a 12% white in dark mode), which
154
+ // made every color about 12% darker (issue #362). The page is the
155
+ // document, not a control, and a browser doesn't outline the document
156
+ // either; the elements in it draw their own focus.
157
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
158
+ lynxView.defaultFocusHighlightEnabled = false
159
+ }
138
160
  lynxView.addLynxViewClient(object : LynxViewClient() {
139
161
  override fun onReceivedError(error: LynxError?) {
140
162
  Log.e(TAG, "Lynx error: ${error?.msg}")
@@ -179,6 +201,7 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
179
201
  }
180
202
  WindowInsetsCompat.CONSUMED
181
203
  }
204
+ DevServer.attach(container)
182
205
  setContentView(container)
183
206
 
184
207
  contentResolver.registerContentObserver(
@@ -202,7 +225,7 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
202
225
  // Sent before the bundle loads, so the app starts with the theme and
203
226
  // the language. The insets follow once the window reports them.
204
227
  lynxView.updateGlobalProps(globalProps(resources.configuration))
205
- lynxView.renderTemplateUrl(BundleAssets.MAIN_BUNDLE, "")
228
+ lynxView.renderTemplateUrl(bundleUrl, "")
206
229
  }
207
230
 
208
231
  override fun setBackHandlerEnabled(enabled: Boolean) {
@@ -16,11 +16,12 @@ import okhttp3.Request
16
16
  /**
17
17
  * Lynx can't load anything by itself: the host app supplies loaders for
18
18
  * bundles, images and other resources. Ours read the copy of dist/ inside the
19
- * APK and fall back to HTTP for absolute http(s) URLs (an API, a CDN, or a dev
20
- * server).
19
+ * APK and fall back to HTTP for absolute http(s) URLs (an API, a CDN). The
20
+ * debug build `ng serve --platform android` runs has no copy: it loads what
21
+ * the bundle names from the dev server instead (DevServer.kt).
21
22
  */
22
23
 
23
- private val http by lazy { OkHttpClient() }
24
+ internal val http by lazy { OkHttpClient() }
24
25
 
25
26
  // LynxResourceResponse.onFailed is declared without a type parameter, so
26
27
  // Kotlin sees a raw type; this gives it the one each callback expects.
@@ -37,17 +38,21 @@ private fun load(
37
38
  ) {
38
39
  LynxThreadPool.getBriefIOExecutor().execute {
39
40
  try {
40
- val asset = BundleAssets.assetPath(url)
41
+ val remote = DevServer.remoteUrl(url)
42
+ val asset = if (remote == null) BundleAssets.assetPath(url) else null
41
43
  val bytes = if (asset != null) {
42
44
  BundleAssets.read(context, asset)
43
45
  } else {
44
- http.newCall(Request.Builder().url(url).build()).execute().use { response ->
45
- check(response.isSuccessful) { "HTTP ${response.code} for $url" }
46
+ val address = remote ?: url
47
+ http.newCall(Request.Builder().url(address).build()).execute().use { response ->
48
+ check(response.isSuccessful) { "HTTP ${response.code} for $address" }
46
49
  response.body!!.bytes()
47
50
  }
48
51
  }
52
+ DevServer.loaded(url, null)
49
53
  onSuccess(bytes)
50
54
  } catch (error: Throwable) {
55
+ DevServer.loaded(url, error)
51
56
  onFailure(Exception("Couldn't load $url: ${error.message}", error))
52
57
  }
53
58
  }
@@ -90,6 +95,7 @@ class AssetTemplateResourceFetcher(context: Context) : LynxTemplateResourceFetch
90
95
  */
91
96
  class AssetMediaResourceFetcher : LynxMediaResourceFetcher() {
92
97
  override fun shouldRedirectUrl(request: LynxResourceRequest): String {
98
+ DevServer.remoteUrl(request.url)?.let { return it }
93
99
  val asset = BundleAssets.assetPath(request.url) ?: return request.url
94
100
  return "asset:///$asset"
95
101
  }