@geastack/apple 0.2.21 → 0.2.23

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/apple",
3
- "version": "0.2.21",
3
+ "version": "0.2.23",
4
4
  "description": "Generated Apple SDK bindings plus the macOS, iOS and tvOS native build targets for Gea apps.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -324,7 +324,8 @@ GEA_CLI_BIN="$GEA_CLI" node "$IOS_DIR/generate-xcode-project.mjs" \
324
324
  --app-name "$APP_NAME" \
325
325
  --bundle-id "$BUNDLE_ID" \
326
326
  --generated-dir "$GENERATED_DIR" \
327
- --project-path "$PROJECT_PATH"
327
+ --project-path "$PROJECT_PATH" \
328
+ --destination "$DESTINATION"
328
329
 
329
330
  SDK="$SIMULATOR_SDK"
330
331
  SIMULATOR_DEVICE_ID="${GEA_IOS_SIMULATOR_UDID:-}"
@@ -6,6 +6,8 @@ import { fileURLToPath } from 'node:url'
6
6
 
7
7
  import { execFileSync } from 'node:child_process'
8
8
 
9
+ import { readUikitNativePackages } from './native-packages.mjs'
10
+
9
11
  // The project is the directory this ran in -- the one being compiled, which is
10
12
  // also what the CLI resolves from cwd. iOS target sources live next to this
11
13
  // script, not in the project. App metadata and icon generation come from the
@@ -171,10 +173,25 @@ const rendererSources = [
171
173
  // resource directories staged into the app bundle (nativeResources).
172
174
  const uikitTarget = tvos ? 'tvos' : 'ios'
173
175
  const appNativeLink = appMeta.nativeLink?.[uikitTarget] || {}
176
+ // Native code the packages the program uses declare in their own gea-native.json
177
+ // (native-packages.mjs): their sources, frameworks, libraries and defines, and
178
+ // any static library they build once on this Mac (ANGLE for WebGL on tvOS).
179
+ let nativePackages
180
+ try {
181
+ nativePackages = readUikitNativePackages({
182
+ appRoot,
183
+ moduleGraphPath: path.join(generatedDir, 'module-graph', 'gea-module-graph.json'),
184
+ target: uikitTarget,
185
+ simulator: (opt('--destination') || 'simulator') === 'simulator',
186
+ })
187
+ } catch (error) {
188
+ fail(`native packages: ${error.message}`)
189
+ }
174
190
  const appNativeSources = [...new Map([
175
191
  ...findAppNativeSources(),
176
192
  ...(appMeta.nativeSourcePaths || []).map((file) => source(file, nativeSourceKind(file))),
177
193
  ...(appMeta.targetNativeSourcePaths?.[uikitTarget] || []).map((file) => source(file, nativeSourceKind(file))),
194
+ ...nativePackages.sources.map((file) => source(file, nativeSourceKind(file))),
178
195
  ].map((entry) => [entry.file, entry])).values()]
179
196
  const sources = [
180
197
  source(path.join(iosDir, 'main/ios_main.mm'), 'sourcecode.cpp.objcpp'),
@@ -215,7 +232,8 @@ const assetsGenerated = source(path.join(generatedDir, 'gea_embedded_assets_gene
215
232
  if (existing(assetsGenerated)) sources.push(assetsGenerated)
216
233
  const hasGeneratedFonts = sources.some((entry) => path.basename(entry.file) === 'gea_embedded_font_generated.cpp')
217
234
 
218
- const fontResources = findFontResources().map((file) => resource(file))
235
+ // Plain files copied into the bundle: fonts, and the packages' resources (license notices).
236
+ const fontResources = [...findFontResources(), ...nativePackages.resources].map((file) => resource(file))
219
237
  // Each nativeResources destination becomes a folder of the same name in the
220
238
  // bundle: stage them under the generated directory, then reference the folders.
221
239
  const nativeResourceDir = path.join(generatedDir, 'native-resources')
@@ -249,7 +267,7 @@ const frameworks = [
249
267
  'MetalKit.framework',
250
268
  'Foundation.framework',
251
269
  ]
252
- for (const name of appNativeLink.frameworks || []) {
270
+ for (const name of [...(appNativeLink.frameworks || []), ...nativePackages.frameworks]) {
253
271
  if (!frameworks.includes(`${name}.framework`)) frameworks.push(`${name}.framework`)
254
272
  }
255
273
 
@@ -332,6 +350,7 @@ const includePaths = [
332
350
  path.join(appRoot, tvos ? 'tvos' : 'ios'),
333
351
  ...new Set(appNativeSources.map(({ file }) => path.dirname(file))),
334
352
  ...(appNativeLink.nativeIncludeDirectories || []),
353
+ ...nativePackages.includeDirs,
335
354
  // Framework include roots (core/host/engine includes + vendor/stb + AnimatedGIF)
336
355
  // from the shared manifest gea_sources.sh, passed by build-ios.sh via env.
337
356
  ...(process.env.GEA_FW_INCLUDE_DIRS || '').split('\n').filter(Boolean),
@@ -361,6 +380,7 @@ function buildSettings(configuration) {
361
380
  ...(hasGeneratedFonts ? ['GEA_EMBEDDED_HAS_GENERATED_FONTS=1'] : []),
362
381
  // gea.defines and the resolved build settings' macros.
363
382
  ...(buildConfig.defines || []),
383
+ ...nativePackages.defines,
364
384
  ]
365
385
  return `{
366
386
  ALWAYS_SEARCH_USER_PATHS = NO;${skipAppIcon ? '' : `
@@ -379,7 +399,7 @@ function buildSettings(configuration) {
379
399
  ${tvos ? 'TVOS_DEPLOYMENT_TARGET = 17.0;' : 'IPHONEOS_DEPLOYMENT_TARGET = 16.0;'}
380
400
  LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
381
401
  ONLY_ACTIVE_ARCH = ${configuration === 'Debug' ? 'YES' : 'NO'};
382
- OTHER_LDFLAGS = (${['$(inherited)', '-Wl,-no_deduplicate', ...(appNativeLink.nativeLibraries || []), ...(appNativeLink.nativeSystemLibraries || []).map((name) => `-l${name}`)].map(q).join(', ')});
402
+ OTHER_LDFLAGS = (${['$(inherited)', '-Wl,-no_deduplicate', ...(appNativeLink.nativeLibraries || []), ...nativePackages.libraries, ...[...(appNativeLink.nativeSystemLibraries || []), ...nativePackages.systemLibraries].map((name) => `-l${name}`)].map(q).join(', ')});
383
403
  PRODUCT_BUNDLE_IDENTIFIER = ${q(bundleId)};
384
404
  PRODUCT_NAME = ${q(appName)};
385
405
  SDKROOT = ${tvos ? 'appletvos' : 'iphoneos'};
@@ -0,0 +1,166 @@
1
+ // Native code that packages contribute to an iOS or tvOS build, the UIKit
2
+ // counterpart of the Windows target's native-packages.mjs. A package that
3
+ // carries native code for these targets says so in its own `gea-native.json`,
4
+ // and the build picks it up without the app repeating any of it:
5
+ //
6
+ // { "tvos": { (and/or "ios")
7
+ // "sources": [...], .m, .mm, .c, .cpp compiled into the app
8
+ // "includeDirs": [...], "frameworks": ["Metal"], "systemLibraries": ["z"],
9
+ // "defines": { "NAME": "value" }, "libraries": [...], "resources": [...],
10
+ // "build": { "command": ["tools/build.sh", "{platform}"],
11
+ // "libraries": ["libX.a"], "resources": ["NOTICES.txt"] } } }
12
+ //
13
+ // Paths are relative to the package root. Only the packages the program uses
14
+ // count: those owning a module of the compiled module graph (the app's
15
+ // declared dependencies when there is no graph).
16
+ //
17
+ // `{platform}` in a build command is the SDK being built for: tvos,
18
+ // tvos-simulator, ios or ios-simulator.
19
+ //
20
+ // `build` is for a static library the package cannot ship prebuilt (ANGLE for
21
+ // tvOS is 600 MB and built from upstream sources). The build runs the command
22
+ // with `--out <dir>` once and caches the result under
23
+ // $GEA_NATIVE_CACHE (default ~/.geastack/cache/native), keyed by package,
24
+ // version, target and the command script's contents; its `libraries` are
25
+ // linked and its `resources` (license notices) are copied into the app bundle.
26
+
27
+ import crypto from 'node:crypto'
28
+ import fs from 'node:fs'
29
+ import os from 'node:os'
30
+ import path from 'node:path'
31
+ import { execFileSync } from 'node:child_process'
32
+ import { createRequire } from 'node:module'
33
+
34
+ function readJson(file) {
35
+ try {
36
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
37
+ } catch {
38
+ return null
39
+ }
40
+ }
41
+
42
+ // The nearest enclosing directory whose package.json names a package.
43
+ function packageRootOf(file, cache) {
44
+ let dir = path.dirname(file)
45
+ const visited = []
46
+ let found = ''
47
+ for (;;) {
48
+ if (cache.has(dir)) {
49
+ found = cache.get(dir)
50
+ break
51
+ }
52
+ visited.push(dir)
53
+ if (readJson(path.join(dir, 'package.json'))?.name) {
54
+ found = dir
55
+ break
56
+ }
57
+ const parent = path.dirname(dir)
58
+ if (parent === dir) break
59
+ dir = parent
60
+ }
61
+ for (const entry of visited) cache.set(entry, found)
62
+ return found
63
+ }
64
+
65
+ function usedPackageRoots(appRoot, moduleGraphPath) {
66
+ const roots = new Set()
67
+ const graph = moduleGraphPath ? readJson(moduleGraphPath) : null
68
+ if (graph && Array.isArray(graph.modules)) {
69
+ const cache = new Map()
70
+ for (const module of graph.modules) {
71
+ const file = module?.file
72
+ if (typeof file !== 'string' || !path.isAbsolute(file) || !fs.existsSync(file)) continue
73
+ const root = packageRootOf(file, cache)
74
+ if (root) roots.add(fs.realpathSync(root))
75
+ }
76
+ return roots
77
+ }
78
+ const manifest = readJson(path.join(appRoot, 'package.json')) || {}
79
+ const appRequire = createRequire(path.join(appRoot, 'package.json'))
80
+ for (const name of [...Object.keys(manifest.dependencies || {}), ...Object.keys(manifest.devDependencies || {})]) {
81
+ try {
82
+ roots.add(fs.realpathSync(path.dirname(appRequire.resolve(`${name}/package.json`))))
83
+ } catch {
84
+ // Not resolvable from the app; it contributes nothing.
85
+ }
86
+ }
87
+ return roots
88
+ }
89
+
90
+ function list(value, what, where) {
91
+ if (value === undefined) return []
92
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string' || !entry)) {
93
+ throw new Error(`${where}: ${what} must be a list of strings`)
94
+ }
95
+ return value
96
+ }
97
+
98
+ function inside(root, relative, where) {
99
+ if (path.isAbsolute(relative) || relative.split(/[\\/]/).includes('..')) throw new Error(`${where}: ${relative} must stay inside the package`)
100
+ return path.join(root, relative)
101
+ }
102
+
103
+ function mustExist(file, where) {
104
+ if (!fs.existsSync(file)) throw new Error(`${where}: ${file} does not exist`)
105
+ return file
106
+ }
107
+
108
+ // Runs a package's library build once per package version, target and script.
109
+ function buildOutputs(root, manifest, platform, build, where, log) {
110
+ const command = list(build.command, 'build.command', where).map((part) => part.replaceAll('{platform}', platform))
111
+ if (!command.length) throw new Error(`${where}: build.command is empty`)
112
+ const script = mustExist(inside(root, command[0], where), where)
113
+ const libraries = list(build.libraries, 'build.libraries', where)
114
+ const resources = list(build.resources, 'build.resources', where)
115
+ const key = crypto.createHash('sha256').update(fs.readFileSync(script)).update(JSON.stringify(command)).digest('hex').slice(0, 12)
116
+ const cacheRoot = process.env.GEA_NATIVE_CACHE || path.join(os.homedir(), '.geastack', 'cache', 'native')
117
+ const out = path.join(cacheRoot, `${manifest.name.replace(/[\\/]/g, '+')}@${manifest.version || '0'}`, `${platform}-${key}`)
118
+ const outputs = [...libraries, ...resources].map((file) => inside(out, file, where))
119
+ if (outputs.some((file) => !fs.existsSync(file))) {
120
+ log(`[gea] building ${libraries.join(', ')} for ${platform} from ${manifest.name} (once; cached in ${out})`)
121
+ const runner = /\.sh$/.test(script) ? ['bash', [script, ...command.slice(1), '--out', out]] : [script, [...command.slice(1), '--out', out]]
122
+ execFileSync(runner[0], runner[1], { cwd: root, stdio: ['ignore', 'inherit', 'inherit'] })
123
+ for (const file of outputs) mustExist(file, `${where} (after ${command[0]})`)
124
+ }
125
+ return {
126
+ libraries: libraries.map((file) => inside(out, file, where)),
127
+ resources: resources.map((file) => inside(out, file, where)),
128
+ }
129
+ }
130
+
131
+ export function readUikitNativePackages({ appRoot, moduleGraphPath, target, simulator = false, log = (line) => process.stderr.write(`${line}\n`) }) {
132
+ const result = { sources: [], includeDirs: [], frameworks: [], systemLibraries: [], defines: [], libraries: [], resources: [], packages: [] }
133
+ const appReal = fs.realpathSync(appRoot)
134
+ for (const root of [...usedPackageRoots(appRoot, moduleGraphPath)].sort()) {
135
+ if (root === appReal) continue
136
+ const descriptorFile = path.join(root, 'gea-native.json')
137
+ if (!fs.existsSync(descriptorFile)) continue
138
+ const descriptor = readJson(descriptorFile)
139
+ if (!descriptor) throw new Error(`${descriptorFile} is not readable JSON`)
140
+ const section = descriptor[target]
141
+ if (!section) continue
142
+ const manifest = readJson(path.join(root, 'package.json')) || {}
143
+ const where = `${manifest.name || root} gea-native.json (${target})`
144
+ result.packages.push(manifest.name || root)
145
+ for (const file of list(section.sources, 'sources', where)) result.sources.push(mustExist(inside(root, file, where), where))
146
+ for (const dir of list(section.includeDirs, 'includeDirs', where)) result.includeDirs.push(mustExist(inside(root, dir, where), where))
147
+ for (const file of list(section.libraries, 'libraries', where)) result.libraries.push(mustExist(inside(root, file, where), where))
148
+ for (const file of list(section.resources, 'resources', where)) result.resources.push(mustExist(inside(root, file, where), where))
149
+ result.frameworks.push(...list(section.frameworks, 'frameworks', where))
150
+ for (const name of list(section.systemLibraries, 'systemLibraries', where)) {
151
+ if (!/^[A-Za-z][A-Za-z0-9_.+-]*$/.test(name)) throw new Error(`${where}: invalid system library ${name}`)
152
+ result.systemLibraries.push(name)
153
+ }
154
+ for (const [name, value] of Object.entries(section.defines || {})) {
155
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error(`${where}: invalid define ${name}`)
156
+ result.defines.push(value === true || value === '' ? name : `${name}=${value}`)
157
+ }
158
+ if (section.build) {
159
+ const built = buildOutputs(root, manifest, simulator ? `${target}-simulator` : target, section.build, where, log)
160
+ result.libraries.push(...built.libraries)
161
+ result.resources.push(...built.resources)
162
+ }
163
+ }
164
+ for (const key of Object.keys(result)) result[key] = [...new Set(result[key])]
165
+ return result
166
+ }
@@ -546,6 +546,16 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
546
546
 
547
547
  [self tick];
548
548
  [self startFrameTimer];
549
+ // GEA_MACOS_FULLSCREEN=1 starts fullscreen. With GEA_MACOS_VSYNC=0 this is
550
+ // the uncapped arm: a windowed CAMetalLayer gets drawables back only as the
551
+ // compositor runs, a fullscreen one presents directly.
552
+ if (const char *fullscreen = std::getenv("GEA_MACOS_FULLSCREEN"); fullscreen && std::strcmp(fullscreen, "1") == 0) {
553
+ self.window.collectionBehavior |= NSWindowCollectionBehaviorFullScreenPrimary;
554
+ NSWindow *window = self.window;
555
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 2), dispatch_get_main_queue(), ^{
556
+ if (!(window.styleMask & NSWindowStyleMaskFullScreen)) [window toggleFullScreen:nil];
557
+ });
558
+ }
549
559
  }
550
560
 
551
561
  - (void)startFrameTimer
@@ -555,7 +565,11 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
555
565
  #endif
556
566
  if (self.frameTimer) return;
557
567
  const BOOL thermalrightTarget = gea::macos::thermalright::enabled();
558
- if (!thermalrightTarget) {
568
+ // GEA_MACOS_VSYNC=0 drops the display-link cadence for the fast timer, so a
569
+ // renderer presenting with swap interval 0 runs uncapped (benchmarking).
570
+ const char *vsync = std::getenv("GEA_MACOS_VSYNC");
571
+ const BOOL uncapped = vsync && std::strcmp(vsync, "0") == 0;
572
+ if (!thermalrightTarget && !uncapped) {
559
573
  if (@available(macOS 14.0, *)) {
560
574
  if (self.frameDisplayLink) return;
561
575
  // A timer cannot express the desired display refresh rate. The
@@ -581,7 +595,16 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
581
595
  repeats:YES
582
596
  block:^(NSTimer *t) {
583
597
  (void)t;
584
- [weakSelf tick];
598
+ if (!uncapped) {
599
+ [weakSelf tick];
600
+ return;
601
+ }
602
+ // The run loop fires even a 1/960 s timer only ~120 times a second, so
603
+ // uncapped, each fire runs frames back to back for up to ~6 ms and then
604
+ // returns so input and window events are still serviced.
605
+ const auto burstEnd = std::chrono::steady_clock::now() + std::chrono::milliseconds(6);
606
+ do [weakSelf tick];
607
+ while (std::chrono::steady_clock::now() < burstEnd);
585
608
  }];
586
609
  self.frameTimer.tolerance = thermalrightTarget ? 0.001 : 0.0;
587
610
  [[NSRunLoop currentRunLoop] addTimer:self.frameTimer forMode:NSRunLoopCommonModes];