Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(native): write the resource table an app icon needs

esenginedbdcbeb9d782
diff --git a/build-tools/utils/aab.js b/build-tools/utils/aab.js
index eb499e4d0..c8f7ec341 100644
--- a/build-tools/utils/aab.js
+++ b/build-tools/utils/aab.js
@@ -22,6 +22,8 @@ import { makeZip } from './zip.js';
import { packageEntries } from './apk.js';
import { message, bytesField } from './protobuf.js';
import { compileProtoManifest } from './androidProtoXml.js';
+import { appResources } from './androidResources.js';
+import { DEFAULT_ICON } from './nativeTemplate.js';
import { jarSignatureFiles } from './jarSign.js';
import { fillTemplate, androidScreenOrientation } from './nativeApp.js';
@@ -48,6 +50,7 @@ export function assembleAab(options) {
const { templateDir, contentDir, app, abi } = options;
const dex = path.join(templateDir, 'classes.dex');
const hasDex = existsSync(dex);
+ const resources = appResources(options.icon ?? readFileSync(path.join(templateDir, DEFAULT_ICON)));
const manifest = compileProtoManifest(fillTemplate(
readFileSync(path.join(templateDir, 'AndroidManifest.xml.in'), 'utf8'), {
@@ -57,7 +60,7 @@ export function assembleAab(options) {
VERSION_CODE: app.versionCode,
SCREEN_ORIENTATION: androidScreenOrientation(app.orientation),
HAS_CODE: hasDex ? 'true' : 'false',
- }));
+ }), resources.references);
const libDir = path.join(templateDir, 'lib', abi);
if (!existsSync(libDir)) throw new Error(`The runtime template has no lib/${abi}.`);
@@ -66,9 +69,8 @@ export function assembleAab(options) {
const entries = [
{ name: 'BundleConfig.pb', data: bundleConfig() },
{ name: 'base/manifest/AndroidManifest.xml', data: manifest },
- // An empty ResourceTable: the app declares no resources of its own, and the
- // one reference its manifest makes is to a framework id.
- { name: 'base/resources.pb', data: Buffer.alloc(0) },
+ { name: 'base/resources.pb', data: resources.pb },
+ ...resources.files.map((f) => ({ ...f, name: `base/${f.name}` })),
...(hasDex ? [{ name: 'base/dex/classes.dex', data: readFileSync(dex) }] : []),
...packageEntries(libDir, `base/lib/${abi}`),
...(existsSync(templateAssets) ? packageEntries(templateAssets, 'base/assets') : []),
diff --git a/build-tools/utils/androidBinaryXml.js b/build-tools/utils/androidBinaryXml.js
index 5f0789ce1..3c4c7ad49 100644
--- a/build-tools/utils/androidBinaryXml.js
+++ b/build-tools/utils/androidBinaryXml.js
@@ -203,15 +203,26 @@ class StringPool {
// Values
// =============================================================================
-/** How a manifest attribute's text is typed. Order matters: `@android:style/...`
- * before anything, then the two integer spellings, then booleans, then string. */
-function typedValue(value, pool) {
+/**
+ * How a manifest attribute's text is typed. Order matters: references before
+ * anything, then the two integer spellings, then booleans, then string.
+ *
+ * `@android:style/...` is a framework id, known here. `@mipmap/...` and friends
+ * are the APP's own resources, whose ids belong to whoever built the resource
+ * table — so they are passed in rather than guessed.
+ */
+function typedValue(value, pool, references) {
const style = /^@android:style\/(.+)$/.exec(value);
if (style) {
const id = ANDROID_STYLE_IDS[style[1]];
if (id === undefined) throw new Error(`Unknown framework style @android:style/${style[1]}`);
return { type: TYPE_REFERENCE, data: id, raw: NO_ENTRY };
}
+ if (value.startsWith('@')) {
+ const id = references[value];
+ if (id === undefined) throw new Error(`No resource id for ${value} — the assembler declares what it packages.`);
+ return { type: TYPE_REFERENCE, data: id >>> 0, raw: NO_ENTRY };
+ }
if (value === 'true' || value === 'false') {
return { type: TYPE_INT_BOOLEAN, data: value === 'true' ? 0xffffffff : 0, raw: NO_ENTRY };
}
@@ -254,9 +265,11 @@ function nodeHeaderExtra(line) {
* the two are one structure written as two.
*
* @param {object} root The element from {@link parseXml}.
+ * @param {Record<string, number>} [references] The app's own resource ids, by
+ * `@type/name` — what an `android:icon` resolves through.
* @returns {Buffer}
*/
-export function encodeBinaryXml(root) {
+export function encodeBinaryXml(root, references = {}) {
const pool = new StringPool();
// Pass 1: every framework attribute name, in first-use order.
@@ -291,7 +304,7 @@ export function encodeBinaryXml(root) {
.map((a) => ({
ns: a.prefix === 'android' ? nsUri : NO_ENTRY,
name: pool.add(a.name),
- value: typedValue(a.value, pool),
+ value: typedValue(a.value, pool, references),
}));
const name = pool.add(node.name);
@@ -343,6 +356,6 @@ export function encodeBinaryXml(root) {
}
/** Compile manifest SOURCE (the filled template) to the bytes an APK carries. */
-export function compileManifest(xml) {
- return encodeBinaryXml(parseXml(xml));
+export function compileManifest(xml, references = {}) {
+ return encodeBinaryXml(parseXml(xml), references);
}
diff --git a/build-tools/utils/androidProtoXml.js b/build-tools/utils/androidProtoXml.js
index acc49107b..da8c2fa98 100644
--- a/build-tools/utils/androidProtoXml.js
+++ b/build-tools/utils/androidProtoXml.js
@@ -34,13 +34,18 @@ const ITEM_PRIM = 7;
const REF_ID = 2;
/** `Item` for an attribute value, typed the way the platform expects to read it. */
-function compiledItem(value) {
+function compiledItem(value, references) {
const style = /^@android:style\/(.+)$/.exec(value);
if (style) {
const id = ANDROID_STYLE_IDS[style[1]];
if (id === undefined) throw new Error(`Unknown framework style @android:style/${style[1]}`);
return bytesField(ITEM_REF, message(varintField(REF_ID, id)));
}
+ if (value.startsWith('@')) {
+ const id = references[value];
+ if (id === undefined) throw new Error(`No resource id for ${value} — the assembler declares what it packages.`);
+ return bytesField(ITEM_REF, message(varintField(REF_ID, id >>> 0)));
+ }
if (value === 'true' || value === 'false') {
return bytesField(ITEM_PRIM, message(boolField(PRIM_BOOLEAN, value === 'true')));
}
@@ -56,13 +61,13 @@ function compiledItem(value) {
}
/** XmlAttribute { namespace_uri = 1, name = 2, value = 3, resource_id = 5, compiled_item = 6 } */
-function attribute(attr) {
+function attribute(attr, references) {
const framework = attr.prefix === 'android';
const id = framework ? ANDROID_ATTR_IDS[attr.name] : undefined;
if (framework && id === undefined) {
throw new Error(`No public resource id known for android:${attr.name} — add it to ANDROID_ATTR_IDS.`);
}
- const compiled = framework ? compiledItem(attr.value) : null;
+ const compiled = framework ? compiledItem(attr.value, references) : null;
return message(
framework ? bytesField(1, ANDROID_NS) : null,
bytesField(2, attr.name),
@@ -73,23 +78,23 @@ function attribute(attr) {
}
/** XmlElement { namespace_declaration = 1, namespace_uri = 2, name = 3, attribute = 4, child = 5 } */
-function element(node, declareNamespace) {
+function element(node, declareNamespace, references) {
return message(
declareNamespace ? bytesField(1, message(bytesField(1, 'android'), bytesField(2, ANDROID_NS))) : null,
bytesField(3, node.name),
...node.attrs
.filter((a) => a.name !== 'xmlns' && a.prefix !== 'xmlns')
- .map((a) => bytesField(4, attribute(a))),
- ...node.children.map((child) => bytesField(5, node_(child, false))),
+ .map((a) => bytesField(4, attribute(a, references))),
+ ...node.children.map((child) => bytesField(5, node_(child, false, references))),
);
}
/** XmlNode { element = 1 } */
-function node_(element_, declareNamespace) {
- return message(bytesField(1, element(element_, declareNamespace)));
+function node_(element_, declareNamespace, references) {
+ return message(bytesField(1, element(element_, declareNamespace, references)));
}
/** Compile manifest SOURCE to the protobuf XML an App Bundle carries. */
-export function compileProtoManifest(xml) {
- return node_(parseXml(xml), true);
+export function compileProtoManifest(xml, references = {}) {
+ return node_(parseXml(xml), true, references);
}
diff --git a/build-tools/utils/androidResources.js b/build-tools/utils/androidResources.js
new file mode 100644
index 000000000..743d6ee1b
--- /dev/null
+++ b/build-tools/utils/androidResources.js
@@ -0,0 +1,194 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The resource table an assembled app declares — one entry, the launcher icon.
+//
+// `android:icon` must be a RESOURCE REFERENCE; a path is not accepted. So an app
+// with its own icon needs a resource table, in both encodings: `resources.arsc`
+// (binary) for the APK and `resources.pb` (protobuf) for the bundle.
+//
+// The alternative was to have the template carry tables aapt2 built, and swap the
+// icon's bytes at assembly time — which works, but puts aapt2 back on the path
+// (for whoever builds a template) and freezes the table's shape into the release.
+// Writing the table is a few hundred lines for something the whole pipeline is
+// already doing four times over, and it keeps "no Android SDK anywhere" true
+// rather than nearly true.
+//
+// One package, one type, one entry, and ids we choose, so nothing here has to
+// agree with a tool that is not in the build.
+
+import { message, bytesField, varintField } from './protobuf.js';
+
+/** The application package's id — 0x7f is what every app's own resources use
+ * (0x01 is the framework). */
+export const APP_PACKAGE_ID = 0x7f;
+const TYPE_ID = 1;
+const ENTRY_ID = 0;
+
+/** The id `@mipmap/ic_launcher` resolves to: package 7f, type 01, entry 0000. */
+export const ICON_RESOURCE_ID = (APP_PACKAGE_ID << 24) | (TYPE_ID << 16) | ENTRY_ID;
+
+/** What the manifest writes to reach it, in either encoding. */
+export const ICON_REFERENCE = '@mipmap/ic_launcher';
+
+/**
+ * Where the icon file sits. xxxhdpi rather than an unqualified folder: with no
+ * density the platform reads a bitmap as mdpi and scales it UP on every modern
+ * screen, so a sharp source would arrive blurry.
+ */
+export const ICON_PATH = 'res/mipmap-xxxhdpi/ic_launcher.png';
+const ICON_DENSITY = 640;
+
+// Res_value data types (the same table binary XML uses).
+const TYPE_STRING = 0x03;
+
+/** A UTF-16 string pool chunk — the same structure binary XML carries. */
+function stringPool(strings) {
+ const bodies = strings.map((s) => {
+ const chars = Buffer.from(s, 'utf16le');
+ const out = Buffer.alloc(2 + chars.length + 2);
+ out.writeUInt16LE(chars.length / 2, 0);
+ chars.copy(out, 2);
+ return out;
+ });
+ const offsets = Buffer.alloc(strings.length * 4);
+ let at = 0;
+ bodies.forEach((b, n) => { offsets.writeUInt32LE(at, n * 4); at += b.length; });
+ const data = Buffer.concat(bodies);
+ const padding = (4 - (data.length % 4)) % 4;
+ const headerSize = 28;
+ const stringsStart = headerSize + offsets.length;
+
+ const header = Buffer.alloc(headerSize);
+ header.writeUInt16LE(0x0001, 0);
+ header.writeUInt16LE(headerSize, 2);
+ header.writeUInt32LE(stringsStart + data.length + padding, 4);
+ header.writeUInt32LE(strings.length, 8);
+ header.writeUInt32LE(0, 12);
+ header.writeUInt32LE(0, 16); // UTF-16, unsorted
+ header.writeUInt32LE(stringsStart, 20);
+ header.writeUInt32LE(0, 24);
+ return Buffer.concat([header, offsets, data, Buffer.alloc(padding)]);
+}
+
+function chunk(type, headerExtra, body) {
+ const headerSize = 8 + headerExtra.length;
+ const header = Buffer.alloc(8);
+ header.writeUInt16LE(type, 0);
+ header.writeUInt16LE(headerSize, 2);
+ header.writeUInt32LE(headerSize + body.length, 4);
+ return Buffer.concat([header, headerExtra, body]);
+}
+
+/** ResTable_config — 28 bytes, everything default except the density the icon is
+ * authored for. */
+function configuration() {
+ const config = Buffer.alloc(28);
+ config.writeUInt32LE(28, 0);
+ config.writeUInt16LE(ICON_DENSITY, 14);
+ return config;
+}
+
+/**
+ * `resources.arsc`: a table with one package, one type (`mipmap`) and one entry
+ * (`ic_launcher`) whose value is the path in the global string pool.
+ */
+function binaryTable() {
+ const values = stringPool([ICON_PATH]);
+
+ const typeStrings = stringPool(['mipmap']);
+ const keyStrings = stringPool(['ic_launcher']);
+
+ // ResTable_typeSpec: one entry, no configuration-varying flags.
+ const specExtra = Buffer.alloc(8);
+ specExtra.writeUInt8(TYPE_ID, 0);
+ specExtra.writeUInt32LE(1, 4);
+ const spec = chunk(0x0202, specExtra, Buffer.alloc(4));
+
+ // ResTable_entry + Res_value: the entry names its key and points at the path.
+ const entry = Buffer.alloc(16);
+ entry.writeUInt16LE(8, 0); // entry size
+ entry.writeUInt16LE(0, 2); // flags: a simple value
+ entry.writeUInt32LE(0, 4); // key index ("ic_launcher")
+ entry.writeUInt16LE(8, 8); // Res_value size
+ entry.writeUInt8(0, 10);
+ entry.writeUInt8(TYPE_STRING, 11);
+ entry.writeUInt32LE(0, 12); // index into the value pool
+ const offsets = Buffer.alloc(4); // one entry, at offset 0
+
+ const config = configuration();
+ const typeExtra = Buffer.alloc(12 + config.length);
+ typeExtra.writeUInt8(TYPE_ID, 0);
+ typeExtra.writeUInt32LE(1, 4); // entryCount
+ typeExtra.writeUInt32LE(8 + 12 + config.length + offsets.length, 8); // entriesStart
+ config.copy(typeExtra, 12);
+ const type = chunk(0x0201, typeExtra, Buffer.concat([offsets, entry]));
+
+ // ResTable_package: the header carries the two pool offsets, so it is built
+ // once the pools' sizes are known.
+ const packageHeaderSize = 288;
+ const packageExtra = Buffer.alloc(packageHeaderSize - 8);
+ packageExtra.writeUInt32LE(APP_PACKAGE_ID, 0);
+ Buffer.from('estella.app', 'utf16le').copy(packageExtra, 4);
+ packageExtra.writeUInt32LE(packageHeaderSize, 260); // typeStrings
+ packageExtra.writeUInt32LE(0, 264); // lastPublicType
+ packageExtra.writeUInt32LE(packageHeaderSize + typeStrings.length, 268); // keyStrings
+ packageExtra.writeUInt32LE(0, 272); // lastPublicKey
+ packageExtra.writeUInt32LE(0, 276); // typeIdOffset
+ const pkg = chunk(0x0200, packageExtra, Buffer.concat([typeStrings, keyStrings, spec, type]));
+
+ const tableExtra = Buffer.alloc(4);
+ tableExtra.writeUInt32LE(1, 0); // packageCount
+ return chunk(0x0002, tableExtra, Buffer.concat([values, pkg]));
+}
+
+/**
+ * `resources.pb`: the same table, protobuf.
+ *
+ * ResourceTable { package = 2 } · Package { package_id = 1, package_name = 2,
+ * type = 3 } · Type { type_id = 1, name = 2, entry = 3 } · Entry { entry_id = 1,
+ * name = 2, config_value = 5 } · ConfigValue { config = 1, value = 3 } ·
+ * Value { item = 1 } · Item { file = 5 } · FileReference { path = 1, type = 2 }.
+ *
+ * No Configuration is written. Its density field number is the one thing here
+ * that no available tool can check, and a wrong number would not be ignored — it
+ * would set some OTHER dimension, and the icon would reach only the devices that
+ * happened to match. An absent configuration is simply "every device", which is
+ * correct, just not density-aware.
+ */
+function protoTable() {
+ const fileReference = message(bytesField(1, ICON_PATH), varintField(2, 1)); // Type.PNG
+ const value = message(bytesField(1, message(bytesField(5, fileReference))));
+ const configValue = message(bytesField(3, value));
+ const entry = message(
+ bytesField(1, message(varintField(1, ENTRY_ID))),
+ bytesField(2, 'ic_launcher'),
+ bytesField(5, configValue),
+ );
+ const type = message(
+ bytesField(1, message(varintField(1, TYPE_ID))),
+ bytesField(2, 'mipmap'),
+ bytesField(3, entry),
+ );
+ const pkg = message(
+ bytesField(1, message(varintField(1, APP_PACKAGE_ID))),
+ bytesField(2, 'estella.app'),
+ bytesField(3, type),
+ );
+ return message(bytesField(2, pkg));
+}
+
+/**
+ * The resources an assembled app carries: the icon file, the table in both
+ * encodings, and the reference the manifest resolves through.
+ *
+ * @param {Buffer} iconPng The launcher icon, as PNG.
+ */
+export function appResources(iconPng) {
+ return {
+ references: { [ICON_REFERENCE]: ICON_RESOURCE_ID },
+ files: [{ name: ICON_PATH, data: iconPng }],
+ arsc: binaryTable(),
+ pb: protoTable(),
+ };
+}
diff --git a/build-tools/utils/apk.js b/build-tools/utils/apk.js
index d48647823..e4ff017e4 100644
--- a/build-tools/utils/apk.js
+++ b/build-tools/utils/apk.js
@@ -20,6 +20,8 @@ import { createHash, createPublicKey, sign as cryptoSign } from 'crypto';
import { existsSync, readFileSync, readdirSync } from 'fs';
import { makeZip, zipLayout } from './zip.js';
import { compileManifest } from './androidBinaryXml.js';
+import { appResources } from './androidResources.js';
+import { DEFAULT_ICON } from './nativeTemplate.js';
import { fillTemplate, androidScreenOrientation } from './nativeApp.js';
/** The boundary a mapped `.so` must start on — a 16 KiB page, which every
@@ -137,12 +139,14 @@ export function packageEntries(dir, prefix) {
* orientation: 'landscape'|'portrait'}} options.app
* @param {{privateKey: import('crypto').KeyObject, certificate: Buffer}} options.key
* @param {string} options.abi
+ * @param {Buffer} [options.icon] The launcher icon; the template's default when absent.
* @returns {Buffer} the signed package.
*/
export function assembleApk(options) {
const { templateDir, contentDir, app, abi } = options;
const dex = path.join(templateDir, 'classes.dex');
const hasDex = existsSync(dex);
+ const resources = appResources(options.icon ?? readFileSync(path.join(templateDir, DEFAULT_ICON)));
const manifest = compileManifest(fillTemplate(
readFileSync(path.join(templateDir, 'AndroidManifest.xml.in'), 'utf8'), {
@@ -152,7 +156,7 @@ export function assembleApk(options) {
VERSION_CODE: app.versionCode,
SCREEN_ORIENTATION: androidScreenOrientation(app.orientation),
HAS_CODE: hasDex ? 'true' : 'false',
- }));
+ }), resources.references);
const libDir = path.join(templateDir, 'lib', abi);
if (!existsSync(libDir)) throw new Error(`The runtime template has no lib/${abi}.`);
@@ -160,6 +164,9 @@ export function assembleApk(options) {
const entries = [
{ name: 'AndroidManifest.xml', data: manifest },
+ // Stored and aligned like the libraries: the resource table is mmapped too.
+ { name: 'resources.arsc', data: resources.arsc, store: true, align: 4 },
+ ...resources.files,
...(hasDex ? [{ name: 'classes.dex', data: readFileSync(dex) }] : []),
...packageEntries(libDir, `lib/${abi}`).map((e) => ({ ...e, store: true, align: PAGE_ALIGNMENT })),
// The template's assets (the SDK bytecode) first, so a project cannot
diff --git a/build-tools/utils/nativeTemplate.d.ts b/build-tools/utils/nativeTemplate.d.ts
index 03c090ce9..3e4cf6354 100644
--- a/build-tools/utils/nativeTemplate.d.ts
+++ b/build-tools/utils/nativeTemplate.d.ts
@@ -64,8 +64,11 @@ export interface PublishedTemplate {
export const TEMPLATE_INDEX: string;
export function releaseAssetBase(engineVersion: string): string;
export function parseTemplateIndex(doc: unknown, engineVersion?: string): PublishedTemplate[] | null;
+export const DEFAULT_ICON: string;
export function iosTemplateSources(dir: string): {
xcframework: string;
mainM: string;
infoPlistIn: string;
+ /** The default launcher icon, used when the project sets none. */
+ icon: string;
};
diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.js
index 41b6b89c9..4b9d0645d 100644
--- a/build-tools/utils/nativeTemplate.js
+++ b/build-tools/utils/nativeTemplate.js
@@ -29,6 +29,15 @@ export const TEMPLATE_MANIFEST = 'template.json';
* the APK's native-code declaration, so the package installs nowhere. */
export const BYTECODE_FILE = 'esengine.native.qjsbc';
+/**
+ * The launcher icon an app gets when the project does not set one.
+ *
+ * In the template rather than in the editor because the CLI packages without an
+ * editor, and shipped at all because the alternative — the platform's default —
+ * is a green robot on a published game.
+ */
+export const DEFAULT_ICON = 'icon.png';
+
/** A template's id: one per thing that must be compiled separately. */
export function templateId(platform, abi) {
return `${platform}-${abi}`;
@@ -59,6 +68,7 @@ export function templateLayout(platform, options = {}) {
},
{ rel: 'App/main.m', from: (ctx) => path.join(ctx.root, 'native', 'ios', 'App', 'main.m') },
{ rel: 'App/Info.plist.in', from: (ctx) => path.join(ctx.root, 'native', 'ios', 'App', 'Info.plist.in') },
+ { rel: DEFAULT_ICON, from: (ctx) => path.join(ctx.root, 'native', 'icon.png') },
];
}
if (platform === 'android') {
@@ -86,6 +96,7 @@ export function templateLayout(platform, options = {}) {
rel: 'AndroidManifest.xml.in',
from: (ctx) => path.join(ctx.root, 'native', 'android', 'host', 'AndroidManifest.xml.in'),
},
+ { rel: DEFAULT_ICON, from: (ctx) => path.join(ctx.root, 'native', 'icon.png') },
];
}
throw new Error(`Unknown native platform "${platform}" (expected android or ios).`);
@@ -243,5 +254,6 @@ export function iosTemplateSources(dir) {
xcframework: path.join(dir, 'Estella.xcframework'),
mainM: path.join(dir, 'App', 'main.m'),
infoPlistIn: path.join(dir, 'App', 'Info.plist.in'),
+ icon: path.join(dir, DEFAULT_ICON),
};
}
diff --git a/desktop/tests/android-aab.test.ts b/desktop/tests/android-aab.test.ts
index d25167029..2b6dcf41d 100644
--- a/desktop/tests/android-aab.test.ts
+++ b/desktop/tests/android-aab.test.ts
@@ -29,6 +29,8 @@ import { readZip, makeZip } from '../../build-tools/utils/zip.js';
const REPO = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const VERIFIER = path.join(REPO, 'build-tools', 'tests', 'verify-aab.py');
const MANIFEST_TEMPLATE = path.join(REPO, 'native', 'android', 'host', 'AndroidManifest.xml.in');
+/** The icon a template ships, used when the project sets none. */
+const DEFAULT_ICON_SOURCE = path.join(REPO, 'native', 'icon.png');
const APP = {
id: 'com.example.demo', name: 'My Game', version: '1.2', versionCode: 7,
@@ -80,6 +82,7 @@ beforeEach(() => {
mkdirSync(path.join(templateDir, 'lib', 'arm64-v8a'), { recursive: true });
mkdirSync(path.join(templateDir, 'assets'), { recursive: true });
writeFileSync(path.join(templateDir, 'AndroidManifest.xml.in'), readFileSync(MANIFEST_TEMPLATE));
+ writeFileSync(path.join(templateDir, 'icon.png'), readFileSync(DEFAULT_ICON_SOURCE));
writeFileSync(path.join(templateDir, 'lib/arm64-v8a/libestella_js_host.so'), Buffer.alloc(40_000, 7));
writeFileSync(path.join(templateDir, 'lib/arm64-v8a/libwebgpu_dawn.so'), Buffer.alloc(30_000, 9));
writeFileSync(path.join(templateDir, 'classes.dex'), Buffer.from('dex\n035\0stand-in'));
@@ -189,6 +192,21 @@ describe('assembling an App Bundle', () => {
expect(attr(find(manifest, 'activity')!, 'name')?.value).toBe(binary.activity);
});
+ it('carries the icon and the resource table the reference resolves through', () => {
+ if (!hasPython) return;
+ const entries = readZip(readFileSync(build())).map((e) => e.name);
+
+ expect(entries).toContain('base/res/mipmap-xxxhdpi/ic_launcher.png');
+ expect(entries).toContain('base/resources.pb');
+
+ const { manifest } = verify(build());
+ const application = find(manifest, 'application')!;
+ expect(attr(application, 'icon')).toMatchObject({
+ value: '@mipmap/ic_launcher',
+ compiled: { ref: 0x7f010000 },
+ });
+ });
+
it('fails verification once an entry changes under the signature', () => {
if (!hasPython) return;
// Repacked with one file swapped and the ORIGINAL signature kept — which is
diff --git a/desktop/tests/android-apk.test.ts b/desktop/tests/android-apk.test.ts
index 990983a61..46f7df128 100644
--- a/desktop/tests/android-apk.test.ts
+++ b/desktop/tests/android-apk.test.ts
@@ -21,11 +21,14 @@ import { fileURLToPath } from 'node:url';
import { assembleApk, apkFileName } from '../../build-tools/utils/apk.js';
import { debugSigningKey } from '../../build-tools/utils/androidKeystore.js';
import { compileManifest, ANDROID_ATTR_IDS } from '../../build-tools/utils/androidBinaryXml.js';
-import { zipLayout } from '../../build-tools/utils/zip.js';
+import { appResources, ICON_RESOURCE_ID, ICON_PATH } from '../../build-tools/utils/androidResources.js';
+import { zipLayout, readZip } from '../../build-tools/utils/zip.js';
const REPO = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const VERIFIER = path.join(REPO, 'build-tools', 'tests', 'verify-apk.py');
const MANIFEST_TEMPLATE = path.join(REPO, 'native', 'android', 'host', 'AndroidManifest.xml.in');
+/** The icon a template ships, used when the project sets none. */
+const DEFAULT_ICON_SOURCE = path.join(REPO, 'native', 'icon.png');
const APP = {
id: 'com.example.demo', name: 'My Game', version: '1.2', versionCode: 7,
@@ -66,6 +69,7 @@ beforeEach(() => {
mkdirSync(path.join(templateDir, 'lib', 'arm64-v8a'), { recursive: true });
mkdirSync(path.join(templateDir, 'assets'), { recursive: true });
writeFileSync(path.join(templateDir, 'AndroidManifest.xml.in'), readFileSync(MANIFEST_TEMPLATE));
+ writeFileSync(path.join(templateDir, 'icon.png'), readFileSync(DEFAULT_ICON_SOURCE));
writeFileSync(path.join(templateDir, 'lib/arm64-v8a/libestella_js_host.so'), Buffer.alloc(120_000, 7));
writeFileSync(path.join(templateDir, 'lib/arm64-v8a/libwebgpu_dawn.so'), Buffer.alloc(90_000, 9));
writeFileSync(path.join(templateDir, 'classes.dex'), Buffer.from('dex\n035\0stand-in'));
@@ -83,6 +87,8 @@ afterEach(() => {
rmSync(scratch, { recursive: true, force: true });
});
+const assemblyOptions = () => ({ templateDir, contentDir, app: APP, abi: 'arm64-v8a', key: debugSigningKey() });
+
function build(app = APP): string {
const apk = assembleApk({ templateDir, contentDir, app, abi: 'arm64-v8a', key: debugSigningKey() });
const file = path.join(contentDir, apkFileName(app.id));
@@ -117,7 +123,8 @@ describe('the manifest is compiled, not shelled out to aapt2', () => {
writeFileSync(file, compileManifest(readFileSync(MANIFEST_TEMPLATE, 'utf8')
.replace(/@APP_ID@/g, 'com.example.demo').replace(/@APP_NAME@/g, 'My Game')
.replace(/@VERSION_NAME@/g, '1.2').replace(/@VERSION_CODE@/g, '7')
- .replace(/@SCREEN_ORIENTATION@/g, 'sensorPortrait').replace(/@HAS_CODE@/g, 'true')));
+ .replace(/@SCREEN_ORIENTATION@/g, 'sensorPortrait').replace(/@HAS_CODE@/g, 'true'),
+ appResources(Buffer.alloc(4)).references));
const xml = execFileSync('python3', ['-c',
'import sys,os;os.environ["LOGURU_LEVEL"]="CRITICAL";'
@@ -185,6 +192,33 @@ describe('assembling an APK', () => {
expect(checked).toBe(2);
});
+ it('carries a launcher icon the platform can resolve, through a table we wrote', () => {
+ if (!hasAndroguard) return;
+ const apk = build();
+
+ const resolved = JSON.parse(execFileSync('python3', ['-c',
+ 'import sys,os,json;os.environ["LOGURU_LEVEL"]="CRITICAL";'
+ + 'from androguard.core.apk import APK;a=APK(sys.argv[1]);i=a.get_app_icon();'
+ + 'print(json.dumps({"attr":a.get_attribute_value("application","icon"),'
+ + '"file":i,"bytes":len(a.get_file(i)) if i else 0}))', apk,
+ ], { encoding: 'utf8' }));
+
+ // The reference resolves through OUR resources.arsc to OUR file — the whole
+ // chain, read back by something that has never seen this code.
+ expect(resolved.attr.toUpperCase()).toBe(`@${ICON_RESOURCE_ID.toString(16).toUpperCase()}`);
+ expect(resolved.file).toBe(ICON_PATH);
+ expect(resolved.bytes).toBe(readFileSync(DEFAULT_ICON_SOURCE).length);
+ });
+
+ it("packages the project's own icon when it has one", () => {
+ const mine = Buffer.concat([readFileSync(DEFAULT_ICON_SOURCE), Buffer.from('mine')]);
+ const file = path.join(contentDir, 'custom.apk');
+ writeFileSync(file, assembleApk({ ...assemblyOptions(), icon: mine }));
+
+ const packaged = readZip(readFileSync(file)).find((e) => e.name === ICON_PATH)!;
+ expect(packaged.data.equals(mine)).toBe(true);
+ });
+
it('is named after the app, so a second project does not replace the first', () => {
expect(path.basename(build())).toBe('demo.apk');
expect(apkFileName('com.acme.spaceGame')).toBe('spaceGame.apk');
diff --git a/native/android/host/AndroidManifest.xml.in b/native/android/host/AndroidManifest.xml.in
index bca415711..b173606c8 100644
--- a/native/android/host/AndroidManifest.xml.in
+++ b/native/android/host/AndroidManifest.xml.in
@@ -15,7 +15,8 @@
android:versionName="@VERSION_NAME@">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="33" />
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x400003" android:required="true" />
- <application android:label="@APP_NAME@" android:hasCode="@HAS_CODE@" android:extractNativeLibs="false">
+ <application android:label="@APP_NAME@" android:icon="@mipmap/ic_launcher"
+ android:hasCode="@HAS_CODE@" android:extractNativeLibs="false">
<!-- A game's window, stated before any code runs: no title, no status bar.
The host asks for the rest (navigation bar, display cutout) once it
has the UI thread — see onWindowFocusChanged in platform/android.cpp. -->
diff --git a/native/icon.png b/native/icon.png
new file mode 100644
index 000000000..6b9b9768c
Binary files /dev/null and b/native/icon.png differ