@blotch/angular-lynx-native 22.2.24 → 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 (53) hide show
  1. package/README.md +6 -4
  2. package/dist/android/project.d.ts +27 -3
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +83 -2
  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 +20 -3
  11. package/dist/ios/project.d.ts.map +1 -1
  12. package/dist/ios/project.js +99 -2
  13. package/dist/options.d.ts +119 -0
  14. package/dist/options.d.ts.map +1 -1
  15. package/dist/options.js +143 -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 +19 -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 +27 -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 +81 -4
  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/ShortcutActivity.kt +33 -0
  32. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShortcutsModule.kt +72 -0
  33. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +15 -4
  34. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +10 -1
  35. package/templates/android/app/src/main/res/values/colors.xml +3 -2
  36. package/templates/android/app/src/main/res/values/splash.xml +9 -0
  37. package/templates/android/app/src/main/res/values/themes.xml +14 -0
  38. package/templates/android/app/src/main/res/xml/shortcuts.xml +7 -0
  39. package/templates/android/app/src/release/java/dev/angularlynx/shell/DevServer.kt +2 -0
  40. package/templates/ios/App/AngularLynxWebGL.h +34 -6
  41. package/templates/ios/App/AngularLynxWebGL.m +58 -23
  42. package/templates/ios/App/AngularLynxWebGLContext.m +25 -21
  43. package/templates/ios/App/AnimationFrameRate.swift +214 -0
  44. package/templates/ios/App/AppDelegate.swift +2 -0
  45. package/templates/ios/App/AssetsModule.swift +3 -1
  46. package/templates/ios/App/DevServer.swift +3 -0
  47. package/templates/ios/App/Info.plist +12 -5
  48. package/templates/ios/App/LynxViewController.swift +24 -1
  49. package/templates/ios/App/ShellModule.swift +14 -1
  50. package/templates/ios/App/ShortcutsModule.swift +82 -0
  51. package/templates/ios/App/SplashScreen.swift +71 -0
  52. package/templates/ios/App/WebViewLoader.swift +95 -0
  53. package/templates/ios/App/XElementRegistry.swift +5 -1
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.24",
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": {
@@ -12,6 +12,8 @@ The app is one activity holding one full-screen `LynxView` that runs `main.lynx.
12
12
  | App identity | `angular-lynx.properties` | Keys: `applicationId`, `versionName`, `versionCode`, `appName`, `screenOrientation` (`portrait`, `sensorLandscape` or `unspecified`). Read by `app/build.gradle.kts`. The committed file holds defaults. |
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
+ | 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. |
15
17
  | SDK location | `local.properties` | `sdk.dir=…`, unless `ANDROID_HOME` is set. |
16
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). |
17
19
 
@@ -34,6 +36,12 @@ Build commands and outputs (no flavors, so the names are fixed):
34
36
 
35
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.
36
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
+
37
45
  ## Memory
38
46
 
39
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.
@@ -52,6 +60,16 @@ PrimJS, which runs the app's JavaScript on Lynx's main thread, collects garbage
52
60
 
53
61
  iOS's `LinkingModule.swift` does the same with `UIApplication.open`, `SFSafariViewController` and `UIApplication.canOpenURL`, which answers only for the schemes in Info.plist's `LSApplicationQueriesSchemes`.
54
62
 
63
+ ## Shortcuts
64
+
65
+ angular.json's `shortcuts` are the app's static shortcuts, in the menu a long press on its icon opens: the manifest's `android.app.shortcuts` meta-data on `MainActivity` points at `res/xml/shortcuts.xml`, which the generator writes. Static ones are there from the moment the app is installed. Each takes the app's icon, since the launcher draws an empty circle for a shortcut without one.
66
+
67
+ - **A shortcut points at `ShortcutActivity`, not `MainActivity`.** Android starts a static shortcut's activity with `FLAG_ACTIVITY_NEW_TASK` and `FLAG_ACTIVITY_CLEAR_TASK`, which an app can't change, so pointing at `MainActivity` would end the open one, and the running Angular app with it. `ShortcutActivity` has a task of its own to clear (`taskAffinity=""`, out of Recents, `Theme.NoDisplay`), starts `MainActivity` the ordinary way with the shortcut's extras, and finishes. The open `MainActivity` gets them in `onNewIntent`. It isn't exported: the launcher starts a shortcut as the app itself.
68
+ - **`NativeModules.AngularLynxShortcuts.take(callback)`** (`ShortcutsModule.kt`, behind the runtime's `LynxShortcuts`) calls back with `{ shortcuts }`: each one that ran since the last call, as `{ id, route? }`. `MainActivity` leaves a shortcut with the module and, when the app is open, sends the `angularLynxShortcut` global event, which the runtime answers by taking them. It also takes them once as it starts, which is how the shortcut that started the app arrives.
69
+ - **A recreated activity doesn't run its shortcut again.** Android hands an activity the intent it started with when it recreates it, and when the app is reopened from Recents, so `onCreate` only takes the shortcut from a first start that didn't come from history.
70
+
71
+ iOS's shell does the same with App Intents: the generator writes `App/AppShortcuts.swift`, whose intents open the app and leave their shortcut with `ShortcutsModule.swift`'s `ShortcutCenter`.
72
+
55
73
  ## Storage
56
74
 
57
75
  `NativeModules.AngularLynxLocalStorage` and `NativeModules.AngularLynxSecureStorage` (`LocalStorageModule.kt` and `SecureStorageModule.kt`, behind the runtime's `LynxLocalStorage` and `LynxSecureStorage`) keep string values, which the runtime stores as JSON, each in a `SharedPreferences` file of its own. Each method calls back once with `{ value }`, `{}` or `{ error }`.
@@ -77,7 +95,7 @@ The module reads the picked photo on a background thread and calls back once wit
77
95
 
78
96
  ## Canvas and WebGL
79
97
 
80
- `<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.
81
99
 
82
100
  Android's GLES has no 2D uploads from a `PIXEL_UNPACK_BUFFER` and no `glGetVertexAttribPointerv`, so those log a warning and answer 0.
83
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,14 +41,39 @@
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" />
46
48
  <category android:name="android.intent.category.LAUNCHER" />
47
49
  </intent-filter>
48
50
  <!-- angular-lynx:deep-links -->
51
+ <!--
52
+ angular.json's shortcuts, in the menu a long press on the
53
+ app's icon opens. Android reads them from the launcher
54
+ activity.
55
+ -->
56
+ <meta-data
57
+ android:name="android.app.shortcuts"
58
+ android:resource="@xml/shortcuts" />
49
59
  </activity>
50
60
 
61
+ <!--
62
+ Where the shortcuts point: it hands the shortcut to MainActivity
63
+ and finishes without drawing (ShortcutActivity.kt). Android starts
64
+ a shortcut's activity in a cleared task, so it gets one of its own
65
+ to clear (no taskAffinity, and not in Recents), which leaves the
66
+ open app as it is. Not exported: the launcher starts a shortcut as
67
+ the app itself.
68
+ -->
69
+ <activity
70
+ android:name=".ShortcutActivity"
71
+ android:excludeFromRecents="true"
72
+ android:exported="false"
73
+ android:noHistory="true"
74
+ android:taskAffinity=""
75
+ android:theme="@android:style/Theme.NoDisplay" />
76
+
51
77
  <!--
52
78
  The files LynxShare shares (ShareModule), which the app picked in
53
79
  the share sheet reads through content:// URIs of this provider.
@@ -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,15 +104,57 @@ 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)
131
+
132
+ // A shortcut that started the app waits for the runtime to take it.
133
+ // Android hands a recreated activity the intent it started with
134
+ // again, and so does reopening the app from Recents, neither of
135
+ // which is the person running the shortcut again.
136
+ if (savedInstanceState == null &&
137
+ intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY == 0
138
+ ) {
139
+ ShortcutsModule.run(intent)
140
+ }
102
141
 
103
142
  // The bundle in the app's assets, or in the debug build `ng serve
104
143
  // --platform android` runs, the dev server's (DevServer.kt).
105
144
  val bundleUrl = DevServer.bundleUrl(this) ?: BundleAssets.MAIN_BUNDLE
106
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)
107
158
  setTemplateProvider(AssetTemplateProvider(this@MainActivity))
108
159
  setTemplateResourceFetcher(AssetTemplateResourceFetcher(this@MainActivity))
109
160
  setMediaResourceFetcher(AssetMediaResourceFetcher())
@@ -124,9 +175,13 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
124
175
  // The share sheet behind LynxShare (ShareModule.kt), which it opens
125
176
  // from this activity.
126
177
  registerModule(ShareModule.NAME, ShareModule::class.java, this@MainActivity)
178
+ // The shortcuts the person runs from the app icon's menu, which
179
+ // LynxShortcuts takes (ShortcutsModule.kt).
180
+ registerModule(ShortcutsModule.NAME, ShortcutsModule::class.java, null)
127
181
  // <canvas>'s WebGL (WebGLModule.kt), which the runtime calls from
128
182
  // the main thread, where Angular runs: main-thread modules let
129
- // 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.
130
185
  registerModule(WebGLModule.NAME, WebGLModule::class.java, null)
131
186
  // Bundled files for the main thread's fetch and Image (AssetsModule.kt).
132
187
  registerModule(AssetsModule.NAME, AssetsModule::class.java, null)
@@ -232,6 +287,14 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
232
287
  backHandler.isEnabled = enabled
233
288
  }
234
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
+
235
298
  override fun startWebAuthSession(url: Uri, callbackScheme: String, done: (WebAuthModule.Result) -> Unit) {
236
299
  if (webAuthSession != null) {
237
300
  done(WebAuthModule.Result.Failed("A sign-in is already open."))
@@ -247,11 +310,19 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
247
310
  }
248
311
  }
249
312
 
250
- // The page's redirect to the callback scheme. The activity is singleTask,
251
- // so the deep link comes back to this one, which closes the Custom Tab
252
- // above it. It arrives before onResume, which then finds no session open.
313
+ // The activity is singleTask, so an intent for it while it's open comes
314
+ // here rather than starting another.
253
315
  override fun onNewIntent(intent: Intent) {
254
316
  super.onNewIntent(intent)
317
+ // A shortcut run while the app is open (ShortcutActivity): the
318
+ // runtime takes it when it hears the event.
319
+ if (ShortcutsModule.run(intent)) {
320
+ lynxView.sendGlobalEvent(ShortcutsModule.EVENT, JavaOnlyArray())
321
+ return
322
+ }
323
+ // The sign-in page's redirect to the callback scheme: the deep link
324
+ // comes back to this activity, which closes the Custom Tab above it.
325
+ // It arrives before onResume, which then finds no session open.
255
326
  val url = intent.data ?: return
256
327
  val session = webAuthSession ?: return
257
328
  if (url.scheme?.lowercase() != session.scheme) return
@@ -370,11 +441,17 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
370
441
  getSystemService(AccessibilityManager::class.java).removeHighContrastTextStateChangeListener(it)
371
442
  }
372
443
  }
444
+ splashTimeout.removeCallbacksAndMessages(null)
373
445
  lynxView.destroy()
374
446
  super.onDestroy()
375
447
  }
376
448
 
377
449
  private companion object {
378
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
379
456
  }
380
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) }
@@ -0,0 +1,33 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.Activity
4
+ import android.content.Intent
5
+ import android.os.Bundle
6
+
7
+ /**
8
+ * Where the app's shortcuts point (`res/xml/shortcuts.xml`): it passes the
9
+ * shortcut on to MainActivity and is gone before it draws anything.
10
+ *
11
+ * A shortcut can't point at MainActivity itself. Android starts a static
12
+ * shortcut's activity with FLAG_ACTIVITY_CLEAR_TASK, which can't be changed,
13
+ * so it would end the open MainActivity, and the running Angular app with
14
+ * it, before starting a new one: every shortcut would restart the app. This
15
+ * activity has a task of its own for Android to clear (`taskAffinity=""` in
16
+ * the manifest), and starts MainActivity the ordinary way, which brings the
17
+ * open one to the front and hands it the shortcut in onNewIntent. It's the
18
+ * trampoline Android's shortcut guide describes.
19
+ */
20
+ class ShortcutActivity : Activity() {
21
+ override fun onCreate(savedInstanceState: Bundle?) {
22
+ super.onCreate(savedInstanceState)
23
+ startActivity(
24
+ Intent(this, MainActivity::class.java).apply {
25
+ intent.extras?.let { putExtras(it) }
26
+ // MainActivity lives in another task than this one.
27
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
28
+ },
29
+ )
30
+ // Theme.NoDisplay needs the activity finished before it would resume.
31
+ finish()
32
+ }
33
+ }