@blotch/angular-lynx-native 22.2.25 → 22.2.27

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 (62) hide show
  1. package/README.md +15 -11
  2. package/dist/android/project.d.ts +13 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +40 -11
  5. package/dist/app-links.d.ts +53 -0
  6. package/dist/app-links.d.ts.map +1 -0
  7. package/dist/app-links.js +115 -0
  8. package/dist/generate.d.ts +1 -1
  9. package/dist/generate.js +8 -2
  10. package/dist/index.d.ts +3 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +23 -0
  13. package/dist/ios/build.d.ts.map +1 -1
  14. package/dist/ios/build.js +5 -0
  15. package/dist/ios/project.d.ts +16 -2
  16. package/dist/ios/project.d.ts.map +1 -1
  17. package/dist/ios/project.js +57 -6
  18. package/dist/options.d.ts +68 -1
  19. package/dist/options.d.ts.map +1 -1
  20. package/dist/options.js +70 -0
  21. package/dist/permissions.d.ts.map +1 -1
  22. package/dist/permissions.js +7 -0
  23. package/dist/png.d.ts +5 -0
  24. package/dist/png.d.ts.map +1 -1
  25. package/dist/png.js +19 -5
  26. package/dist/splash.d.ts +70 -0
  27. package/dist/splash.d.ts.map +1 -0
  28. package/dist/splash.js +239 -0
  29. package/package.json +1 -1
  30. package/templates/android/README.md +11 -2
  31. package/templates/android/app/build.gradle.kts +19 -9
  32. package/templates/android/app/proguard-rules.pro +67 -55
  33. package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServer.kt +6 -0
  34. package/templates/android/app/src/main/AndroidManifest.xml +3 -1
  35. package/templates/android/app/src/main/java/dev/angularlynx/shell/AssetsModule.kt +2 -1
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +16 -3
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/LinkingModule.kt +42 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +96 -7
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +15 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +24 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +15 -4
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +10 -1
  43. package/templates/android/app/src/main/res/values/colors.xml +3 -2
  44. package/templates/android/app/src/main/res/values/splash.xml +9 -0
  45. package/templates/android/app/src/main/res/values/themes.xml +14 -0
  46. package/templates/android/app/src/release/java/dev/angularlynx/shell/DevServer.kt +2 -0
  47. package/templates/android/build.gradle.kts +1 -1
  48. package/templates/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  49. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  50. package/templates/android/gradlew.bat +41 -11
  51. package/templates/ios/App/AngularLynxWebGL.h +34 -6
  52. package/templates/ios/App/AngularLynxWebGL.m +58 -23
  53. package/templates/ios/App/AngularLynxWebGLContext.m +104 -26
  54. package/templates/ios/App/AnimationFrameRate.swift +214 -0
  55. package/templates/ios/App/AppDelegate.swift +48 -0
  56. package/templates/ios/App/AssetsModule.swift +3 -1
  57. package/templates/ios/App/DevServer.swift +3 -0
  58. package/templates/ios/App/Info.plist +12 -5
  59. package/templates/ios/App/LinkingModule.swift +62 -1
  60. package/templates/ios/App/LynxViewController.swift +30 -6
  61. package/templates/ios/App/ShellModule.swift +40 -1
  62. 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.27",
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
 
@@ -24,6 +25,8 @@ Build commands and outputs (no flavors, so the names are fixed):
24
25
  # app/build/outputs/bundle/release/app-release.aab
25
26
  ```
26
27
 
28
+ The release build runs R8 and the resource shrinker (`isMinifyEnabled`, `isShrinkResources`), and writes the mapping that turns the renamed classes back to `app/build/outputs/mapping/release/mapping.txt`, which also goes in the `.aab` for Google Play. Lynx's AAR ships keep rules for its own classes; `app/proguard-rules.pro` adds the ones they miss, each with what broke without it (the app aborting on launch, for one). Any class Lynx or the shell reaches only by name needs a rule there. How they were found, and the sizes, are in `investigations/native-app-builds.md` ("R8 in the Android release build").
29
+
27
30
  ## How the shell loads the app
28
31
 
29
32
  - **Bundles** come from `assets/` (`ResourceFetchers.kt`, `BundleAssets.kt`). A URL without a scheme (`/static/…`, `static/…`), `asset:///…` and `file:///android_asset/…` all mean "the file at that path in `assets/`", so the bundle works with Rspeedy's default asset prefix (`/`) and doesn't need a platform-specific one. Absolute `http(s)` URLs are fetched with OkHttp.
@@ -35,6 +38,12 @@ Build commands and outputs (no flavors, so the names are fixed):
35
38
 
36
39
  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
40
 
41
+ ## Splash screen
42
+
43
+ `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.
44
+
45
+ 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.
46
+
38
47
  ## Memory
39
48
 
40
49
  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.
@@ -45,7 +54,7 @@ PrimJS, which runs the app's JavaScript on Lynx's main thread, collects garbage
45
54
 
46
55
  ## Links
47
56
 
48
- `NativeModules.AngularLynxLinking` (`LinkingModule.kt`, behind the runtime's `LynxLinking`) opens links outside the app. `MainActivity` registers it with itself as the param, since the module starts activities from it and watches its lifecycle.
57
+ `NativeModules.AngularLynxLinking` (`LinkingModule.kt`, behind the runtime's `LynxLinking`) opens links outside the app. `MainActivity` registers it with itself as the param, since the module starts activities from it and watches its lifecycle. Its `takeURLs(callback)` calls back with `{ urls }`, the links with one of angular.json's `deepLinkSchemes`, and the App Links to its `appLinkDomains`, that arrived while the app was open: `MainActivity.onNewIntent` keeps each one with the module and sends the `angularLynxURL` global event, which the runtime answers by taking them. The link that started the app goes in the `initialURL` global prop instead, read from the intent in `onCreate` unless the app was reopened from Recents.
49
58
 
50
59
  - **`openURL(url, callback)`** starts an `ACTION_VIEW` intent, which the browser, the mail app or the app that claims the URL opens, and calls back with `{}`, or with `{ error, message }` when nothing does.
51
60
  - **`openInApp(url, options, callback)`** opens an http(s) URL in a Custom Tab, with `options.toolbarColor` as its toolbar color. Android says nothing when a Custom Tab closes, so the module watches the activity's lifecycle and calls back when it resumes after pausing for the tab: the person closed the tab or came back to the app another way. It doesn't touch `WebAuthModule`'s session, which `MainActivity` tracks on its own.
@@ -88,7 +97,7 @@ The module reads the picked photo on a background thread and calls back once wit
88
97
 
89
98
  ## Canvas and WebGL
90
99
 
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.
100
+ `<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
101
 
93
102
  Android's GLES has no 2D uploads from a `PIXEL_UNPACK_BUFFER` and no `glGetVertexAttribPointerv`, so those log a warning and answer 0.
94
103
 
@@ -28,7 +28,7 @@ val hasReleaseSigning = releaseSigning.values.all { !it.isNullOrEmpty() }
28
28
 
29
29
  // One place for the Lynx version, so a Lynx upgrade is a one-line change.
30
30
  val lynxVersion = "4.1.0"
31
- val primjsVersion = "4.1.1"
31
+ val primjsVersion = "4.2.1"
32
32
  // Lynx's image service is written against Fresco 2.3, and Lynx Explorer ships
33
33
  // the same version, so stay on it until Lynx moves.
34
34
  val frescoVersion = "2.3.0"
@@ -72,11 +72,17 @@ android {
72
72
 
73
73
  buildTypes {
74
74
  release {
75
- // R8 shrinking is off until the Lynx keep rules in
76
- // proguard-rules.pro are verified against every AngularLynx
77
- // feature; Lynx reaches much of its Java code through JNI and
78
- // reflection, which R8 can't see.
79
- isMinifyEnabled = false
75
+ // R8 shrinks, optimizes and renames the app's Java and Kotlin,
76
+ // and the resource shrinker drops the resources nothing uses.
77
+ // Most of the code is libraries the app uses a little of (media3
78
+ // and Guava behind <video>, appcompat and material behind
79
+ // XElement): R8 takes the dex from 19.5 MB to 3.3 MB, and what an
80
+ // arm64 phone downloads from 13.6 MB to 7.5 MB. Lynx reaches much
81
+ // of its Java through JNI and reflection, which R8 can't see:
82
+ // Lynx's AAR ships keep rules for its own classes, and
83
+ // proguard-rules.pro adds the ones they miss.
84
+ isMinifyEnabled = true
85
+ isShrinkResources = true
80
86
  proguardFiles(
81
87
  getDefaultProguardFile("proguard-android-optimize.txt"),
82
88
  "proguard-rules.pro",
@@ -120,8 +126,12 @@ android {
120
126
  }
121
127
 
122
128
  dependencies {
123
- implementation("androidx.activity:activity-ktx:1.10.1")
129
+ implementation("androidx.activity:activity-ktx:1.13.0")
124
130
  implementation("androidx.core:core-ktx:1.16.0")
131
+ // The splash screen (MainActivity, themes.xml): Android 12's on every
132
+ // version the app runs on, and kept up until the app's first screen is
133
+ // ready.
134
+ implementation("androidx.core:core-splashscreen:1.2.0")
125
135
  // Custom Tabs, which WebAuthModule opens sign-in pages in, and
126
136
  // LinkingModule the pages of openInApp().
127
137
  implementation("androidx.browser:browser:1.8.0")
@@ -148,7 +158,7 @@ dependencies {
148
158
  implementation("com.facebook.fresco:animated-webp:$frescoVersion")
149
159
  implementation("com.facebook.fresco:webpsupport:$frescoVersion")
150
160
  implementation("com.facebook.fresco:animated-base:$frescoVersion")
151
- implementation("com.squareup.okhttp3:okhttp:4.12.0")
161
+ implementation("com.squareup.okhttp3:okhttp:4.12.1")
152
162
 
153
163
  // XElement: <input>, <textarea>, <overlay>, <svg>, <blur-view>,
154
164
  // <viewpager>, <refresh>, the <scroll-coordinator> family, <webview> and
@@ -168,6 +178,6 @@ dependencies {
168
178
  // vectordrawable 1.0.0 and vectordrawable-animated 1.0.0. Those two share
169
179
  // the namespace androidx.vectordrawable, and AGP 9's manifest merger
170
180
  // fails the build on that; newer versions give them distinct namespaces.
171
- implementation("androidx.appcompat:appcompat:1.7.1")
181
+ implementation("androidx.appcompat:appcompat:1.8.0")
172
182
  implementation("com.google.android.material:material:1.12.0")
173
183
  }
@@ -1,65 +1,77 @@
1
- # Lynx's keep rules, from Lynx's integration guide
2
- # (https://lynxjs.org/guide/start/integrate-with-existing-apps). Only used once
3
- # isMinifyEnabled is turned on in build.gradle.kts.
4
- # LYNX START
5
- # use @Keep to annotate retained classes.
6
- -dontwarn android.support.annotation.Keep
7
- -keep @android.support.annotation.Keep class **
8
- -keep @android.support.annotation.Keep class ** {
9
- @android.support.annotation.Keep <fields>;
10
- @android.support.annotation.Keep <methods>;
11
- }
12
- -dontwarn androidx.annotation.Keep
13
- -keep @androidx.annotation.Keep class **
14
- -keep @androidx.annotation.Keep class ** {
15
- @androidx.annotation.Keep <fields>;
16
- @androidx.annotation.Keep <methods>;
17
- }
18
- # native method call
19
- -keepclasseswithmembers,includedescriptorclasses class * {
20
- native <methods>;
21
- }
1
+ # The release build's keep rules, on top of the ones its libraries ship.
2
+ #
3
+ # R8 (isMinifyEnabled in build.gradle.kts) removes and renames whatever it
4
+ # can't see used. Lynx reaches much of its Java through JNI and reflection,
5
+ # which R8 can't see, so Lynx's AAR carries keep rules of its own (its
6
+ # proguard.txt, which R8 applies by itself): @Keep classes, native and
7
+ # @CalledByNative methods, @LynxMethod modules, @LynxProp and @LynxUIMethod
8
+ # members, and every LynxBaseUI, ShadowNode and LynxModule subclass. They're
9
+ # the rules from Lynx's integration guide, plus a few. Fresco's core library,
10
+ # XElement's modules and the AndroidX libraries ship theirs too.
11
+ #
12
+ # The rules below cover what those miss. They were found by listing every
13
+ # reflective call and every method native code calls in the Lynx, XElement and
14
+ # Fresco classes, checking the release APK's dex for each, and running the E2E
15
+ # tests and a page that drives every XElement on an emulator.
16
+ # investigations/native-app-builds.md has the details.
17
+ #
18
+ # Methods Lynx's native code calls. Lynx's rules keep the ones marked with
19
+ # com.lynx.tasm.base.CalledByNative, but lynx-base and lynx-trace, which ship
20
+ # no rules, mark theirs with annotations of their own. Without these, R8
21
+ # removed LynxLog.log(), which lynx-base's native library looks up as Lynx
22
+ # starts, and the app aborted on launch ("JNI DETECTED ERROR IN APPLICATION:
23
+ # mid == null" from LynxBaseTrace.nativeInitBaseTrace).
22
24
  -keepclasseswithmembers class * {
23
- @com.lynx.tasm.base.CalledByNative <methods>;
25
+ @com.lynx.base.CalledByNative <methods>;
24
26
  }
25
-
26
- # to customize a module, you need to keep the class name and the method annotated as LynxMethod.
27
27
  -keepclasseswithmembers class * {
28
- @com.lynx.jsbridge.LynxMethod <methods>;
28
+ @com.lynx.trace.CalledByNative <methods>;
29
29
  }
30
30
 
31
- -keepclassmembers class * {
32
- @com.lynx.tasm.behavior.LynxProp <methods>;
33
- @com.lynx.tasm.behavior.LynxPropGroup <methods>;
34
- @com.lynx.tasm.behavior.LynxUIMethod <methods>;
35
- }
31
+ # Most of the rest come from R8's full mode, AGP's default since AGP 8: a
32
+ # -keep rule that names a class without members keeps the class but not its
33
+ # constructor. The libraries' rules were written for ProGuard, which kept it,
34
+ # so a class they create with Class.newInstance() lost its constructor, and
35
+ # with it the methods only an instance could call.
36
36
 
37
- -keepclassmembers class com.lynx.tasm.behavior.ui.UIGroup {
38
- public boolean needCustomLayout();
39
- }
37
+ # Lynx's generated setters and method invokers. Lynx finds the ones for each
38
+ # element class by name (<class>$$PropsSetter, <class>$$MethodInvoker) and
39
+ # creates them with newInstance(). Without these rules R8 emptied them (none
40
+ # had a constructor left), and Lynx then set every property and called every
41
+ # UI method through reflection instead.
42
+ -keep class * implements com.lynx.tasm.behavior.utils.Settable { <init>(); }
43
+ -keep class * implements com.lynx.tasm.behavior.utils.LynxUIMethodInvoker { <init>(); }
44
+ # The same for a JSI object's descriptor (<class>$$Descriptor).
45
+ -keep class * implements com.lynx.jsbridge.jsi.ILynxJSIObjectDescriptor { <init>(); }
40
46
 
41
- # in case R8 compiler may remove mLoader in bytecode.
42
- # as mLoader is not used in java and passed as a WeakRef in JNI.
43
- -keepclassmembers class com.lynx.tasm.LynxTemplateRender {
44
- private com.lynx.tasm.core.resource.LynxResourceLoader mLoader;
45
- private com.lynx.tasm.core.resource.LynxResourceLoader mResourceLoader;
46
- }
47
+ # Fresco creates its WebP transcoder by name, and R8 had removed its
48
+ # constructor and methods.
49
+ -keep class com.facebook.imagepipeline.nativecode.WebpTranscoderImpl { <init>(); }
47
50
 
48
- # the automatically generated setter classes use the class names of LynxBaseUI and ShadowNode and their subclasses.
49
- -keep class com.lynx.tasm.behavior.ui.LynxBaseUI
50
- -keep class com.lynx.tasm.behavior.shadow.ShadowNode
51
- -keep class com.lynx.jsbridge.LynxModule { *; }
52
- -keep class * extends com.lynx.tasm.behavior.ui.LynxBaseUI
53
- -keep class * extends com.lynx.tasm.behavior.shadow.ShadowNode
54
- -keep class * extends com.lynx.jsbridge.LynxModule { *; }
55
- -keep class * extends com.lynx.jsbridge.LynxContextModule
56
- -keep class * implements com.lynx.tasm.behavior.utils.Settable
57
- -keep class * implements com.lynx.tasm.behavior.utils.LynxUISetter
58
- -keep class * implements com.lynx.tasm.behavior.utils.LynxUIMethodInvoker
59
- -keep class com.lynx.tasm.rendernode.compat.**{
60
- *;
51
+ # <viewpager> reads ViewPager's private mIsUnableToDrag by name, which
52
+ # XElement's own rules (they keep only populate()) leave R8 to rename.
53
+ -keepclassmembers class androidx.viewpager.widget.ViewPager {
54
+ private boolean mIsUnableToDrag;
61
55
  }
62
- -keep class com.lynx.tasm.rendernode.compat.RenderNodeFactory{
63
- *;
56
+
57
+ # <text enable-emoji-compat> looks up AndroidX's EmojiCompat by name, which R8
58
+ # had renamed.
59
+ -keep class androidx.emoji2.text.EmojiCompat {
60
+ public static androidx.emoji2.text.EmojiCompat get();
61
+ public java.lang.CharSequence process(java.lang.CharSequence);
64
62
  }
65
- # LYNX END
63
+
64
+ # Classes the app doesn't have, which R8 would otherwise fail the build on.
65
+ # XElement's umbrella registers <animax-view> and <markdown>, whose modules
66
+ # build.gradle.kts leaves out, so those two tags can't be created (the runtime
67
+ # doesn't support them). Lynx uses Gson only to describe its environment for
68
+ # debugging tools.
69
+ -dontwarn com.lynx.animax.**
70
+ -dontwarn com.lynx.xelement.markdown.**
71
+ -dontwarn com.google.gson.**
72
+
73
+ # Keep the file names and line numbers in stack traces. The mapping file
74
+ # (app/build/outputs/mapping/release/mapping.txt, which Gradle also puts in
75
+ # the .aab for Google Play) turns the renamed classes and methods back.
76
+ -keepattributes SourceFile,LineNumberTable
77
+ -renamesourcefileattribute SourceFile
@@ -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")