@blotch/angular-lynx-native 22.2.25 → 22.2.26

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 (47) hide show
  1. package/README.md +5 -3
  2. package/dist/android/project.d.ts +2 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +4 -1
  5. package/dist/generate.d.ts +1 -1
  6. package/dist/generate.js +8 -2
  7. package/dist/index.d.ts +3 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +9 -0
  10. package/dist/ios/project.d.ts +3 -2
  11. package/dist/ios/project.d.ts.map +1 -1
  12. package/dist/ios/project.js +12 -2
  13. package/dist/options.d.ts +57 -0
  14. package/dist/options.d.ts.map +1 -1
  15. package/dist/options.js +51 -0
  16. package/dist/png.d.ts +5 -0
  17. package/dist/png.d.ts.map +1 -1
  18. package/dist/png.js +19 -5
  19. package/dist/splash.d.ts +70 -0
  20. package/dist/splash.d.ts.map +1 -0
  21. package/dist/splash.js +239 -0
  22. package/package.json +1 -1
  23. package/templates/android/README.md +8 -1
  24. package/templates/android/app/build.gradle.kts +4 -0
  25. package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServer.kt +6 -0
  26. package/templates/android/app/src/main/AndroidManifest.xml +3 -1
  27. package/templates/android/app/src/main/java/dev/angularlynx/shell/AssetsModule.kt +2 -1
  28. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +16 -3
  29. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +57 -1
  30. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +10 -0
  31. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +15 -4
  32. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +10 -1
  33. package/templates/android/app/src/main/res/values/colors.xml +3 -2
  34. package/templates/android/app/src/main/res/values/splash.xml +9 -0
  35. package/templates/android/app/src/main/res/values/themes.xml +14 -0
  36. package/templates/android/app/src/release/java/dev/angularlynx/shell/DevServer.kt +2 -0
  37. package/templates/ios/App/AngularLynxWebGL.h +34 -6
  38. package/templates/ios/App/AngularLynxWebGL.m +58 -23
  39. package/templates/ios/App/AngularLynxWebGLContext.m +25 -21
  40. package/templates/ios/App/AnimationFrameRate.swift +214 -0
  41. package/templates/ios/App/AppDelegate.swift +2 -0
  42. package/templates/ios/App/AssetsModule.swift +3 -1
  43. package/templates/ios/App/DevServer.swift +3 -0
  44. package/templates/ios/App/Info.plist +12 -5
  45. package/templates/ios/App/LynxViewController.swift +19 -1
  46. package/templates/ios/App/ShellModule.swift +14 -1
  47. package/templates/ios/App/SplashScreen.swift +71 -0
package/dist/splash.js ADDED
@@ -0,0 +1,239 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { DENSITIES } from "./android/icon.js";
4
+ import { centerOnCanvas, decodePng, encodePng, readPngSize, resize, } from "./png.js";
5
+ /**
6
+ * Android's splash icon, without an icon background, is a 288 dp square...
7
+ */
8
+ export const ANDROID_SLOT_DP = 288;
9
+ /**
10
+ * ...of which it shows the middle: a circle 192 dp across, two thirds of it.
11
+ * Anything outside the circle is cut off.
12
+ */
13
+ export const ANDROID_CIRCLE_DP = 192;
14
+ /** The scales iPhones draw at: 1× is no longer made, but the simulator has it. */
15
+ const IOS_SCALES = [1, 2, 3];
16
+ /** Where the shells find the launch image, by name. */
17
+ export const IOS_IMAGE_SET = 'LaunchImage';
18
+ const ANDROID_ICON = 'splash_icon';
19
+ /**
20
+ * The template's alias of the splash icon to the launcher icon, which an app
21
+ * with a splash image replaces with its own drawable of the same name.
22
+ */
23
+ const ANDROID_ICON_ALIAS = 'app/src/main/res/values/splash.xml';
24
+ /**
25
+ * The image's size on screen in points (dp on Android): `imageWidth` across,
26
+ * and as tall as its shape makes that.
27
+ */
28
+ export const splashImageSize = (pixels, imageWidth) => ({
29
+ width: imageWidth,
30
+ height: (imageWidth * pixels.height) / pixels.width,
31
+ });
32
+ /**
33
+ * The size Android draws the image at: as on iOS, unless its corners reach
34
+ * past the circle Android shows, when it's scaled down until they touch it.
35
+ * A wide logo is then smaller than on iOS, but whole.
36
+ */
37
+ export const androidSplashSize = (size) => {
38
+ const scale = Math.min(1, ANDROID_CIRCLE_DP / Math.hypot(size.width, size.height));
39
+ return { width: size.width * scale, height: size.height * scale };
40
+ };
41
+ /**
42
+ * The splash images, each once: light, then dark if it's another file.
43
+ */
44
+ const splashImages = (splash) => [
45
+ ...(splash.light.image
46
+ ? [{ option: 'splash.image', file: splash.light.image }]
47
+ : []),
48
+ ...(splash.dark.image && splash.dark.image !== splash.light.image
49
+ ? [{ option: 'splash.dark.image', file: splash.dark.image }]
50
+ : []),
51
+ ];
52
+ /**
53
+ * What's worth knowing about how the splash images will look, checked on
54
+ * every build (unlike the project, which is generated only when its inputs
55
+ * change): an image too wide for Android's circle, or with too few pixels to
56
+ * be sharp. A missing image is left to generation, which fails on it.
57
+ */
58
+ export const splashWarnings = (app, projectRoot, platform) => {
59
+ const { imageWidth } = app.splash;
60
+ if (imageWidth === undefined)
61
+ return [];
62
+ const warnings = [];
63
+ for (const { option, file } of splashImages(app.splash)) {
64
+ const absolute = path.resolve(projectRoot, file);
65
+ if (!existsSync(absolute))
66
+ continue;
67
+ const pixels = readPngSize(absolute);
68
+ const size = splashImageSize(pixels, imageWidth);
69
+ const needed = Math.ceil(imageWidth * 3);
70
+ if (pixels.width < needed) {
71
+ warnings.push(`${option} is ${pixels.width} px wide: at ${imageWidth} points, a 3× screen needs ${needed} px for it to be sharp.`);
72
+ }
73
+ const drawn = androidSplashSize(size);
74
+ if (platform === 'android' && drawn.width < size.width) {
75
+ // The widest image of this shape that fits the circle whole.
76
+ const widest = Math.floor((ANDROID_CIRCLE_DP * pixels.width) /
77
+ Math.hypot(pixels.width, pixels.height));
78
+ warnings.push(`${option} at ${imageWidth} dp wide doesn't fit in the circle ${ANDROID_CIRCLE_DP} dp across that Android shows of a splash screen's image, so Android draws it ${Math.floor(drawn.width)} dp wide. With an imageWidth of ${widest} or less, it's the same size on iOS and Android.`);
79
+ }
80
+ }
81
+ return warnings;
82
+ };
83
+ /**
84
+ * Reads a splash image, whose shape and size are free (unlike the icon's),
85
+ * so only its being there is checked.
86
+ */
87
+ const loadImage = (projectRoot, option, file) => {
88
+ const absolute = path.resolve(projectRoot, file);
89
+ if (!existsSync(absolute)) {
90
+ throw new Error(`${option}: ${file} doesn't exist.`);
91
+ }
92
+ // Fails with "is not a PNG file" before pngjs gets a JPEG renamed .png.
93
+ readPngSize(absolute);
94
+ return decodePng(readFileSync(absolute));
95
+ };
96
+ /**
97
+ * `#RGB` or `#RRGGBB` as its three channels, 0 to 255.
98
+ */
99
+ const channels = (color) => {
100
+ const hex = color.length === 4 ? color.slice(1).replace(/./g, '$&$&') : color.slice(1);
101
+ return [0, 2, 4].map((at) => parseInt(hex.slice(at, at + 2), 16));
102
+ };
103
+ const DARK_APPEARANCE = [{ appearance: 'luminosity', value: 'dark' }];
104
+ const ASSET_INFO = { author: 'xcode', version: 1 };
105
+ /**
106
+ * The `LaunchBackground` color set: the launch screen's color, which the
107
+ * shell also paints behind the LynxView. Only its dark entry varies with dark
108
+ * mode: an entry without an appearance is the color for any.
109
+ */
110
+ export const launchBackgroundColorSet = (splash) => {
111
+ const color = (value) => {
112
+ const [red, green, blue] = channels(value);
113
+ return {
114
+ 'color-space': 'srgb',
115
+ components: {
116
+ alpha: '1.000',
117
+ blue: (blue / 255).toFixed(3),
118
+ green: (green / 255).toFixed(3),
119
+ red: (red / 255).toFixed(3),
120
+ },
121
+ };
122
+ };
123
+ // The template's white, when only dark mode has a color.
124
+ const light = splash.light.backgroundColor ?? '#FFFFFF';
125
+ const dark = splash.dark.backgroundColor;
126
+ return `${JSON.stringify({
127
+ colors: [
128
+ { color: color(light), idiom: 'universal' },
129
+ ...(dark && dark !== light
130
+ ? [
131
+ {
132
+ appearances: DARK_APPEARANCE,
133
+ color: color(dark),
134
+ idiom: 'universal',
135
+ },
136
+ ]
137
+ : []),
138
+ ],
139
+ info: ASSET_INFO,
140
+ }, null, 2)}\n`;
141
+ };
142
+ /** The image set's Contents.json, for the files {@link writeIosSplash} writes. */
143
+ export const launchImageSet = (hasDark) => `${JSON.stringify({
144
+ images: [
145
+ ...IOS_SCALES.map((scale) => ({
146
+ filename: `${IOS_IMAGE_SET}${scale === 1 ? '' : `@${scale}x`}.png`,
147
+ idiom: 'universal',
148
+ scale: `${scale}x`,
149
+ })),
150
+ ...(hasDark
151
+ ? IOS_SCALES.map((scale) => ({
152
+ appearances: DARK_APPEARANCE,
153
+ filename: `${IOS_IMAGE_SET}-dark${scale === 1 ? '' : `@${scale}x`}.png`,
154
+ idiom: 'universal',
155
+ scale: `${scale}x`,
156
+ }))
157
+ : []),
158
+ ],
159
+ info: ASSET_INFO,
160
+ }, null, 2)}\n`;
161
+ /**
162
+ * Writes the splash into the iOS project's asset catalog: the
163
+ * `LaunchBackground` color set, and the `LaunchImage` image set at 1×, 2× and
164
+ * 3× (and again for dark mode). Info.plist's UILaunchScreen names them (see
165
+ * `infoPlistEntries`), and the shell's SplashScreen.swift draws the same two
166
+ * over the app until the app hides it.
167
+ *
168
+ * Each scale is made here: a launch screen draws its image at its natural
169
+ * size, which is its pixels over its scale, so each copy is `imageWidth`
170
+ * points across.
171
+ */
172
+ export const writeIosSplash = (dir, app, projectRoot) => {
173
+ const { splash } = app;
174
+ const assets = path.join(dir, 'App/Assets.xcassets');
175
+ if (splash.light.backgroundColor || splash.dark.backgroundColor) {
176
+ writeFileSync(path.join(assets, 'LaunchBackground.colorset/Contents.json'), launchBackgroundColorSet(splash));
177
+ }
178
+ if (!splash.light.image || splash.imageWidth === undefined)
179
+ return;
180
+ const set = path.join(assets, `${IOS_IMAGE_SET}.imageset`);
181
+ mkdirSync(set, { recursive: true });
182
+ const images = splashImages(splash);
183
+ for (const [index, { option, file }] of images.entries()) {
184
+ const image = loadImage(projectRoot, option, file);
185
+ const size = splashImageSize(image, splash.imageWidth);
186
+ for (const scale of IOS_SCALES) {
187
+ const name = `${IOS_IMAGE_SET}${index === 0 ? '' : '-dark'}${scale === 1 ? '' : `@${scale}x`}.png`;
188
+ writeFileSync(path.join(set, name), encodePng(resize(image, Math.max(1, Math.round(size.width * scale)), Math.max(1, Math.round(size.height * scale)))));
189
+ }
190
+ }
191
+ writeFileSync(path.join(set, 'Contents.json'), launchImageSet(images.length > 1));
192
+ };
193
+ /**
194
+ * Sets the template's `window_background` color, the splash screen's color
195
+ * and the window's behind the LynxView, in one of its colors.xml files.
196
+ */
197
+ const setWindowBackground = (file, color) => {
198
+ const source = readFileSync(file, 'utf8');
199
+ const updated = source.replace(/(<color name="window_background">)[^<]*(<\/color>)/, `$1${color}$2`);
200
+ if (updated === source && !source.includes(`>${color}<`)) {
201
+ throw new Error(`${file} has no window_background color.`);
202
+ }
203
+ writeFileSync(file, updated);
204
+ };
205
+ /**
206
+ * Writes the splash into the Android project's resources: its colors as
207
+ * `window_background` (light in `values/`, dark in `values-night/`), which
208
+ * the splash theme and the window behind the LynxView both use, and its
209
+ * image as the `splash_icon` drawable the theme shows.
210
+ *
211
+ * Android shows a splash image in a 288 dp square, cut to the circle 192 dp
212
+ * across in its middle, and scales whatever drawable it's given to the
213
+ * square. So the image is drawn on a transparent 288 dp canvas, at
214
+ * `imageWidth` dp, or smaller if its corners would be cut off, and the canvas
215
+ * made at each density, as the icons are.
216
+ */
217
+ export const writeAndroidSplash = (dir, app, projectRoot) => {
218
+ const { splash } = app;
219
+ const res = path.join(dir, 'app/src/main/res');
220
+ if (splash.light.backgroundColor) {
221
+ setWindowBackground(path.join(res, 'values/colors.xml'), splash.light.backgroundColor);
222
+ }
223
+ if (splash.dark.backgroundColor) {
224
+ setWindowBackground(path.join(res, 'values-night/colors.xml'), splash.dark.backgroundColor);
225
+ }
226
+ if (!splash.light.image || splash.imageWidth === undefined)
227
+ return;
228
+ rmSync(path.join(dir, ANDROID_ICON_ALIAS), { force: true });
229
+ for (const [index, { option, file }] of splashImages(splash).entries()) {
230
+ const image = loadImage(projectRoot, option, file);
231
+ const drawn = androidSplashSize(splashImageSize(image, splash.imageWidth));
232
+ for (const [density, scale] of Object.entries(DENSITIES)) {
233
+ const folder = path.join(res, `drawable-${index === 0 ? '' : 'night-'}${density}`);
234
+ mkdirSync(folder, { recursive: true });
235
+ const canvas = Math.round(ANDROID_SLOT_DP * scale);
236
+ writeFileSync(path.join(folder, `${ANDROID_ICON}.png`), encodePng(centerOnCanvas(resize(image, Math.min(canvas, Math.max(1, Math.round(drawn.width * scale))), Math.min(canvas, Math.max(1, Math.round(drawn.height * scale)))), canvas, canvas)));
237
+ }
238
+ }
239
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotch/angular-lynx-native",
3
- "version": "22.2.25",
3
+ "version": "22.2.26",
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": {
@@ -13,6 +13,7 @@ The app is one activity holding one full-screen `LynxView` that runs `main.lynx.
13
13
  | Permissions | `AndroidManifest.xml`, at `<!-- angular-lynx:permissions -->` | `<uses-permission>` lines. `INTERNET` is always declared. |
14
14
  | Deep links | `AndroidManifest.xml`, at `<!-- angular-lynx:deep-links -->` | `<intent-filter>`s inside the main activity. |
15
15
  | Shortcuts | `res/xml/shortcuts.xml`, `res/values/shortcuts.xml` | One `<shortcut>` per entry of angular.json's `shortcuts`, and a string for its title. The committed `shortcuts.xml` is an empty list. |
16
+ | Splash screen | `res/values*/colors.xml`, `res/drawable-*/splash_icon.png` | angular.json's `splash`: its colors as `window_background` (`values/`, `values-night/`), and its image drawn on a transparent 288 dp canvas at each density, in place of `res/values/splash.xml`'s alias to the launcher icon. |
16
17
  | SDK location | `local.properties` | `sdk.dir=…`, unless `ANDROID_HOME` is set. |
17
18
  | Release signing | Gradle properties, from the environment | `ORG_GRADLE_PROJECT_angularLynxStoreFile`, `…StorePassword`, `…KeyAlias`, `…KeyPassword` (no dots: dash, `/bin/sh` on Debian and Ubuntu, drops variables whose names aren't shell identifiers before `gradlew` starts Gradle). Never written to disk. Without all four, release builds are signed with the debug key (installable, not uploadable). |
18
19
 
@@ -35,6 +36,12 @@ Build commands and outputs (no flavors, so the names are fixed):
35
36
 
36
37
  Back is off by default, so it leaves the app like any root screen. The runtime turns it on while the Router has history by calling `NativeModules.AngularLynxShell.setBackHandlerEnabled(true)`, and off again on the first screen (`LynxBackButton` in `packages/runtime/src/lib/router/lynx-back-button.ts`, which `provideRouter()` starts; the call goes through the background thread, where `NativeModules` lives). While it's on, a back press sends the global event `angularLynxBack` instead, which the runtime turns into `Location.back()`. The app has to say beforehand because Android decides synchronously, at the start of the gesture, whether an app handles back (predictive back animates differently). Layer 6's `native/back-button.yaml` checks both ends.
37
38
 
39
+ ## Splash screen
40
+
41
+ `MainActivity` starts with the theme `Theme.AngularLynxShell.Starting` (`res/values/themes.xml`), a child of AndroidX `core-splashscreen`'s `Theme.SplashScreen`, which draws Android 12's splash screen on every version from 7: `window_background` with `splash_icon` in the middle, the launcher icon unless angular.json's `splash` has an image. `installSplashScreen()`, before `super.onCreate`, switches it to the app's theme. Android would take the splash down at the first frame, the empty LynxView, so `setKeepOnScreenCondition` holds it until the runtime calls `NativeModules.AngularLynxShell.hideSplashScreen()` (`LynxSplashScreen` in `packages/runtime`, once the app's first screen is drawn), a development build's message shows, or five seconds pass. The exit animation fades it out over 250 ms, as the iOS shell does.
42
+
43
+ Android shows a splash icon without an icon background in a 288 dp square, cut to the circle 192 dp across in its middle. The generator draws the image at `splash.imageWidth` dp on a 288 dp canvas, smaller if its corners would reach past the circle (the build warns then), so a logo is never cropped.
44
+
38
45
  ## Memory
39
46
 
40
47
  PrimJS, which runs the app's JavaScript on Lynx's main thread, collects garbage as the app runs, but those collections leave behind much of what a screen leaves when it goes, so native memory grows with every screen the app shows. Lynx runs a full collection, which frees it, when the host reports memory pressure with `LynxEnv.trimMemory`. The runtime asks for one through `NativeModules.AngularLynxShell.collectGarbage()` (`ShellModule.kt`, which reports moderate pressure) once the app has released about a screen's worth of elements and settled (`collect-garbage.ts` in `packages/runtime`), and `ShellApplication.kt` reports the system's `onTrimMemory` and `onLowMemory`, including the app leaving the screen.
@@ -88,7 +95,7 @@ The module reads the picked photo on a background thread and calls back once wit
88
95
 
89
96
  ## Canvas and WebGL
90
97
 
91
- `<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.
98
+ `<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 Lynx's engine thread, which `MainActivity` runs off the UI thread (`setThreadStrategyForRendering(ThreadStrategyForRendering.MOST_ON_TASM)`). The canvas's `TextureView` reports its surface on the UI thread, so `WebGLContext` and `CanvasRegistry` are locked: each call makes the EGL context current and puts back what was current before, so either thread can make the next one, and a surface callback waits for a batch to end. 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.
92
99
 
93
100
  Android's GLES has no 2D uploads from a `PIXEL_UNPACK_BUFFER` and no `glGetVertexAttribPointerv`, so those log a warning and answer 0.
94
101
 
@@ -122,6 +122,10 @@ android {
122
122
  dependencies {
123
123
  implementation("androidx.activity:activity-ktx:1.10.1")
124
124
  implementation("androidx.core:core-ktx:1.16.0")
125
+ // The splash screen (MainActivity, themes.xml): Android 12's on every
126
+ // version the app runs on, and kept up until the app's first screen is
127
+ // ready.
128
+ implementation("androidx.core:core-splashscreen:1.2.0")
125
129
  // Custom Tabs, which WebAuthModule opens sign-in pages in, and
126
130
  // LinkingModule the pages of openInApp().
127
131
  implementation("androidx.browser:browser:1.8.0")
@@ -150,6 +150,12 @@ object DevServer {
150
150
  }
151
151
  }
152
152
 
153
+ /**
154
+ * Whether a message is on screen, such as that the dev server can't be
155
+ * reached: the splash screen makes way for it (MainActivity).
156
+ */
157
+ fun isShowingMessage(): Boolean = status?.visibility == View.VISIBLE
158
+
153
159
  private fun show(message: String) {
154
160
  val status = status ?: return
155
161
  status.text = message
@@ -32,7 +32,8 @@
32
32
  One activity holding one LynxView; Angular Router does all navigation
33
33
  inside it. configChanges keeps the activity (and the running Angular
34
34
  app) alive on rotation, resizing and dark-mode switches instead of
35
- restarting it; the LynxView re-lays itself out.
35
+ restarting it; the LynxView re-lays itself out. It starts with the
36
+ splash screen's theme, which installSplashScreen() replaces.
36
37
  -->
37
38
  <activity
38
39
  android:name=".MainActivity"
@@ -40,6 +41,7 @@
40
41
  android:exported="true"
41
42
  android:launchMode="singleTask"
42
43
  android:screenOrientation="${screenOrientation}"
44
+ android:theme="@style/Theme.AngularLynxShell.Starting"
43
45
  android:windowSoftInputMode="adjustResize">
44
46
  <intent-filter>
45
47
  <action android:name="android.intent.action.MAIN" />
@@ -43,7 +43,8 @@ class AssetsModule(context: Context, param: Any?) : LynxModule(context, param) {
43
43
  * The file on the dev server, in the debug build `ng serve --platform
44
44
  * android` runs, which has the current copy. The call is synchronous, so
45
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.
46
+ * network requests on the UI thread, where Lynx calls this under its
47
+ * default thread strategy (MainActivity runs it on Lynx's engine thread).
47
48
  */
48
49
  private fun readRemote(url: String): JavaOnlyArray? = try {
49
50
  val download = FutureTask {
@@ -2,6 +2,7 @@ package dev.angularlynx.shell
2
2
 
3
3
  import android.content.Context
4
4
  import android.graphics.SurfaceTexture
5
+ import android.os.Looper
5
6
  import android.view.TextureView
6
7
  import com.lynx.tasm.behavior.Behavior
7
8
  import com.lynx.tasm.behavior.LynxContext
@@ -19,7 +20,11 @@ import com.lynx.tasm.behavior.ui.LynxUI
19
20
  class CanvasUI(context: LynxContext) : LynxUI<TextureView>(context) {
20
21
  private var canvasId: String? = null
21
22
 
22
- /** The view's surface, while it has one. */
23
+ /**
24
+ * The view's surface, while it has one. Set on the UI thread, and read by
25
+ * the context on Lynx's engine thread too.
26
+ */
27
+ @Volatile
23
28
  var surface: SurfaceTexture? = null
24
29
  private set
25
30
 
@@ -49,9 +54,17 @@ class CanvasUI(context: LynxContext) : LynxUI<TextureView>(context) {
49
54
 
50
55
  private fun contextOrNull(): WebGLContext? = canvasId?.let { CanvasRegistry.context(it) }
51
56
 
52
- /** Whether the frames can be shown see-through, as the context's `alpha` asks. */
57
+ /**
58
+ * Whether the frames can be shown see-through, as the context's `alpha`
59
+ * asks. The context attaches from Lynx's engine thread when it's made
60
+ * after the view, and a view is the UI thread's to change.
61
+ */
53
62
  fun setOpaque(opaque: Boolean) {
54
- view.isOpaque = opaque
63
+ if (Looper.myLooper() == Looper.getMainLooper()) {
64
+ view.isOpaque = opaque
65
+ } else {
66
+ view.post { view.isOpaque = opaque }
67
+ }
55
68
  }
56
69
 
57
70
  @LynxProp(name = "canvas-id")
@@ -23,6 +23,7 @@ import androidx.activity.enableEdgeToEdge
23
23
  import androidx.browser.customtabs.CustomTabsIntent
24
24
  import androidx.core.graphics.Insets
25
25
  import androidx.core.os.ConfigurationCompat
26
+ import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
26
27
  import androidx.core.view.ViewCompat
27
28
  import androidx.core.view.WindowInsetsCompat
28
29
  import com.lynx.react.bridge.JavaOnlyArray
@@ -31,6 +32,7 @@ import com.lynx.tasm.LynxError
31
32
  import com.lynx.tasm.LynxView
32
33
  import com.lynx.tasm.LynxViewBuilder
33
34
  import com.lynx.tasm.LynxViewClient
35
+ import com.lynx.tasm.ThreadStrategyForRendering
34
36
  import com.lynx.xelement.XElementBehaviors
35
37
 
36
38
  /**
@@ -60,6 +62,13 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
60
62
  private var contrastListener: Any? = null
61
63
  private var highContrastTextListener: Any? = null
62
64
 
65
+ // Whether the splash screen stays up: until the runtime says the app's
66
+ // first screen is drawn (ShellModule.hideSplashScreen), or
67
+ // SPLASH_TIMEOUT_MS have passed, so a host the runtime can't reach, or a
68
+ // first screen that never settles, doesn't leave the app behind its logo.
69
+ private var keepSplashScreen = true
70
+ private val splashTimeout = Handler(Looper.getMainLooper())
71
+
63
72
  // Disabled until the Angular app enables it (see ShellModule), so by
64
73
  // default back leaves the app like any other root screen.
65
74
  private val backHandler = object : OnBackPressedCallback(false) {
@@ -95,10 +104,30 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
95
104
  }
96
105
 
97
106
  override fun onCreate(savedInstanceState: Bundle?) {
107
+ // The splash screen (themes.xml's Theme.AngularLynxShell.Starting),
108
+ // before anything else: it switches the activity to the app's own
109
+ // theme. Android takes a splash screen down at the app's first frame,
110
+ // which would be the empty LynxView: the bundle hasn't run yet, and
111
+ // the first screen may have work to finish first, such as a lazy
112
+ // route or a guard. So it stays up until the runtime says the screen
113
+ // is drawn, and then fades out.
114
+ val splashScreen = installSplashScreen()
98
115
  // Android 15+ always draws apps edge to edge; opting in on older
99
116
  // versions too keeps the layout the same everywhere.
100
117
  enableEdgeToEdge()
101
118
  super.onCreate(savedInstanceState)
119
+ // Checked before each frame while the splash screen is up. The
120
+ // development build's message, such as that the dev server can't be
121
+ // reached, shows at once.
122
+ splashScreen.setKeepOnScreenCondition { keepSplashScreen && !DevServer.isShowingMessage() }
123
+ splashScreen.setOnExitAnimationListener { splash ->
124
+ splash.view.animate()
125
+ .alpha(0f)
126
+ .setDuration(SPLASH_FADE_MS)
127
+ .withEndAction { splash.remove() }
128
+ .start()
129
+ }
130
+ splashTimeout.postDelayed({ hideSplashScreen() }, SPLASH_TIMEOUT_MS)
102
131
 
103
132
  // A shortcut that started the app waits for the runtime to take it.
104
133
  // Android hands a recreated activity the intent it started with
@@ -114,6 +143,18 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
114
143
  // --platform android` runs, the dev server's (DevServer.kt).
115
144
  val bundleUrl = DevServer.bundleUrl(this) ?: BundleAssets.MAIN_BUNDLE
116
145
  lynxView = LynxViewBuilder().apply {
146
+ // Lynx's engine thread, which runs the main thread's JavaScript
147
+ // (the whole Angular app), layout and Lynx's animator, gets a
148
+ // thread of its own. Lynx's default, ALL_ON_UI, runs it on the UI
149
+ // thread, where change detection, a screen being built or a long
150
+ // event handler took frames from what Android runs itself: a
151
+ // scroll view's fling, typing, a web view. Off it, the element
152
+ // tree reaches the screen a step later, once the flush crosses to
153
+ // the UI thread: the build plugin turns on Lynx's pending invokes
154
+ // so UI methods follow it, and the runtime sets enable-async-list
155
+ // on every <list>, which this strategy requires. The iOS shell
156
+ // does the same.
157
+ setThreadStrategyForRendering(ThreadStrategyForRendering.MOST_ON_TASM)
117
158
  setTemplateProvider(AssetTemplateProvider(this@MainActivity))
118
159
  setTemplateResourceFetcher(AssetTemplateResourceFetcher(this@MainActivity))
119
160
  setMediaResourceFetcher(AssetMediaResourceFetcher())
@@ -139,7 +180,8 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
139
180
  registerModule(ShortcutsModule.NAME, ShortcutsModule::class.java, null)
140
181
  // <canvas>'s WebGL (WebGLModule.kt), which the runtime calls from
141
182
  // the main thread, where Angular runs: main-thread modules let
142
- // it get its answers synchronously, with lynx.module(name).
183
+ // it get its answers synchronously, with lynx.module(name). Lynx
184
+ // calls them on its engine thread, not the UI thread.
143
185
  registerModule(WebGLModule.NAME, WebGLModule::class.java, null)
144
186
  // Bundled files for the main thread's fetch and Image (AssetsModule.kt).
145
187
  registerModule(AssetsModule.NAME, AssetsModule::class.java, null)
@@ -245,6 +287,14 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
245
287
  backHandler.isEnabled = enabled
246
288
  }
247
289
 
290
+ // The splash screen goes at the next frame (see onCreate). Once gone,
291
+ // nothing: the development build loads the app again on every edit, and
292
+ // each load asks.
293
+ override fun hideSplashScreen() {
294
+ keepSplashScreen = false
295
+ splashTimeout.removeCallbacksAndMessages(null)
296
+ }
297
+
248
298
  override fun startWebAuthSession(url: Uri, callbackScheme: String, done: (WebAuthModule.Result) -> Unit) {
249
299
  if (webAuthSession != null) {
250
300
  done(WebAuthModule.Result.Failed("A sign-in is already open."))
@@ -391,11 +441,17 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
391
441
  getSystemService(AccessibilityManager::class.java).removeHighContrastTextStateChangeListener(it)
392
442
  }
393
443
  }
444
+ splashTimeout.removeCallbacksAndMessages(null)
394
445
  lynxView.destroy()
395
446
  super.onDestroy()
396
447
  }
397
448
 
398
449
  private companion object {
399
450
  const val TAG = "AngularLynxShell"
451
+
452
+ // The longest the splash screen waits for the app (see onCreate),
453
+ // and its fade, as long as the iOS shell's.
454
+ const val SPLASH_TIMEOUT_MS = 5_000L
455
+ const val SPLASH_FADE_MS = 250L
400
456
  }
401
457
  }
@@ -29,6 +29,10 @@ import com.lynx.tasm.LynxEnv
29
29
  * pressure, so this reports a moderate one. The runtime asks once it has
30
30
  * released about a screen's worth of elements and the app has settled
31
31
  * (`collect-garbage.ts` in `packages/runtime`).
32
+ *
33
+ * `hideSplashScreen` lets the splash screen go, which MainActivity keeps up
34
+ * until the app's first screen is ready. The runtime's LynxSplashScreen
35
+ * calls it.
32
36
  */
33
37
  class ShellModule(context: Context, param: Any?) : LynxModule(context, param) {
34
38
  private val host = param as Host
@@ -36,6 +40,7 @@ class ShellModule(context: Context, param: Any?) : LynxModule(context, param) {
36
40
 
37
41
  interface Host {
38
42
  fun setBackHandlerEnabled(enabled: Boolean)
43
+ fun hideSplashScreen()
39
44
  }
40
45
 
41
46
  @LynxMethod
@@ -43,6 +48,11 @@ class ShellModule(context: Context, param: Any?) : LynxModule(context, param) {
43
48
  main.post { host.setBackHandlerEnabled(enabled) }
44
49
  }
45
50
 
51
+ @LynxMethod
52
+ fun hideSplashScreen() {
53
+ main.post { host.hideSplashScreen() }
54
+ }
55
+
46
56
  @LynxMethod
47
57
  fun collectGarbage() {
48
58
  main.post { LynxEnv.inst().trimMemory(MEMORY_PRESSURE_MODERATE) }
@@ -33,8 +33,13 @@ private const val EGL_OPENGL_ES3_BIT = 0x40
33
33
  * default framebuffer the size of the canvas's `width` and `height`, which
34
34
  * each finished frame is copied from into the canvas's TextureView.
35
35
  *
36
- * The runtime's `run` calls arrive on the UI thread, which makes the context
37
- * current for each and puts back whatever was current before.
36
+ * The runtime's `run` calls arrive on Lynx's engine thread, which the shell
37
+ * runs off the UI thread (MainActivity's thread strategy), while the canvas's
38
+ * TextureView reports its surface on the UI thread. Each call makes the
39
+ * context current for itself and puts back whatever was current before, so
40
+ * either thread can make the next one; the context's lock keeps them from
41
+ * making two at once. The UI thread waits for a batch only when the surface
42
+ * comes, goes or resizes.
38
43
  */
39
44
  class WebGLContext(val canvasId: String, attributes: ReadableMap?) {
40
45
  private val display: EGLDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
@@ -125,6 +130,7 @@ class WebGLContext(val canvasId: String, attributes: ReadableMap?) {
125
130
  }
126
131
  }
127
132
 
133
+ @Synchronized
128
134
  fun destroy() {
129
135
  if (destroyed) return
130
136
  withCurrent {
@@ -167,6 +173,7 @@ class WebGLContext(val canvasId: String, attributes: ReadableMap?) {
167
173
 
168
174
  // --- The view ------------------------------------------------------------
169
175
 
176
+ @Synchronized
170
177
  fun attachView(canvas: CanvasUI?) {
171
178
  if (view === canvas) return
172
179
  view = canvas
@@ -175,6 +182,7 @@ class WebGLContext(val canvasId: String, attributes: ReadableMap?) {
175
182
  }
176
183
 
177
184
  /** The view's surface came, went or changed size. */
185
+ @Synchronized
178
186
  fun surfaceChanged() {
179
187
  if (destroyed) return
180
188
  val texture = view?.surface
@@ -187,8 +195,9 @@ class WebGLContext(val canvasId: String, attributes: ReadableMap?) {
187
195
  } else {
188
196
  windowTexture = texture
189
197
  withCurrent {
190
- // Presenting never waits for the display: it runs on
191
- // the UI thread.
198
+ // Presenting never waits for the display: the frame
199
+ // is copied once into the TextureView, which the UI
200
+ // thread composites at its own pace.
192
201
  EGL14.eglSwapInterval(display, 0)
193
202
  }
194
203
  }
@@ -332,6 +341,7 @@ class WebGLContext(val canvasId: String, attributes: ReadableMap?) {
332
341
  * app has drawn since the last frame was shown, or, once a frame has been
333
342
  * shown without preserveDrawingBuffer, the cleared buffer.
334
343
  */
344
+ @Synchronized
335
345
  fun readDrawingBuffer(): DrawingBufferPixels? {
336
346
  if (destroyed) return null
337
347
  val pixels = ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.nativeOrder())
@@ -640,6 +650,7 @@ class WebGLContext(val canvasId: String, attributes: ReadableMap?) {
640
650
  fun skip() { index++ }
641
651
  }
642
652
 
653
+ @Synchronized
643
654
  fun run(commands: ReadableArray): JavaOnlyArray {
644
655
  val results = JavaOnlyArray()
645
656
  if (destroyed) return results
@@ -28,7 +28,8 @@ import kotlin.math.roundToInt
28
28
  * only come from a main-thread module: MainActivity turns those on
29
29
  * (`setEnableMTSModule`). The runtime batches the calls into one `run` per
30
30
  * frame; see packages/runtime/src/lib/canvas/webgl-bridge.ts for the
31
- * protocol. Lynx calls these methods on the UI thread, where GL runs.
31
+ * protocol. Lynx calls these methods on its engine thread, where the main
32
+ * thread's JavaScript runs, which the shell runs off the UI thread.
32
33
  */
33
34
  class WebGLModule(context: Context, param: Any?) : LynxModule(context, param) {
34
35
  private val contexts = HashMap<Int, WebGLContext>()
@@ -232,18 +233,25 @@ internal object DecodedImages {
232
233
  /**
233
234
  * Pairs canvases with contexts by canvas id: either can come first, as the
234
235
  * runtime may make the context before Lynx has made the element's view.
236
+ *
237
+ * Views come and go on the UI thread, contexts on Lynx's engine thread, so
238
+ * it's locked. It takes a context's lock inside its own, and a context never
239
+ * calls it, so the two can't wait on each other.
235
240
  */
236
241
  internal object CanvasRegistry {
237
242
  private val views = HashMap<String, WeakReference<CanvasUI>>()
238
243
  private val contexts = HashMap<String, WeakReference<WebGLContext>>()
239
244
 
245
+ @Synchronized
240
246
  fun setView(canvasId: String, view: CanvasUI?) {
241
247
  if (view == null) views.remove(canvasId) else views[canvasId] = WeakReference(view)
242
248
  contexts[canvasId]?.get()?.attachView(view)
243
249
  }
244
250
 
251
+ @Synchronized
245
252
  fun view(canvasId: String): CanvasUI? = views[canvasId]?.get()
246
253
 
254
+ @Synchronized
247
255
  fun setContext(canvasId: String, context: WebGLContext?) {
248
256
  if (context == null) {
249
257
  contexts.remove(canvasId)
@@ -253,6 +261,7 @@ internal object CanvasRegistry {
253
261
  }
254
262
  }
255
263
 
264
+ @Synchronized
256
265
  fun context(canvasId: String): WebGLContext? = contexts[canvasId]?.get()
257
266
  }
258
267
 
@@ -1,8 +1,9 @@
1
1
  <?xml version="1.0" encoding="utf-8"?>
2
2
  <resources>
3
3
  <!--
4
- The window background, which shows before the first Lynx frame and
5
- behind the system bars. MainActivity sets it again when dark mode
4
+ The window background, which shows behind the splash screen's image
5
+ and the system bars, and behind the page: angular.json's
6
+ splash.backgroundColor. MainActivity sets it again when dark mode
6
7
  switches while the app is open, from values-night's.
7
8
  -->
8
9
  <color name="window_background">#FFFFFFFF</color>