@blotch/angular-lynx-native 22.3.0 → 22.3.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.
Files changed (100) hide show
  1. package/README.md +41 -15
  2. package/dist/android/project.d.ts +90 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +369 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +13 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/generate.d.ts +17 -1
  12. package/dist/generate.d.ts.map +1 -1
  13. package/dist/generate.js +12 -4
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8 -1
  17. package/dist/ios/build.d.ts.map +1 -1
  18. package/dist/ios/build.js +8 -2
  19. package/dist/ios/frameworks.d.ts +6 -5
  20. package/dist/ios/frameworks.d.ts.map +1 -1
  21. package/dist/ios/frameworks.js +46 -15
  22. package/dist/ios/project.d.ts +173 -11
  23. package/dist/ios/project.d.ts.map +1 -1
  24. package/dist/ios/project.js +767 -33
  25. package/dist/options.d.ts +143 -2
  26. package/dist/options.d.ts.map +1 -1
  27. package/dist/options.js +127 -0
  28. package/dist/permissions.d.ts +18 -1
  29. package/dist/permissions.d.ts.map +1 -1
  30. package/dist/permissions.js +63 -3
  31. package/package.json +1 -1
  32. package/templates/android/README.md +37 -2
  33. package/templates/android/angular-lynx.properties +2 -0
  34. package/templates/android/app/build.gradle.kts +70 -1
  35. package/templates/android/app/src/main/AndroidManifest.xml +24 -3
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +376 -6
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +25 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +168 -0
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +6 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +47 -3
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  65. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  66. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  67. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  68. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  69. package/templates/android/build.gradle.kts +1 -1
  70. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  71. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  72. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  73. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  74. package/templates/ios/App/AngularLynxVideo.h +37 -0
  75. package/templates/ios/App/AngularLynxVideo.m +435 -0
  76. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  77. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  78. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  79. package/templates/ios/App/AppDelegate.swift +34 -2
  80. package/templates/ios/App/AppleSignInButton.swift +106 -0
  81. package/templates/ios/App/AppleSignInModule.swift +222 -0
  82. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  83. package/templates/ios/App/BiometricsModule.swift +256 -0
  84. package/templates/ios/App/BluetoothModule.swift +1086 -0
  85. package/templates/ios/App/CalendarModule.swift +158 -0
  86. package/templates/ios/App/FilePickerModule.swift +240 -0
  87. package/templates/ios/App/HapticsModule.swift +90 -0
  88. package/templates/ios/App/Info.plist +2 -0
  89. package/templates/ios/App/LynxViewController.swift +210 -6
  90. package/templates/ios/App/MotionModule.swift +430 -0
  91. package/templates/ios/App/NfcModule.swift +346 -0
  92. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  93. package/templates/ios/App/ShareTargetModule.swift +150 -0
  94. package/templates/ios/App/ShellModule.swift +17 -0
  95. package/templates/ios/App/StoreReviewModule.swift +61 -0
  96. package/templates/ios/App/TrackingModule.swift +121 -0
  97. package/templates/ios/App/WifiModule.swift +237 -0
  98. package/templates/ios/App/XElementRegistry.swift +13 -3
  99. package/templates/ios/ShareExtension/Info.plist +42 -0
  100. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,168 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.content.ContentValues
4
+ import android.content.Context
5
+ import android.database.sqlite.SQLiteException
6
+ import android.net.Uri
7
+ import android.os.Build
8
+ import android.os.Environment
9
+ import android.provider.MediaStore
10
+ import android.util.Base64
11
+ import com.lynx.jsbridge.LynxMethod
12
+ import com.lynx.jsbridge.LynxModule
13
+ import com.lynx.react.bridge.Callback
14
+ import com.lynx.react.bridge.JavaOnlyMap
15
+ import com.lynx.react.bridge.ReadableMap
16
+ import java.io.IOException
17
+ import java.util.concurrent.Executors
18
+
19
+ /**
20
+ * The native module behind the runtime's `LynxPhotoLibrary`, which calls it
21
+ * as `NativeModules.AngularLynxPhotoLibrary` (from the background thread,
22
+ * where NativeModules lives).
23
+ *
24
+ * Only an app with `permissions.savePhotos` in angular.json has this file
25
+ * and the lines in MainActivity that register it: the generator deletes them
26
+ * from the others (@blotch/angular-lynx-native's android/project.ts).
27
+ *
28
+ * A photo goes into MediaStore's images, in `Pictures/<app name>`, and a
29
+ * video into its videos, in `Movies/<app name>`, where the gallery and
30
+ * Google Photos find them. From Android 10 an app may add its own media
31
+ * there without any permission, so the app declares none. Before Android 10
32
+ * it would need WRITE_EXTERNAL_STORAGE, asked for while it runs, which the
33
+ * shell has no way to ask for yet, so `save` answers `unavailable` there
34
+ * (and `permission` says `unsupported`). Each method calls back once with
35
+ * `{ permission }`, `{ id, permission }` or `{ error, message, permission }`,
36
+ * where `error` is one of the runtime's PhotoLibraryErrorCode values.
37
+ */
38
+ class PhotoLibraryModule(context: Context, param: Any?) : LynxModule(context, param) {
39
+ private val resolver = context.applicationContext.contentResolver
40
+ private val appName =
41
+ context.applicationInfo.loadLabel(context.packageManager).toString()
42
+
43
+ /** `{ permission }`: whether the app may add to the library. */
44
+ @LynxMethod
45
+ fun permission(callback: Callback) {
46
+ callback.invoke(JavaOnlyMap.from(mapOf("permission" to permissionName())))
47
+ }
48
+
49
+ /**
50
+ * Adds [request]'s file (`{ base64, name, type }`) to the library, and
51
+ * calls back with its `content://` URI.
52
+ */
53
+ @LynxMethod
54
+ fun save(request: ReadableMap, callback: Callback) {
55
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
56
+ callback.invoke(
57
+ failure(
58
+ "unavailable",
59
+ "Saving to the photo library needs Android 10 or later.",
60
+ ),
61
+ )
62
+ return
63
+ }
64
+ // Decoding and writing a video takes a moment: off the JavaScript
65
+ // thread, one at a time.
66
+ worker.execute {
67
+ callback.invoke(
68
+ try {
69
+ JavaOnlyMap.from(
70
+ mapOf("id" to insert(request).toString(), "permission" to permissionName()),
71
+ )
72
+ } catch (error: UnsupportedType) {
73
+ failure("unsupported-type", error.message ?: "Only images and videos can be saved.")
74
+ } catch (error: IllegalArgumentException) {
75
+ failure("failed", "The file's bytes couldn't be read.")
76
+ } catch (error: IOException) {
77
+ failure("failed", "The file couldn't be saved to the photo library: ${error.message}")
78
+ } catch (error: SecurityException) {
79
+ failure("permission-denied", "The app isn't allowed to add to the photo library.")
80
+ } catch (error: SQLiteException) {
81
+ // MediaStore's database couldn't take the entry, such as
82
+ // SQLiteFullException on a full phone. The provider
83
+ // rethrows it in the app, unchecked.
84
+ failure("failed", "The file couldn't be saved to the photo library: ${error.message}")
85
+ } catch (error: RuntimeException) {
86
+ // Anything else MediaStore throws: without an answer the
87
+ // runtime's save() would never settle, and an exception
88
+ // left on this thread would end the app.
89
+ failure("failed", "The file couldn't be saved to the photo library: ${error.message}")
90
+ },
91
+ )
92
+ }
93
+ }
94
+
95
+ private fun insert(request: ReadableMap): Uri {
96
+ val base64 = if (request.hasKey("base64")) request.getString("base64") else null
97
+ val bytes = Base64.decode(base64 ?: throw IllegalArgumentException(), Base64.DEFAULT)
98
+ val type = if (request.hasKey("type")) request.getString("type") ?: "" else ""
99
+ val isVideo = type.startsWith("video/")
100
+ if (!isVideo && !type.startsWith("image/")) {
101
+ throw UnsupportedType("$type isn't an image or a video.")
102
+ }
103
+ val name = (if (request.hasKey("name")) request.getString("name") else null)
104
+ ?.replace('/', '_')
105
+ ?.takeIf { it.isNotBlank() }
106
+ ?: if (isVideo) "Video.mp4" else "Photo.jpg"
107
+ val collection =
108
+ if (isVideo) {
109
+ MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
110
+ } else {
111
+ MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
112
+ }
113
+ val folder = if (isVideo) Environment.DIRECTORY_MOVIES else Environment.DIRECTORY_PICTURES
114
+ val values = ContentValues().apply {
115
+ put(MediaStore.MediaColumns.DISPLAY_NAME, name)
116
+ put(MediaStore.MediaColumns.MIME_TYPE, type)
117
+ put(MediaStore.MediaColumns.RELATIVE_PATH, "$folder/${folderName()}")
118
+ // Hidden from the gallery until it's all written, so nobody sees
119
+ // half a photo, and taken out again if writing fails.
120
+ put(MediaStore.MediaColumns.IS_PENDING, 1)
121
+ }
122
+ val uri = try {
123
+ resolver.insert(collection, values)
124
+ } catch (error: IllegalArgumentException) {
125
+ // MediaStore refuses a type its collection doesn't hold, such as
126
+ // an image type it doesn't know.
127
+ throw UnsupportedType("The photo library doesn't take $type files.")
128
+ } ?: throw IOException("MediaStore didn't make an entry for it.")
129
+ try {
130
+ resolver.openOutputStream(uri)?.use { it.write(bytes) }
131
+ ?: throw IOException("The new entry couldn't be opened.")
132
+ resolver.update(
133
+ uri,
134
+ ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) },
135
+ null,
136
+ null,
137
+ )
138
+ } catch (error: Exception) {
139
+ // A failed cleanup mustn't hide why the write failed.
140
+ try {
141
+ resolver.delete(uri, null, null)
142
+ } catch (cleanup: RuntimeException) {
143
+ error.addSuppressed(cleanup)
144
+ }
145
+ throw error
146
+ }
147
+ return uri
148
+ }
149
+
150
+ /** The app's name as a folder, without what a path can't hold. */
151
+ private fun folderName(): String =
152
+ appName.replace(Regex("[\\\\/:*?\"<>|]"), "_").trim().ifEmpty { "Pictures" }
153
+
154
+ private fun permissionName(): String =
155
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) "granted" else "unsupported"
156
+
157
+ private fun failure(code: String, message: String) =
158
+ JavaOnlyMap.from(mapOf("error" to code, "message" to message, "permission" to permissionName()))
159
+
160
+ private class UnsupportedType(message: String) : Exception(message)
161
+
162
+ companion object {
163
+ const val NAME = "AngularLynxPhotoLibrary"
164
+
165
+ // One thread, so saves happen in the order the app made them.
166
+ private val worker = Executors.newSingleThreadExecutor()
167
+ }
168
+ }
@@ -0,0 +1,234 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.content.Context
4
+ import android.content.Intent
5
+ import android.net.Uri
6
+ import android.os.Build
7
+ import android.os.Handler
8
+ import android.os.Looper
9
+ import android.provider.OpenableColumns
10
+ import android.util.Base64
11
+ import android.util.Log
12
+ import android.webkit.MimeTypeMap
13
+ import com.lynx.jsbridge.LynxMethod
14
+ import com.lynx.jsbridge.LynxModule
15
+ import com.lynx.react.bridge.Callback
16
+ import com.lynx.react.bridge.JavaOnlyArray
17
+ import com.lynx.react.bridge.JavaOnlyMap
18
+ import java.io.ByteArrayOutputStream
19
+ import java.io.IOException
20
+ import java.io.InputStream
21
+ import java.util.concurrent.Executors
22
+
23
+ /**
24
+ * The native module behind the runtime's `LynxShareTarget`, which calls it as
25
+ * `NativeModules.AngularLynxShareTarget` (from the background thread, where
26
+ * NativeModules lives). iOS's shell has one of the same name.
27
+ *
28
+ * angular.json's `shareTarget` puts `ACTION_SEND` and `ACTION_SEND_MULTIPLE`
29
+ * intent filters for its MIME types on MainActivity, so the app is in other
30
+ * apps' share sheets. A share may start the app, so the activity can't hand
31
+ * it straight to the Angular app: it leaves it here ([receive]), and the
32
+ * runtime takes it when it's ready, at startup and each time it hears the
33
+ * `angularLynxShare` global event. A share waits for as long as that takes,
34
+ * so the one that started the app isn't lost, and none is handled twice.
35
+ *
36
+ * The shared files are read as soon as the share arrives: the app may read
37
+ * another app's `content://` URI only while the activity it was granted to
38
+ * is alive. `take` calls back with `{ shares }`: each `{ title?, text?, url?,
39
+ * files: [{ base64, name, type }] }` since the last call, oldest first.
40
+ *
41
+ * The generator leaves this file, and the lines in MainActivity that hand it
42
+ * the intents and register it, out of an app whose angular.json has no
43
+ * `shareTarget`.
44
+ */
45
+ class ShareTargetModule(context: Context, param: Any?) : LynxModule(context, param) {
46
+ @LynxMethod
47
+ fun take(callback: Callback) {
48
+ val shares = JavaOnlyArray()
49
+ for (share in takeWaiting()) {
50
+ shares.pushMap(share)
51
+ }
52
+ callback.invoke(JavaOnlyMap.from(mapOf("shares" to shares)))
53
+ }
54
+
55
+ companion object {
56
+ const val NAME = "AngularLynxShareTarget"
57
+
58
+ // The global event that says a share is waiting. It carries nothing:
59
+ // the listener answers by taking them.
60
+ const val EVENT = "angularLynxShare"
61
+
62
+ private const val TAG = "AngularLynxShareTarget"
63
+
64
+ /**
65
+ * The most bytes of files one share hands the app, all its files
66
+ * together: 20 MiB, as LynxFilePicker's FILE_PICKER_MAX_BYTES. They
67
+ * travel to JavaScript as base64, held several times over on the
68
+ * way, so a file that would take a share past it is left out.
69
+ */
70
+ private const val MAX_BYTES = 20L * 1024 * 1024
71
+
72
+ /** An absolute link, which a share of a page carries as its text. */
73
+ private val LINK = Regex("^[a-zA-Z][a-zA-Z0-9+.-]*://\\S+$")
74
+
75
+ private val worker = Executors.newSingleThreadExecutor()
76
+ private val main = Handler(Looper.getMainLooper())
77
+
78
+ // The activity leaves them on the worker thread, and Lynx calls
79
+ // modules off it.
80
+ private val waiting = mutableListOf<JavaOnlyMap>()
81
+
82
+ /**
83
+ * Tells the runtime a share is waiting: set by the activity that's
84
+ * current, and called on the main thread once a share's files are
85
+ * read. A share is read on a worker thread, and Android may replace
86
+ * the activity that received it meanwhile, as on a rotation, so
87
+ * the event goes through the activity current then, rather than
88
+ * the one that started the read. Without one, the runtime takes
89
+ * the share as it next starts.
90
+ */
91
+ @Volatile
92
+ var arrived: (() -> Unit)? = null
93
+
94
+ /**
95
+ * Leaves the share `intent` carries for the runtime to take, and
96
+ * calls [arrived] once it's waiting. Returns whether the intent was
97
+ * a share.
98
+ */
99
+ fun receive(context: Context, intent: Intent): Boolean {
100
+ if (intent.action != Intent.ACTION_SEND && intent.action != Intent.ACTION_SEND_MULTIPLE) {
101
+ return false
102
+ }
103
+ val accepted = context.resources.getStringArray(R.array.angular_lynx_share_mime_types).toList()
104
+ val subject = intent.getStringExtra(Intent.EXTRA_SUBJECT) ?: intent.getStringExtra(Intent.EXTRA_TITLE)
105
+ val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()
106
+ val streams = streams(intent)
107
+ val resolver = context.applicationContext.contentResolver
108
+ // Reading a large photo takes a moment: off the main thread. The
109
+ // grant to read the URIs lasts as long as the activity, which
110
+ // this outlives only if the person leaves at once.
111
+ worker.execute {
112
+ val share = mutableMapOf<String, Any>()
113
+ if (subject != null) share["title"] = subject
114
+ // Android shares a link as text (Chrome sends its page's URL
115
+ // as text/plain): a text that is one link is the share's url,
116
+ // for an app that takes links.
117
+ val trimmed = text?.trim()
118
+ if (trimmed != null && LINK.matches(trimmed) && accepts(accepted, "text/uri-list")) {
119
+ share["url"] = trimmed
120
+ } else if (!text.isNullOrEmpty() && accepts(accepted, "text/plain")) {
121
+ share["text"] = text
122
+ }
123
+ val files = JavaOnlyArray()
124
+ var remaining = MAX_BYTES
125
+ for (uri in streams) {
126
+ val type = resolver.getType(uri) ?: typeFromName(uri) ?: "application/octet-stream"
127
+ if (!accepts(accepted, type)) continue
128
+ val bytes = try {
129
+ resolver.openInputStream(uri)?.use { readAtMost(it, remaining) }
130
+ } catch (error: IOException) {
131
+ Log.w(TAG, "Couldn't read $uri", error)
132
+ null
133
+ } catch (error: SecurityException) {
134
+ Log.w(TAG, "Not allowed to read $uri", error)
135
+ null
136
+ } ?: continue
137
+ if (bytes.size > remaining) {
138
+ Log.w(TAG, "Left out $uri: the share is over ${MAX_BYTES / 1024 / 1024} MiB")
139
+ continue
140
+ }
141
+ remaining -= bytes.size
142
+ files.pushMap(
143
+ JavaOnlyMap.from(
144
+ mapOf(
145
+ "base64" to Base64.encodeToString(bytes, Base64.NO_WRAP),
146
+ "name" to (displayName(context, uri) ?: uri.lastPathSegment ?: "file"),
147
+ "type" to type,
148
+ ),
149
+ ),
150
+ )
151
+ }
152
+ // Nothing the app takes, such as text for an app that takes
153
+ // only photos: there's nothing to hand over.
154
+ if (files.size == 0 && !share.containsKey("text") && !share.containsKey("url")) {
155
+ return@execute
156
+ }
157
+ share["files"] = files
158
+ synchronized(waiting) { waiting.add(JavaOnlyMap.from(share)) }
159
+ main.post { arrived?.invoke() }
160
+ }
161
+ return true
162
+ }
163
+
164
+ private fun takeWaiting(): List<JavaOnlyMap> =
165
+ synchronized(waiting) {
166
+ val taken = waiting.toList()
167
+ waiting.clear()
168
+ taken
169
+ }
170
+
171
+ /** The files a share carries: one for ACTION_SEND, a list for ACTION_SEND_MULTIPLE. */
172
+ @Suppress("DEPRECATION")
173
+ private fun streams(intent: Intent): List<Uri> {
174
+ if (intent.action == Intent.ACTION_SEND_MULTIPLE) {
175
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
176
+ intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java)
177
+ } else {
178
+ intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)
179
+ } ?: emptyList()
180
+ }
181
+ val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
182
+ intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)
183
+ } else {
184
+ intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
185
+ }
186
+ return listOfNotNull(uri)
187
+ }
188
+
189
+ /**
190
+ * Whether angular.json's `shareTarget.mimeTypes` takes [type]: the
191
+ * type itself, a wildcard for its subtype, or the wildcard for
192
+ * every type. The intent filters already chose, but a share's own
193
+ * type is often broader than each of its files', such as the
194
+ * wildcard for a photo and a PDF together.
195
+ */
196
+ private fun accepts(accepted: List<String>, type: String): Boolean {
197
+ val mime = type.lowercase()
198
+ val major = mime.substringBefore('/')
199
+ return accepted.any { it == "*/*" || it == mime || it == "$major/*" }
200
+ }
201
+
202
+ private fun typeFromName(uri: Uri): String? =
203
+ uri.lastPathSegment?.substringAfterLast('.', "")?.takeIf { it.isNotEmpty() }?.let {
204
+ MimeTypeMap.getSingleton().getMimeTypeFromExtension(it.lowercase())
205
+ }
206
+
207
+ /** The file's name, such as `photo.jpg`, as its provider gives it. */
208
+ private fun displayName(context: Context, uri: Uri): String? =
209
+ try {
210
+ context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
211
+ if (it.moveToFirst() && !it.isNull(0)) it.getString(0) else null
212
+ }
213
+ } catch (_: Exception) {
214
+ null
215
+ }
216
+
217
+ /**
218
+ * The stream's bytes, up to [limit] and one more: a result longer
219
+ * than [limit] says the file is over it, without reading the rest.
220
+ */
221
+ private fun readAtMost(input: InputStream, limit: Long): ByteArray {
222
+ val output = ByteArrayOutputStream()
223
+ val buffer = ByteArray(64 * 1024)
224
+ while (output.size() <= limit) {
225
+ val left = limit - output.size()
226
+ val wanted = if (left >= buffer.size) buffer.size else (left + 1).toInt()
227
+ val read = input.read(buffer, 0, wanted)
228
+ if (read < 0) break
229
+ output.write(buffer, 0, read)
230
+ }
231
+ return output.toByteArray()
232
+ }
233
+ }
234
+ }
@@ -12,6 +12,7 @@ import com.lynx.service.image.LynxImageService
12
12
  import com.lynx.service.log.LynxLogService
13
13
  import com.lynx.tasm.LynxEnv
14
14
  import com.lynx.tasm.base.LLog
15
+ import com.lynx.tasm.behavior.shadow.text.TypefaceCache
15
16
  import com.lynx.tasm.service.LynxServiceCenter
16
17
 
17
18
  /**
@@ -39,6 +40,11 @@ class ShellApplication : Application() {
39
40
  // its loaders to the LynxView it builds.
40
41
  LynxEnv.inst().init(this, null, null, null)
41
42
 
43
+ // Android's own font families (`monospace`, `serif`...), which Lynx
44
+ // doesn't find by itself (SystemFontFamilies.kt). Before the first
45
+ // LynxView, so its first text finds them.
46
+ TypefaceCache.addLazyProvider(SystemFontFamilies)
47
+
42
48
  // Lynx's libraries are built for release, where Lynx logs at INFO: a
43
49
  // line for every touch, flush, layout, event listener and main-thread
44
50
  // module call, each a call from native code back into Java and an
@@ -3,6 +3,9 @@ package dev.angularlynx.shell
3
3
  import android.content.Context
4
4
  import android.os.Handler
5
5
  import android.os.Looper
6
+ import android.os.SystemClock
7
+ import android.os.Trace
8
+ import android.util.Log
6
9
  import com.lynx.jsbridge.LynxMethod
7
10
  import com.lynx.jsbridge.LynxModule
8
11
  import com.lynx.tasm.LynxEnv
@@ -16,10 +19,13 @@ import com.lynx.tasm.LynxEnv
16
19
  * gesture starts whether the app will handle it (predictive back shows a
17
20
  * different animation either way). The Angular app can't answer in time, so it
18
21
  * tells us ahead of time instead: it enables the back handler while the Router
19
- * has somewhere to go back to. While enabled, back presses become an
22
+ * has somewhere to go back to, or something open on top (a popover) takes
23
+ * back. While enabled, back presses become an
20
24
  * `angularLynxBack` global event; while disabled (the default, and whenever the
21
25
  * runtime doesn't know about this module) Android's default back behavior
22
- * applies, which leaves the app.
26
+ * applies, which leaves the app. While enabled, the predictive back gesture
27
+ * also arrives as it goes, as `angularLynxBackGesture` global events, so a
28
+ * stack in the app can move its page with the finger.
23
29
  *
24
30
  * `collectGarbage` runs a full collection of the main thread's JavaScript
25
31
  * heap. PrimJS, which runs it, collects as the app runs, but those collections
@@ -40,7 +46,26 @@ import com.lynx.tasm.LynxEnv
40
46
  * `am start -W`'s callers) read as time to full display. It's called on the
41
47
  * thread the runtime calls from, Lynx's engine thread: the system takes it
42
48
  * from any thread, and a post to the UI thread would add a wait to the moment
43
- * it marks.
49
+ * it marks. Each call also logs `Fully Drawn at <ns> ns` (below).
50
+ *
51
+ * `markEvent(name)` marks any other moment the app names, as an instant
52
+ * section of that name in a system trace (`Trace.beginSection`, ended at
53
+ * once), which Perfetto and Android Studio's profiler show on the thread
54
+ * that called it: the start of the work a profile is about, for example.
55
+ * Every call marks. The benchmark apps mark `MountStart` as their mount
56
+ * screen starts building (`benchmarks/SPEC.md`); the iOS shell's is an
57
+ * `os_signpost` event that Instruments shows.
58
+ *
59
+ * Both also log a line under this module's name, `Mark <name> at <ns> ns`
60
+ * and `Fully Drawn at <ns> ns`, with `SystemClock.elapsedRealtimeNanos()`
61
+ * at the call. logcat shows neither trace sections nor when the app called
62
+ * reportFullyDrawn: its own `Fully drawn` line gives a time from the
63
+ * launch's start, or from the first frame for a call before it, on no clock
64
+ * a mark shares. The benchmark harness (`android_launch.py`) reads the two
65
+ * lines to time a mount screen from its `MountStart` to its fully drawn call,
66
+ * as the iOS harness does with the two signposts. The clock is in the
67
+ * message, rather than taken from logcat's timestamps, because those are
68
+ * wall-clock time, which an emulator steps when it syncs with its host.
44
69
  */
45
70
  class ShellModule(context: Context, param: Any?) : LynxModule(context, param) {
46
71
  private val host = param as Host
@@ -64,7 +89,21 @@ class ShellModule(context: Context, param: Any?) : LynxModule(context, param) {
64
89
 
65
90
  @LynxMethod
66
91
  fun reportFullyDrawn() {
92
+ // Read before the call, which is the moment it marks: the system's
93
+ // own bookkeeping comes after.
94
+ val at = SystemClock.elapsedRealtimeNanos()
67
95
  host.markFullyDrawn()
96
+ Log.i(NAME, "Fully Drawn at $at ns")
97
+ }
98
+
99
+ // On the calling thread, as reportFullyDrawn is, so the mark lands at the
100
+ // moment it marks. A trace section's name is at most 127 characters.
101
+ @LynxMethod
102
+ fun markEvent(name: String) {
103
+ val at = SystemClock.elapsedRealtimeNanos()
104
+ Trace.beginSection(name.take(127))
105
+ Trace.endSection()
106
+ Log.i(NAME, "Mark $name at $at ns")
68
107
  }
69
108
 
70
109
  @LynxMethod
@@ -76,6 +115,11 @@ class ShellModule(context: Context, param: Any?) : LynxModule(context, param) {
76
115
  const val NAME = "AngularLynxShell"
77
116
  const val BACK_EVENT = "angularLynxBack"
78
117
 
118
+ // Android's predictive back gesture as it goes (see MainActivity's
119
+ // backHandler): it starts, moves, or is canceled. One that ends in
120
+ // back sends BACK_EVENT, as a press does.
121
+ const val BACK_GESTURE_EVENT = "angularLynxBackGesture"
122
+
79
123
  // Lynx's MemoryPressureLevel values, from a package the app doesn't
80
124
  // compile against.
81
125
  const val MEMORY_PRESSURE_MODERATE = 1
@@ -0,0 +1,66 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.os.Handler
6
+ import android.os.Looper
7
+ import android.util.Log
8
+ import com.google.android.play.core.review.ReviewManagerFactory
9
+ import com.lynx.jsbridge.LynxMethod
10
+ import com.lynx.jsbridge.LynxModule
11
+ import com.lynx.react.bridge.Callback
12
+ import com.lynx.react.bridge.JavaOnlyMap
13
+
14
+ /**
15
+ * The native module behind the runtime's `LynxStoreReview`, which calls it as
16
+ * `NativeModules.AngularLynxStoreReview` (from the background thread, where
17
+ * NativeModules lives). MainActivity registers it with itself as the param:
18
+ * Google Play shows the rating prompt over it.
19
+ *
20
+ * `request` asks Play's In-App Review API for a review flow and launches it,
21
+ * then calls back once with `{}`. Play decides whether the prompt shows, and
22
+ * doesn't say: it has a quota per person, shows nothing until the account
23
+ * has installed the app from Play (an internal test track or internal app
24
+ * sharing will do), and fails
25
+ * where the phone has no Play Store. None of that is something the app can
26
+ * act on, so a failure is logged and calls back the same `{}`.
27
+ *
28
+ * The generator leaves this file, the lines in MainActivity that register it
29
+ * and Play's review library out of an app whose angular.json doesn't set
30
+ * `storeReview`.
31
+ */
32
+ class StoreReviewModule(context: Context, param: Any?) : LynxModule(context, param) {
33
+ private val activity = param as Activity
34
+ private val main = Handler(Looper.getMainLooper())
35
+
36
+ // Lynx calls modules off the main thread. Play's tasks call their
37
+ // listeners on the main thread, and the flow is launched from there too,
38
+ // over the activity.
39
+ @LynxMethod
40
+ fun request(callback: Callback) {
41
+ main.post {
42
+ val done = { callback.invoke(JavaOnlyMap()) }
43
+ try {
44
+ val manager = ReviewManagerFactory.create(activity)
45
+ manager.requestReviewFlow().addOnCompleteListener { request ->
46
+ if (!request.isSuccessful || activity.isFinishing) {
47
+ Log.w(TAG, "Google Play has no review flow for the app", request.exception)
48
+ done()
49
+ return@addOnCompleteListener
50
+ }
51
+ // Completes once the prompt has closed, or at once when
52
+ // Play chose not to show it.
53
+ manager.launchReviewFlow(activity, request.result).addOnCompleteListener { done() }
54
+ }
55
+ } catch (error: RuntimeException) {
56
+ Log.w(TAG, "Google Play's review flow failed", error)
57
+ done()
58
+ }
59
+ }
60
+ }
61
+
62
+ companion object {
63
+ const val NAME = "AngularLynxStoreReview"
64
+ private const val TAG = "AngularLynxStoreReview"
65
+ }
66
+ }
@@ -0,0 +1,68 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.graphics.Typeface
4
+ import android.os.Build
5
+ import com.lynx.tasm.behavior.shadow.text.TypefaceCache
6
+ import java.util.Locale
7
+
8
+ /**
9
+ * Lets `font-family` name Android's own font families, as a browser does:
10
+ * `monospace`, `serif`, `sans-serif`, the other CSS generic families Android
11
+ * has a font for, and the families in the system's fonts.xml
12
+ * (`sans-serif-condensed`, `serif-monospace`, `casual`...).
13
+ *
14
+ * Lynx on Android finds a family only in the providers the host app
15
+ * registers and in the app's `@font-face` rules (TypefaceCache.getTypeface,
16
+ * then FontFaceManager); neither asks Android for its system families, so
17
+ * `font-family: Menlo, monospace` (the build plugin's rule for `<code>`)
18
+ * drew the default font. iOS finds installed fonts by name itself.
19
+ *
20
+ * Lynx walks the list a family at a time, so a name Android doesn't have
21
+ * must return null here, letting Lynx try the app's `@font-face` rules and
22
+ * then the next family in the list. Lynx asks the providers before the
23
+ * `@font-face` rules, so an app's `@font-face` named after one of these
24
+ * families loses to the system's. A browser treats unquoted generic names the
25
+ * same way, and Lynx drops the quotes that would tell the two apart.
26
+ */
27
+ object SystemFontFamilies : TypefaceCache.LazyProvider {
28
+ // CSS's generic families, and the Android family each draws in, with
29
+ // `system-ui` in the system font as Chrome draws it. Android has no
30
+ // family for `fantasy`, `math` or `emoji` (emoji come from the fallback
31
+ // fonts whatever the family), and Chrome doesn't know Safari's `ui-*`
32
+ // families, so those fall through to the next family in the list.
33
+ private val NAMED_FAMILIES = mapOf(
34
+ "serif" to "serif",
35
+ "sans-serif" to "sans-serif",
36
+ "monospace" to "monospace",
37
+ "cursive" to "cursive",
38
+ "system-ui" to "sans-serif",
39
+ // fonts.xml's aliases of `sans-serif`. Android hands back the default
40
+ // Typeface itself for them, which the check below can't tell from a
41
+ // name it doesn't have, so they're named here: `Arial, monospace`
42
+ // draws Arial's alias, as Chrome on Android does.
43
+ "arial" to "sans-serif",
44
+ "helvetica" to "sans-serif",
45
+ "tahoma" to "sans-serif",
46
+ "verdana" to "sans-serif",
47
+ )
48
+
49
+ // Lynx calls this from TypefaceCache, which caches each family and style
50
+ // it returns, so a family is looked up once. `style` is Typeface's style
51
+ // (NORMAL, BOLD, ITALIC or BOLD_ITALIC), from the text's font-weight and
52
+ // font-style.
53
+ override fun getTypeface(fontFamily: String, style: Int): Typeface? {
54
+ // CSS family names ignore case; Android's are all lowercase.
55
+ val family = fontFamily.lowercase(Locale.ROOT)
56
+ NAMED_FAMILIES[family]?.let { return Typeface.create(it, style) }
57
+
58
+ // Any other family in fonts.xml. Typeface.create(name) gives back
59
+ // Typeface.DEFAULT itself for a name it doesn't have, from Android 9;
60
+ // before it, that isn't promised, so earlier versions find only the
61
+ // generic families (returning the default there would stop Lynx at a
62
+ // family the system doesn't have and skip the rest of the list).
63
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return null
64
+ val typeface = Typeface.create(family, Typeface.NORMAL)
65
+ if (typeface === Typeface.DEFAULT) return null
66
+ return Typeface.create(typeface, style)
67
+ }
68
+ }