@geastack/apple 0.2.26 → 0.2.28

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/README.md CHANGED
@@ -10,22 +10,31 @@ npm install @geastack/apple
10
10
 
11
11
  ## Building an app
12
12
 
13
- The `gea` CLI drives the targets:
13
+ The `gea` CLI drives the targets. It is a separate package: install
14
+ `@geastack/cli` in the app too (0.1.110 or later for tvOS), and declare each
15
+ target in the app's `package.json`, for example
16
+ `"gea": { "targets": { "macos": true, "ios": true, "tvos": true } }`. From the
17
+ app folder:
14
18
 
15
19
  ```sh
16
- gea build --target macos
17
- gea build --target ios
18
- gea build --target tvos
20
+ npm install --save-dev @geastack/cli
21
+ npx gea build --target macos
22
+ npx gea build --target ios
23
+ npx gea build --target tvos
19
24
  ```
20
25
 
21
26
  The target build scripts can also be run directly from an app directory that
22
- has the GeaStack packages installed:
27
+ has the GeaStack packages (including `@geastack/cli`) installed. Run this way
28
+ they do not receive the app's `gea.targets.<target>.build` configuration, and
29
+ `build-ios.sh` boots, installs and launches the app on a simulator or device
30
+ after building, like `gea run`; prefix `GEA_IOS_SKIP_LAUNCH=1` to stop after
31
+ the build, which is what `gea build` does:
23
32
 
24
33
  ```sh
25
34
  node_modules/@geastack/apple/targets/macos/build-macos.sh my-app
26
- node_modules/@geastack/apple/targets/ios/build-ios.sh my-app simulator
35
+ GEA_IOS_SKIP_LAUNCH=1 node_modules/@geastack/apple/targets/ios/build-ios.sh my-app simulator
27
36
  GEA_IOS_DEVELOPMENT_TEAM=ABCDE12345 node_modules/@geastack/apple/targets/ios/build-ios.sh my-app device
28
- node_modules/@geastack/apple/targets/ios/build-ios.sh my-app simulator tvos
37
+ GEA_IOS_SKIP_LAUNCH=1 node_modules/@geastack/apple/targets/ios/build-ios.sh my-app simulator tvos
29
38
  ```
30
39
 
31
40
  Requires Xcode with the macOS, iOS and tvOS SDKs you target. Each target directory has its own
@@ -138,7 +147,8 @@ string on success. A located occurrence must lie within a week of its
138
147
  `occurrenceDate`.
139
148
 
140
149
  macOS ends a process that asks for calendar access without a usage
141
- description. Add both keys to `apps/<id>/macos.json`; its optional `infoPlist`
150
+ description. Add both keys to `macos.json` in the app folder (next to its
151
+ `package.json`); its optional `infoPlist`
142
152
  object is merged over the shared `Info.plist` template:
143
153
 
144
154
  ```json
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/apple",
3
- "version": "0.2.26",
3
+ "version": "0.2.28",
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": {
@@ -116,8 +116,8 @@
116
116
  },
117
117
  "dependencies": {
118
118
  "@geastack/compiler": "^1.0.34",
119
- "@geastack/core": "^0.1.52",
120
- "@geastack/elements": "^0.1.6",
119
+ "@geastack/core": "^0.1.57",
120
+ "@geastack/elements": "^0.1.7",
121
121
  "@geastack/engine": "^0.1.23",
122
122
  "@geastack/geaos": "^0.1.3",
123
123
  "@geastack/geatsc-plugin-apple-native": "^0.1.4",
@@ -1,9 +1,18 @@
1
1
  # iOS target
2
2
 
3
- Build a gea-embedded JSX app as a native UIKit app.
3
+ Build a Gea JSX app as a native UIKit app.
4
4
 
5
- From an app that depends on `@geastack/apple` (every iOS example does, and
6
- `gea create --targets ios` adds it), the CLI drives this target:
5
+ The app needs `@geastack/apple` and `@geastack/cli` (0.1.110 or later for tvOS)
6
+ in its own dependencies and `"ios": true` under `gea.targets` in its
7
+ `package.json`; `npx create-geastack my-app --targets ios` sets up all three,
8
+ and for an existing app:
9
+
10
+ ```bash
11
+ npm install @geastack/apple
12
+ npm install --save-dev @geastack/cli
13
+ ```
14
+
15
+ From the app folder, the CLI drives this target:
7
16
 
8
17
  ```bash
9
18
  npx gea build --target ios # simulator .app, no launch
@@ -12,11 +21,15 @@ npx gea run --target ios # build, install and launch on a simu
12
21
  npx gea run --target ios --mode device # build, sign, install and launch on an iPhone
13
22
  ```
14
23
 
15
- The same script can be run directly from the app folder; the CLI passes the
16
- app id and destination through unchanged:
24
+ The CLI runs `build-ios.sh <app-id> <simulator|device> [tvos]` from the
25
+ installed package, with `GEA_IOS_SKIP_LAUNCH=1` for `gea build` and the app's
26
+ build configuration from `gea.targets.ios`. The script can also be run
27
+ directly from the app folder; it then installs and launches the app after
28
+ building unless `GEA_IOS_SKIP_LAUNCH=1` is set, and does not apply the
29
+ `gea.targets.ios.build` settings:
17
30
 
18
31
  ```bash
19
- node_modules/@geastack/apple/targets/ios/build-ios.sh <app-id> simulator
32
+ GEA_IOS_SKIP_LAUNCH=1 node_modules/@geastack/apple/targets/ios/build-ios.sh <app-id> simulator
20
33
  ```
21
34
 
22
35
  The script resolves `@geastack/core`, `@geastack/compiler`, the apple-native
@@ -39,7 +52,7 @@ GEA_IOS_DEVELOPMENT_TEAM=ABCDE12345 npx gea run --target ios --mode device
39
52
  To see the automatically detected team id:
40
53
 
41
54
  ```bash
42
- targets/ios/detect-development-team.mjs
55
+ node node_modules/@geastack/apple/targets/ios/detect-development-team.mjs
43
56
  ```
44
57
 
45
58
  Signed device builds auto-pick an attached iPhone with Developer Mode enabled,
@@ -63,18 +76,20 @@ the source of truth.
63
76
  ## tvOS
64
77
 
65
78
  Apps that declare `gea.targets.tvos` can use the shared UIKit host on tvOS 17
66
- or later. Install the tvOS platform in Xcode's Components settings. From the
67
- Geastack examples project, run the JSX demo on an Apple TV simulator:
79
+ or later. Install the tvOS platform in Xcode's Components settings. The app
80
+ needs the same `@geastack/apple` and `@geastack/cli` dependencies as on iOS
81
+ (the `three-tvos` example lists both). From the app folder, run it on an Apple
82
+ TV simulator:
68
83
 
69
84
  ```sh
70
- gea run --target tvos --app bouncing-balls-jsx
85
+ npx gea run --target tvos
71
86
  ```
72
87
 
73
88
  For a physical Apple TV, pair it with Xcode over the local network and use an
74
89
  Apple development team configured for the device:
75
90
 
76
91
  ```sh
77
- GEA_IOS_DEVELOPMENT_TEAM=ABCDE12345 gea run --target tvos --mode device --app bouncing-balls-jsx
92
+ GEA_IOS_DEVELOPMENT_TEAM=ABCDE12345 npx gea run --target tvos --mode device
78
93
  ```
79
94
 
80
95
  Use `gea build` with the same options to generate the Xcode project and build
@@ -1,6 +1,6 @@
1
1
  # macOS target
2
2
 
3
- Build a gea-embedded app as a native Cocoa Mac app — `<Button>` becomes
3
+ Build a Gea app as a native Cocoa Mac app — `<Button>` becomes
4
4
  `NSButton`, `<Text>` becomes `NSTextField`, `<View>` becomes `NSView`,
5
5
  `<Image>` becomes `NSImageView`, `<canvas>` is a custom `NSView` backed by
6
6
  CoreGraphics, `<virtual-list>` is `NSScrollView`. The flex layout engine
@@ -8,8 +8,20 @@ in `@geastack/engine`'s `ui/layout.cpp` computes frames; AppKit draws.
8
8
 
9
9
  ## Build
10
10
 
11
- targets/macos/build-macos.sh <app-id>
12
- open dist/macos/<app-id>/<AppName>.app
11
+ The app needs `@geastack/apple` and `@geastack/cli` in its dependencies and
12
+ `"macos": true` under `gea.targets` in its `package.json`. From the app folder:
13
+
14
+ npx gea run --target macos
15
+
16
+ builds the app and opens it. `npx gea build --target macos` builds only; the
17
+ bundle is `dist/macos/<app-id>/<AppName>.app`. `gea run --target macos` needs
18
+ `@geastack/cli` 0.1.117 or later; with an older CLI, build and then
19
+ `open dist/macos/<app-id>/<AppName>.app`.
20
+
21
+ `gea build --target macos` runs this package's `build-macos.sh <app-id>` with
22
+ the app's build configuration. The script can also be run directly from the
23
+ app folder as `node_modules/@geastack/apple/targets/macos/build-macos.sh
24
+ <app-id>`.
13
25
 
14
26
  ## Where the build writes
15
27
 
@@ -24,49 +36,22 @@ Output does not go under the package because the package lives in the app's
24
36
  `node_modules`, which npm replaces on reinstall. Set `GEA_MACOS_OUTPUT_DIR` to
25
37
  put the whole tree elsewhere.
26
38
 
27
- `<app-id>` is currently any name; when no generated app is present under
28
- `dist/macos/.generated/<app-id>/` the build falls back to a built-in
29
- Phase B smoke app (`macos_smoke_app.cpp`) that exercises View / Text /
30
- Button / event dispatch. geatsc-compiled apps go into
31
- `dist/macos/.generated/` and supersede the smoke automatically — the
32
- JSX → C++ pipeline for the macOS target is a follow-up.
33
-
34
- ## Hard-muted builds must prove artifact provenance
35
-
36
- For any verification that must not produce audio, configure the final native
37
- mute source and its literal on the build itself:
38
-
39
- ```sh
40
- GEA_MACOS_HARD_MUTE_SOURCE=/absolute/path/to/the/committed/native/audio_source.mm \
41
- GEA_MACOS_HARD_MUTE_GATE=THE_NATIVE_MUTE_ENVIRONMENT_LITERAL \
42
- targets/macos/build-macos.sh <app-id>
43
- ```
44
-
45
- Both variables are required together. After code signing, the build writes
46
- `dist/<app-id>/build/hard-mute-artifact-provenance.json` and statically proves:
47
-
48
- - the selected source is the committed blob at the recorded dependency revision;
49
- - exactly one linked object depends on that source and contains the gate;
50
- - `link.sig` records that exact object;
51
- - source, translation unit, depfile, link signature, object, and executable
52
- SHA-256 values still match; and
53
- - the signed executable contains the same gate.
54
-
55
- Immediately before launch, rerun the no-launch check against the exact binary:
56
-
57
- ```sh
58
- node targets/macos/preflight-hard-muted-artifact.mjs verify \
59
- --manifest /absolute/path/to/build/hard-mute-artifact-provenance.json \
60
- --executable "/absolute/path/to/App.app/Contents/MacOS/App" \
61
- --source /absolute/path/to/the/committed/native/audio_source.mm \
62
- --gate THE_NATIVE_MUTE_ENVIRONMENT_LITERAL
63
- ```
64
-
65
- Do not launch unless this prints
66
- `PASS artifact-static-hard-mute-gate=present`. The checker reads files and Git
67
- metadata only; it does not execute the app or open an audio device. Any missing
68
- manifest, gate, changed dependency revision, or changed source/object/executable
69
- fails closed.
39
+ The build compiles the app's entry through geatsc into
40
+ `dist/macos/.generated/<app-id>/` and links the generated C++ into the bundle;
41
+ a geatsc failure for a resolved app fails the build. Only when `<app-id>`
42
+ resolves to no app with an entry file does the build fall back to the built-in
43
+ smoke app (`main/macos_smoke_app.cpp`), which exercises View / Text / Button /
44
+ event dispatch.
45
+
46
+ ## Hard-muted builds
47
+
48
+ Setting `GEA_MACOS_HARD_MUTE_SOURCE` (absolute path to the committed native
49
+ audio source) and `GEA_MACOS_HARD_MUTE_GATE` (the mute literal it contains)
50
+ together makes the build record and check that the signed executable was built
51
+ from that source with the gate present. It writes
52
+ `dist/macos/<app-id>/build/hard-mute-artifact-provenance.json`;
53
+ `preflight-hard-muted-artifact.mjs verify` re-checks a binary against it
54
+ without launching it. Setting only one of the two variables is an error.
70
55
 
71
56
  ## Architecture
72
57
 
@@ -93,11 +78,17 @@ display list, so other targets keep calling `refresh()` unchanged.
93
78
 
94
79
  ## Frame loop
95
80
 
96
- `macos_main.mm` schedules a 60Hz `NSTimer` on `NSRunLoopCommonModes` so
97
- the loop keeps firing during live window-resize and other event-
98
- tracking modes. Each tick:
99
-
100
- 1. `gea_embedded_app_frame(timestampMs)` lets the app update state
81
+ `main/macos_main.mm` drives frames from the window's `CADisplayLink` on
82
+ macOS 14 and later, at the screen's maximum refresh rate (following the window
83
+ between displays). On older macOS, or when the app's window config sets
84
+ `"vsync": false`, it uses a fast `NSTimer` instead; with `vsync: false` frames
85
+ run uncapped. Both are scheduled on `NSRunLoopCommonModes` so the loop keeps
86
+ firing during live window-resize and other event-tracking modes. The window
87
+ config is `macos.json` in the app folder overlaid with
88
+ `gea.targets.macos.window` from its `package.json` (`width`, `height`,
89
+ `vsync`, `fullscreen`, ...), bundled as `Resources/window.json`. Each tick:
90
+
91
+ 1. `Application::frame(timestampMs)` lets the app update state
101
92
  2. Force `style.width/height` on the mounted root to the current window
102
93
  content size — this is the macOS convention that makes the root
103
94
  viewport track resize automatically
@@ -124,8 +115,15 @@ runs the measurement harness (offline render, RMS + measured frequency);
124
115
  `GEA_AUDIO_CAPTURE_RAW=<path>` captures an app run for
125
116
  `targets/shared/analyze-audio-capture.mjs`.
126
117
 
127
- Stubbed for v1: WiFi (`macos_wifi`), BLE (`macos_ble`), IMU (`macos_imu`)
128
- — present only as link-satisfying no-ops; apps that depend on these will
129
- run but those calls return inert values. Custom font bundling, code
130
- signing with entitlements, notarisation, and the JSX → C++ pipeline for
131
- this target are follow-ups.
118
+ Also implemented in `main/`: HTTP(S) `fetch` over `NSURLSession`
119
+ (`macos_network.mm`), battery level from IOKit power sources and pointer
120
+ input as touch (`macos_sensors.cpp`), timers (`macos_timers.mm`), launching
121
+ other apps' bundles (`macos_app_platform.mm`), and the `runDeviceCommand`
122
+ shell escape hatch (`macos_device_control.mm`).
123
+
124
+ Stubbed in `main/macos_sensors.cpp`: the accelerometer/gyroscope (tilt 0,
125
+ gravity on Z) and the embedded memory diagnostics (all zeros).
126
+ `main/macos_display.mm` keeps the framebuffer display inert because AppKit
127
+ draws. `main/` has no WiFi or Bluetooth backend. Code signing with
128
+ entitlements and notarisation are not done by the build; development bundles
129
+ are signed ad hoc.
@@ -396,7 +396,7 @@ resolve_app_dir() {
396
396
  }
397
397
 
398
398
  # Info.plist comes from the shared template plus the optional `infoPlist`
399
- # object of apps/<id>/macos.json (usage descriptions and other per-app keys).
399
+ # object of the app's macos.json (usage descriptions and other per-app keys).
400
400
  INFO_PLIST_TMP="$BUILD_DIR/Info.plist.tmp.$$"
401
401
  sed -e "s/@APP_EXEC@/$APP_EXEC/g" \
402
402
  -e "s/@APP_ID@/$APP_ID/g" \
@@ -994,6 +994,7 @@ case "${GEA_MACOS_THERMALRIGHT_PRODUCT_ID:-}" in
994
994
  esac
995
995
  if [[ "$THERMALRIGHT_DISPLAY_TARGET" == "0" ]]; then
996
996
  CXX_DEFINES+=(-DGEA_EMBEDDED_PIXEL_FORMAT=1 -DGEA_CSS_FONT_STRETCH=1) # RGBA8888 and native variable-font style for AppKit
997
+ CXX_DEFINES+=(-DGEA_EMBEDDED_HAS_GENERATED_FONTS=1) # Enable retained text rasterization via the runtime TTF hooks
997
998
  fi
998
999
  if [[ "$THERMALRIGHT_DISPLAY_TARGET" == "1" ]]; then
999
1000
  THERMALRIGHT_WIDTH="${GEA_MACOS_THERMALRIGHT_WIDTH:-$THERMALRIGHT_DEFAULT_WIDTH}"
@@ -1124,6 +1125,8 @@ if [[ -n "$SINGLE_APP_DIR" ]]; then
1124
1125
  *) full_src="$SINGLE_APP_DIR/$native_src" ;;
1125
1126
  esac
1126
1127
  [[ -f "$full_src" ]] || continue
1128
+ # Generated host calls can include headers beside their native source.
1129
+ INCLUDES+=(-iquote "${full_src%/*}")
1127
1130
  case "$full_src" in
1128
1131
  *.c) C_SOURCES+=("$full_src") ;;
1129
1132
  *.m|*.mm) MM_SOURCES+=("$full_src") ;;
@@ -1997,6 +2000,13 @@ while IFS= read -r library; do [[ -z "$library" ]] || LINK_FRAMEWORKS+=("-l$libr
1997
2000
  node "$GEA_CLI" apps sync-native-resources "$APP_ID" --target macos --output "$RES_DIR" > "$BUILD_DIR/native-resources.json"
1998
2001
  if [[ "$(node -e 'process.stdout.write(String(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).changed))' "$BUILD_DIR/native-resources.json")" == "true" ]]; then BUNDLE_CONTENT_CHANGED=1; fi
1999
2002
 
2003
+ # These weak program hooks are emitted only for programs with cycle-collectable
2004
+ # values. ld64 requires named exceptions for unresolved executable symbols.
2005
+ MACOS_LINK_FLAGS=(
2006
+ -Wl,-no_deduplicate
2007
+ -Wl,-U,_gea_cycle_collection_defer_begin
2008
+ -Wl,-U,_gea_cycle_collection_defer_end
2009
+ )
2000
2010
  LINK_OUTPUT="$MACOS_DIR/$APP_EXEC"
2001
2011
  LINK_OUTPUT_TMP="$LINK_OUTPUT.tmp.$$"
2002
2012
  LINK_SIGNATURE_FILE="$BUILD_DIR/link.sig"
@@ -2005,7 +2015,7 @@ LINK_SIGNATURE_TMP="$LINK_SIGNATURE_FILE.tmp.$$"
2005
2015
  printf 'compiler=%s\n' "$MACOS_COMPILER_VERSION"
2006
2016
  printf 'opt=%s\n' "$GEA_MACOS_OPT_LEVEL"
2007
2017
  printf 'debug=%s\n' "${GEA_MACOS_DEBUG_INFO:-}"
2008
- printf 'link=%s\n' -Wl,-no_deduplicate
2018
+ printf 'link=%s\n' "${MACOS_LINK_FLAGS[@]}"
2009
2019
  printf 'framework=%s\n' "${LINK_FRAMEWORKS[@]}"
2010
2020
  printf 'object=%s\n' "${OBJ_FILES[@]}"
2011
2021
  for library in ${APP_NATIVE_LIBRARIES[@]+"${APP_NATIVE_LIBRARIES[@]}"}; do shasum -a 256 "$library"; done
@@ -2032,7 +2042,7 @@ if (( LINK_NEEDED != 0 )); then
2032
2042
  # entry address (CallableObject::callWithReceiver finds a method's receiver
2033
2043
  # check by it), so a folded method template ran its twin's check.
2034
2044
  macos_run_tracked_child clang++ -std=c++20 -ObjC++ -fobjc-arc "$GEA_MACOS_OPT_LEVEL" ${GEA_MACOS_DEBUG_INFO} \
2035
- -Wl,-no_deduplicate \
2045
+ "${MACOS_LINK_FLAGS[@]}" \
2036
2046
  "${LINK_FRAMEWORKS[@]}" \
2037
2047
  "${OBJ_FILES[@]}" \
2038
2048
  ${APP_NATIVE_LIBRARIES[@]+"${APP_NATIVE_LIBRARIES[@]}"} \
@@ -2047,8 +2057,8 @@ timing_mark link
2047
2057
 
2048
2058
  # Convert the app icon only when its resolved source, manifest metadata, or the
2049
2059
  # icon tooling changed. Ten `sips` subprocesses made this the largest historical
2050
- # no-op phase.
2051
- if [[ -n "$APP_META" ]]; then
2060
+ # no-op phase. A prerender bundle is run directly and needs no Finder icon.
2061
+ if [[ -n "$APP_META" && "${GEA_MACOS_PRERENDER:-0}" != "1" ]]; then
2052
2062
  ICON_OUTPUT="$RES_DIR/AppIcon.icns"
2053
2063
  ICON_INPUT_SIGNATURE_FILE="$BUILD_DIR/AppIcon.inputs"
2054
2064
  ICON_INPUT_SIGNATURE="$(node "$GEA_CLI" apps apple-icons "$APP_ID" --platform macos --signature)"
@@ -2072,7 +2082,7 @@ fi
2072
2082
  # Copy any TTF / OTF referenced by @font-face in CSS — for resident-app
2073
2083
  # builds we walk every resident's app dir so fonts used by other tiles
2074
2084
  # are also bundled.
2075
- if [[ "$MACOS_PIPELINE_CACHE" == "0" ]]; then
2085
+ if [[ "$MACOS_PIPELINE_CACHE" == "0" && "${GEA_MACOS_PRERENDER:-0}" != "1" ]]; then
2076
2086
  FONTS_OUT="$RES_DIR/Fonts"
2077
2087
  mkdir -p "$FONTS_OUT"
2078
2088
  APP_DIRS_FOR_FONTS=()
@@ -2128,7 +2138,7 @@ done
2128
2138
 
2129
2139
  # Per-app window config — the macOS main reads window.json out of Resources/
2130
2140
  # at launch to pick up size, transparent title bar, dark appearance, etc.
2131
- # Source is apps/<id>/macos.json overlaid with gea.targets.macos.window from
2141
+ # Source is the app's macos.json overlaid with gea.targets.macos.window from
2132
2142
  # the app's package.json (window-config.mjs), written as window.json so the runtime path is stable
2133
2143
  # regardless of which app id produced it.
2134
2144
  APP_DIR_FOR_CONFIG="$(resolve_app_dir "$APP_ID")"
@@ -25,6 +25,9 @@ NSFont *fontForId(int fontId, int sizePx, int weight, int stretch);
25
25
  // after the app bundle is known.
26
26
  int registerCustomTtfDirectory(NSString *directoryPath);
27
27
 
28
+ // Match software glyph layout and paint during offscreen capture.
29
+ void useSoftwareTextMeasurement();
30
+
28
31
  // Picks the right NSLineBreakMode for `text` rendered in `font` within
29
32
  // `maxWidth` points. Returns word-wrap when every space-separated chunk fits
30
33
  // on a line by itself, otherwise char-wrap so that a long unbreakable run
@@ -9,8 +9,10 @@
9
9
  #include <cmath>
10
10
  #include <cstdint>
11
11
  #include <cstring>
12
+ #include <memory>
12
13
  #include <mutex>
13
14
  #include <string>
15
+ #include <sys/stat.h>
14
16
  #include <unordered_map>
15
17
  #include <utility>
16
18
  #include <vector>
@@ -72,9 +74,21 @@ NSString *familyForId(int id)
72
74
  // the process lifetime: the rasterizer keeps stbtt_fontinfo pointers into
73
75
  // them across atlas rebuilds. Construct-on-first-use for the same dyld-
74
76
  // initializer-ordering reason as FamilyRegistry above.
77
+ using FontBytes = std::shared_ptr<const std::vector<std::uint8_t>>;
78
+ using FontNames = std::unordered_map<std::string, FontBytes>;
79
+
80
+ struct FontFile {
81
+ struct stat stamp;
82
+ FontBytes bytes;
83
+ };
84
+
75
85
  struct TtfByteRegistry {
76
86
  std::mutex lock;
77
- std::unordered_map<std::string, std::vector<std::uint8_t>> byFamily;
87
+ FontNames byFamily;
88
+ FontNames byAlias;
89
+ FontNames documentFonts;
90
+ FontNames pendingFonts;
91
+ std::unordered_map<std::string, FontFile> files;
78
92
  };
79
93
 
80
94
  TtfByteRegistry &ttfByteRegistry()
@@ -90,25 +104,30 @@ std::string lowercased(const std::string &value)
90
104
  return out;
91
105
  }
92
106
 
93
- void registerTtfBytesForFamily(NSString *path)
107
+ bool softwareTextMeasurement = false;
108
+
109
+ bool registerTtfBytesForFamily(NSString *path, NSArray<NSString *> *aliases)
94
110
  {
95
111
  NSData *data = [NSData dataWithContentsOfFile:path];
96
- if (data.length == 0) return;
112
+ if (data.length == 0) return false;
97
113
  CTFontDescriptorRef desc = CTFontManagerCreateFontDescriptorFromData((__bridge CFDataRef)data);
98
- if (!desc) return;
114
+ if (!desc) return false;
99
115
  CFStringRef family = (CFStringRef)CTFontDescriptorCopyAttribute(desc, kCTFontFamilyNameAttribute);
100
116
  CFRelease(desc);
101
- if (!family) return;
117
+ if (!family) return false;
102
118
  char buf[256] = {0};
103
119
  const bool ok = CFStringGetCString(family, buf, sizeof(buf), kCFStringEncodingUTF8);
104
120
  CFRelease(family);
105
- if (!ok || !buf[0]) return;
121
+ if (!ok || !buf[0]) return false;
106
122
  const auto *bytes = static_cast<const std::uint8_t *>(data.bytes);
107
123
  TtfByteRegistry &registry = ttfByteRegistry();
108
124
  std::scoped_lock guard(registry.lock);
109
125
  // First face wins (e.g. Inter-Regular before other weights of the family):
110
126
  // the runtime rasterizer keys on the family alone.
111
- registry.byFamily.emplace(lowercased(buf), std::vector<std::uint8_t>(bytes, bytes + data.length));
127
+ auto font = std::make_shared<const std::vector<std::uint8_t>>(bytes, bytes + data.length);
128
+ registry.byFamily.emplace(lowercased(buf), font);
129
+ for (NSString *alias in aliases) registry.byAlias.emplace(alias.UTF8String, font);
130
+ return true;
112
131
  }
113
132
 
114
133
  } // namespace
@@ -122,10 +141,16 @@ const std::uint8_t *runtimeTtfBytesForFamilyId(int familyId, unsigned long *leng
122
141
  if (!family || family.length == 0) return nullptr;
123
142
  TtfByteRegistry &registry = ttfByteRegistry();
124
143
  std::scoped_lock guard(registry.lock);
125
- const auto it = registry.byFamily.find(lowercased(family.UTF8String));
126
- if (it == registry.byFamily.end()) return nullptr;
127
- if (length) *length = it->second.size();
128
- return it->second.data();
144
+ const auto key = lowercased(family.UTF8String);
145
+ const auto document = registry.documentFonts.find(key);
146
+ const auto alias = registry.byAlias.find(key);
147
+ const auto fallback = registry.byFamily.find(key);
148
+ const auto *font = document != registry.documentFonts.end() ? document->second.get()
149
+ : alias != registry.byAlias.end() ? alias->second.get()
150
+ : fallback != registry.byFamily.end() ? fallback->second.get() : nullptr;
151
+ if (!font) return nullptr;
152
+ if (length) *length = font->size();
153
+ return font->data();
129
154
  }
130
155
 
131
156
  static NSFont *self_resolveFont(int fontId, int sizePx, int weight, int stretch)
@@ -186,18 +211,35 @@ NSFont *fontForId(int fontId, int sizePx, int weight, int stretch)
186
211
 
187
212
  NSFont *fontForId(int fontId, int sizePx) { return fontForId(fontId, sizePx, 400, 1000); }
188
213
 
214
+ void useSoftwareTextMeasurement()
215
+ {
216
+ softwareTextMeasurement = true;
217
+ }
218
+
189
219
  int registerCustomTtfDirectory(NSString *directoryPath)
190
220
  {
191
221
  NSFileManager *fm = [NSFileManager defaultManager];
192
222
  BOOL isDir = NO;
193
223
  if (![fm fileExistsAtPath:directoryPath isDirectory:&isDir] || !isDir) return 0;
194
224
  NSArray<NSString *> *entries = [fm contentsOfDirectoryAtPath:directoryPath error:nil];
225
+ NSString *aliasPath = [directoryPath.stringByDeletingLastPathComponent stringByAppendingPathComponent:@"font-aliases.json"];
226
+ NSData *aliasData = [NSData dataWithContentsOfFile:aliasPath];
227
+ NSDictionary *aliases = aliasData ? [NSJSONSerialization JSONObjectWithData:aliasData options:0 error:nil] : nil;
228
+ NSMutableDictionary<NSString *, NSMutableArray<NSString *> *> *aliasesByFile = [NSMutableDictionary dictionary];
229
+ if ([aliases isKindOfClass:NSDictionary.class]) {
230
+ for (NSString *alias in aliases) {
231
+ NSString *filename = aliases[alias];
232
+ if (![filename isKindOfClass:NSString.class]) continue;
233
+ if (!aliasesByFile[filename]) aliasesByFile[filename] = [NSMutableArray array];
234
+ [aliasesByFile[filename] addObject:alias];
235
+ }
236
+ }
195
237
  int count = 0;
196
238
  for (NSString *name in entries) {
197
239
  NSString *lower = name.lowercaseString;
198
240
  if (![lower hasSuffix:@".ttf"] && ![lower hasSuffix:@".otf"]) continue;
199
241
  NSString *path = [directoryPath stringByAppendingPathComponent:name];
200
- registerTtfBytesForFamily(path);
242
+ registerTtfBytesForFamily(path, aliasesByFile[name]);
201
243
  CFErrorRef err = NULL;
202
244
  CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
203
245
  if (CTFontManagerRegisterFontsForURL(url, kCTFontManagerScopeProcess, &err)) {
@@ -213,6 +255,58 @@ int registerCustomTtfDirectory(NSString *directoryPath)
213
255
  return count;
214
256
  }
215
257
 
258
+ extern "C" void gea_macos_begin_runtime_fonts()
259
+ {
260
+ auto &registry = ttfByteRegistry();
261
+ std::scoped_lock guard(registry.lock);
262
+ registry.pendingFonts.clear();
263
+ }
264
+
265
+ extern "C" bool gea_macos_register_runtime_font(const char *path, const char *family)
266
+ {
267
+ struct stat stamp{};
268
+ if (!family || !*family || stat(path, &stamp) != 0 || !S_ISREG(stamp.st_mode) ||
269
+ stamp.st_size <= 0 || stamp.st_size > 16 * 1024 * 1024) return false;
270
+ auto &registry = ttfByteRegistry();
271
+ std::scoped_lock guard(registry.lock);
272
+ const auto existing = registry.files.find(path);
273
+ FontBytes bytes;
274
+ if (existing != registry.files.end()) {
275
+ const auto &old = existing->second.stamp;
276
+ if (old.st_dev == stamp.st_dev && old.st_ino == stamp.st_ino &&
277
+ old.st_size == stamp.st_size && old.st_ctimespec.tv_sec == stamp.st_ctimespec.tv_sec &&
278
+ old.st_ctimespec.tv_nsec == stamp.st_ctimespec.tv_nsec) {
279
+ bytes = existing->second.bytes;
280
+ }
281
+ }
282
+ if (!bytes) {
283
+ NSString *filename = [NSString stringWithUTF8String:path];
284
+ NSData *data = filename ? [NSData dataWithContentsOfFile:filename] : nil;
285
+ if (data.length != static_cast<NSUInteger>(stamp.st_size)) return false;
286
+ CTFontDescriptorRef descriptor = CTFontManagerCreateFontDescriptorFromData((__bridge CFDataRef)data);
287
+ if (!descriptor) return false;
288
+ CFRelease(descriptor);
289
+ const auto *begin = static_cast<const std::uint8_t *>(data.bytes);
290
+ bytes = std::make_shared<const std::vector<std::uint8_t>>(begin, begin + data.length);
291
+ if (registry.files.size() >= 32) registry.files.clear();
292
+ registry.files.insert_or_assign(path, FontFile{stamp, bytes});
293
+ }
294
+ registry.pendingFonts.emplace(lowercased(family), bytes);
295
+ return true;
296
+ }
297
+
298
+ extern "C" void gea_macos_commit_runtime_fonts()
299
+ {
300
+ auto &registry = ttfByteRegistry();
301
+ std::scoped_lock guard(registry.lock);
302
+ if (registry.documentFonts != registry.pendingFonts) {
303
+ // The old tree is gone. Release glyph slots before dropping their byte buffers.
304
+ gea::framework::graphics::FontRegistry::invalidateRuntimeFonts();
305
+ registry.documentFonts.swap(registry.pendingFonts);
306
+ }
307
+ registry.pendingFonts.clear();
308
+ }
309
+
216
310
  } // namespace gea::macos
217
311
 
218
312
  // Strong overrides of the framework's weak font-lookup hooks for the AppKit
@@ -279,7 +373,7 @@ static bool measureNativeText(const char *text,
279
373
  int *outWidth,
280
374
  int *outHeight)
281
375
  {
282
- if (!outWidth || !outHeight) return false;
376
+ if (gea::macos::softwareTextMeasurement || !outWidth || !outHeight) return false;
283
377
  if (!text || !text[0]) {
284
378
  *outWidth = 0;
285
379
  *outHeight = 0;
@@ -1,6 +1,7 @@
1
1
  #import <Cocoa/Cocoa.h>
2
2
 
3
3
  #include "display.h"
4
+ #include "macos_prerender.h"
4
5
  #include "canvas.h"
5
6
  #include "host/display_orientation.h"
6
7
  #include "pixel.h"
@@ -29,6 +30,7 @@ int g_canvas_w = gea::platform::display::kWidth;
29
30
  int g_canvas_h = gea::platform::display::kHeight;
30
31
  int g_brightness = 100;
31
32
  std::uint8_t g_alpha = 255;
33
+ bool g_prerender = false;
32
34
  int g_flush_rows = 0;
33
35
  int g_flush_depth = 0;
34
36
  int g_flush_calls = 0;
@@ -43,13 +45,13 @@ void ensure_canvas()
43
45
 
44
46
  bool framebuffer_target()
45
47
  {
46
- return gea::macos::thermalright::enabled();
48
+ return g_prerender || gea::macos::thermalright::enabled();
47
49
  }
48
50
 
49
51
  void count_rect(int x0, int y0, int x1, int y1)
50
52
  {
51
- using gea::platform::display::kWidth;
52
- using gea::platform::display::kHeight;
53
+ const int kWidth = g_canvas_w;
54
+ const int kHeight = g_canvas_h;
53
55
  if (x0 < 0) x0 = 0;
54
56
  if (y0 < 0) y0 = 0;
55
57
  if (x1 >= kWidth) x1 = kWidth - 1;
@@ -60,7 +62,7 @@ void count_rect(int x0, int y0, int x1, int y1)
60
62
 
61
63
  void submit_full_frame()
62
64
  {
63
- if (!framebuffer_target()) return;
65
+ if (g_prerender || !framebuffer_target()) return;
64
66
  ensure_canvas();
65
67
  #if GEA_MACOS_THERMALRIGHT_DISPLAY_TARGET
66
68
  gea::macos::thermalright::submitRgb565(g_framebuffer,
@@ -71,6 +73,46 @@ void submit_full_frame()
71
73
 
72
74
  } // namespace
73
75
 
76
+ bool gea_macos_prepare_prerender(int width, int height)
77
+ {
78
+ if (!g_framebuffer || width != g_canvas_w || height != g_canvas_h) {
79
+ auto *pixels = static_cast<gea::framework::graphics::pixel::native_t *>(
80
+ std::calloc(static_cast<size_t>(width) * height, sizeof(*g_framebuffer)));
81
+ if (!pixels) return false;
82
+ std::free(g_framebuffer);
83
+ g_framebuffer = pixels;
84
+ g_canvas_w = width;
85
+ g_canvas_h = height;
86
+ }
87
+ g_prerender = true;
88
+ g_canvas.bindPixels(g_framebuffer, width, height);
89
+ g_canvas.setGlobalAlpha(255);
90
+ g_canvas.clear(0);
91
+ return true;
92
+ }
93
+
94
+ bool gea_macos_write_prerender_png(NSString *path)
95
+ {
96
+ NSBitmapImageRep *image = [[NSBitmapImageRep alloc]
97
+ initWithBitmapDataPlanes:nullptr pixelsWide:g_canvas_w pixelsHigh:g_canvas_h
98
+ bitsPerSample:8 samplesPerPixel:3 hasAlpha:NO isPlanar:NO
99
+ colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
100
+ if (!image) return false;
101
+ for (int y = 0; y < g_canvas_h; ++y) {
102
+ auto *row = image.bitmapData + y * image.bytesPerRow;
103
+ for (int x = 0; x < g_canvas_w; ++x) {
104
+ int r, g, b, a;
105
+ gea::framework::graphics::pixel::unpackNative8(
106
+ g_framebuffer[static_cast<size_t>(y) * g_canvas_w + x], &r, &g, &b, &a);
107
+ row[x * 3] = r;
108
+ row[x * 3 + 1] = g;
109
+ row[x * 3 + 2] = b;
110
+ }
111
+ }
112
+ NSData *png = [image representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
113
+ return [png writeToFile:path atomically:YES];
114
+ }
115
+
74
116
  namespace gea::platform::display {
75
117
 
76
118
  bool Display::init() { ensure_canvas(); return true; }
@@ -129,8 +171,8 @@ void Display::flushRectsRasterized(const DisplayFlushRect *rects, int count, Dis
129
171
  for (int i = 0; i < count; i++) {
130
172
  int x0 = std::max(0, rects[i].x0);
131
173
  int y0 = std::max(0, rects[i].y0);
132
- int x1 = std::min(kWidth - 1, rects[i].x1);
133
- int y1 = std::min(kHeight - 1, rects[i].y1);
174
+ int x1 = std::min(g_canvas_w - 1, rects[i].x1);
175
+ int y1 = std::min(g_canvas_h - 1, rects[i].y1);
134
176
  if (x0 > x1 || y0 > y1) continue;
135
177
  const int w = x1 - x0 + 1;
136
178
  const int h = y1 - y0 + 1;
@@ -138,7 +180,7 @@ void Display::flushRectsRasterized(const DisplayFlushRect *rects, int count, Dis
138
180
  raster(pixels.data(), w, h, x0, y0, user);
139
181
  for (int row = 0; row < h; row++) {
140
182
  for (int col = 0; col < w; ++col)
141
- g_framebuffer[static_cast<std::size_t>(y0 + row) * kWidth + x0 + col] = pixels[static_cast<std::size_t>(row) * w + col];
183
+ g_framebuffer[static_cast<std::size_t>(y0 + row) * g_canvas_w + x0 + col] = pixels[static_cast<std::size_t>(row) * w + col];
142
184
  }
143
185
  g_canvas.markDirty(x0, y0, x1, y1);
144
186
  }
@@ -158,8 +200,8 @@ bool Display::streamRect(int x, int y, int w, int h, DisplayStreamRasterFn raste
158
200
  if (!raster || w <= 0 || h <= 0) return false;
159
201
  int x0 = std::max(0, x);
160
202
  int y0 = std::max(0, y);
161
- int x1 = std::min(kWidth - 1, x + w - 1);
162
- int y1 = std::min(kHeight - 1, y + h - 1);
203
+ int x1 = std::min(g_canvas_w - 1, x + w - 1);
204
+ int y1 = std::min(g_canvas_h - 1, y + h - 1);
163
205
  if (x0 > x1 || y0 > y1) return true;
164
206
 
165
207
  const int rw = x1 - x0 + 1;
@@ -168,7 +210,7 @@ bool Display::streamRect(int x, int y, int w, int h, DisplayStreamRasterFn raste
168
210
  raster(pixels.data(), rw, rh, x0, y0, user);
169
211
  for (int row = 0; row < rh; row++) {
170
212
  for (int col = 0; col < rw; ++col)
171
- g_framebuffer[static_cast<std::size_t>(y0 + row) * kWidth + x0 + col] = pixels[static_cast<std::size_t>(row) * rw + col];
213
+ g_framebuffer[static_cast<std::size_t>(y0 + row) * g_canvas_w + x0 + col] = pixels[static_cast<std::size_t>(row) * rw + col];
172
214
  }
173
215
  g_canvas.markDirty(x0, y0, x1, y1);
174
216
  flush();
@@ -305,7 +347,7 @@ bool Display::present(const DisplayPresentCommand *commands, int command_count)
305
347
  void Display::setFlushConfig(int chunk_rows, int queue_depth) { g_flush_rows = chunk_rows; g_flush_depth = queue_depth; }
306
348
  int Display::flushChunkRows() { return g_flush_rows; }
307
349
  int Display::flushQueueDepth() { return g_flush_depth; }
308
- int Display::flushBufferBytes() { return kWidth * g_flush_rows * 2 * g_flush_depth; }
350
+ int Display::flushBufferBytes() { return g_canvas_w * g_flush_rows * 2 * g_flush_depth; }
309
351
 
310
352
  void Display::pushClip(int x, int y, int w, int h) { if (framebuffer_target()) canvas()->pushClip(x, y, w, h); }
311
353
  void Display::popClip() { if (framebuffer_target()) canvas()->popClip(); }
@@ -12,6 +12,7 @@ extern void gea_macos_debugger_start();
12
12
 
13
13
  #include "font_registry.h"
14
14
  #include "macos_native_shell.h"
15
+ #include "macos_prerender.h"
15
16
  #include "macos_renderer.h"
16
17
  #include "macos_background_test.h"
17
18
  #include "press_bridge.h"
@@ -45,6 +46,10 @@ namespace gea::macos { void installWifiDriver(); int nodeIdForView(NSView *view)
45
46
  #include "css/declarative.h"
46
47
  #include "css/engine.h"
47
48
  #include "display.h"
49
+ #if __has_include("platform/prerender_video.h")
50
+ #include "platform/prerender_video.h"
51
+ #define GEA_MACOS_PRERENDER_VIDEO 1
52
+ #endif
48
53
  #include "platform/file_cache.h"
49
54
  #if __has_include("resident_apps.h")
50
55
  #include "resident_apps.h"
@@ -60,10 +65,15 @@ namespace gea::macos { void installWifiDriver(); int nodeIdForView(NSView *view)
60
65
 
61
66
  #include <algorithm>
62
67
  #include <chrono>
68
+ #include <cmath>
63
69
  #include <cstdint>
64
70
  #include <cstdio>
65
71
  #include <cstdlib>
66
72
  #include <cstring>
73
+ #include <exception>
74
+ #include <iostream>
75
+ #include <string>
76
+ #include <unistd.h>
67
77
  #include "gea_appkit_host.h"
68
78
 
69
79
  extern "C" int gea_embedded_now_ms(void);
@@ -1236,12 +1246,192 @@ void gea::apple::AppKit::setScrollDocumentTopAligned(gea::apple::AppKit::NSScrol
1236
1246
  }
1237
1247
  #endif
1238
1248
 
1249
+ static bool validPrerenderViewport(int width, int height, double dpr)
1250
+ {
1251
+ return width >= 1 && width <= 8192 && height >= 1 && height <= 8192 &&
1252
+ std::isfinite(dpr) && dpr >= 0.1 && dpr <= 8;
1253
+ }
1254
+
1255
+ static void preparePrerenderHost()
1256
+ {
1257
+ NSString *fontsDir = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"Fonts"];
1258
+ gea::macos::registerCustomTtfDirectory(fontsDir);
1259
+ gea::macos::useSoftwareTextMeasurement();
1260
+ gea::platform::storage::setMountProvider(+[]() { return true; });
1261
+ }
1262
+
1263
+ static bool loadPrerenderPage(int width, int height, double dpr)
1264
+ {
1265
+ if (!gea_macos_prepare_prerender(width, height)) return false;
1266
+ gea_macos_set_prerender_time(0);
1267
+ // Seed the timer scheduler before app initialization schedules any timers.
1268
+ gea::host::resetAnimationFrameCallbacks();
1269
+ gea::host::resetScheduledTimers();
1270
+ gea::host::runAnimationFrameCallbacks(0);
1271
+ gea::framework::app::Application::init(width, height, dpr);
1272
+ if (gea::embedded::ui::Tree::instance().mountedRoot() < 0) return false;
1273
+ gea::css::DeclarativeAnimations::scanAndStart(0);
1274
+ return true;
1275
+ }
1276
+
1277
+ static void paintPrerenderFrame(int timeMs)
1278
+ {
1279
+ @autoreleasepool {
1280
+ gea_macos_set_prerender_time(timeMs);
1281
+ gea::embedded::ui::StyleSheet::instance().startCssAnimations(timeMs);
1282
+ gea::css::AnimationEngine::instance().tick(static_cast<std::uint32_t>(timeMs));
1283
+ gea::framework::app::Application::frame(timeMs);
1284
+ }
1285
+ }
1286
+
1287
+ static void drawPrerenderFrames(int fps, int targetMs)
1288
+ {
1289
+ for (std::int64_t frame = 0; ; ++frame) {
1290
+ const auto tickMs = (frame * 1000 + fps / 2) / fps;
1291
+ const int timeMs = static_cast<int>(std::min<std::int64_t>(tickMs, targetMs));
1292
+ paintPrerenderFrame(timeMs);
1293
+ if (timeMs == targetMs) break;
1294
+ }
1295
+ }
1296
+
1297
+ static int prerender(int argc, const char *argv[])
1298
+ {
1299
+ const bool video = std::strcmp(argv[1], "--gea-prerender-video") == 0;
1300
+ if (argc != (video ? 9 : 8)) return 2;
1301
+ const int width = std::atoi(argv[3]);
1302
+ const int height = std::atoi(argv[4]);
1303
+ const double dpr = std::atof(argv[5]);
1304
+ const int fps = std::atoi(argv[6]);
1305
+ const int targetMs = std::atoi(argv[7]);
1306
+ if (!validPrerenderViewport(width, height, dpr) || fps < 1 || fps > 1000 || targetMs < 0) return 2;
1307
+ try {
1308
+ if (video) {
1309
+ #if defined(GEA_MACOS_PRERENDER_VIDEO)
1310
+ const int endMs = std::atoi(argv[8]);
1311
+ if (endMs <= targetMs) return 2;
1312
+ gea::platform::prerender::VideoFrames stream(width, height);
1313
+ gea::platform::prerender::VideoClock clock(fps);
1314
+ preparePrerenderHost();
1315
+ if (!loadPrerenderPage(width, height, dpr)) throw std::runtime_error("Could not mount the page");
1316
+ gea::platform::prerender::streamVideoFrames(stream, fps, targetMs, endMs, paintPrerenderFrame);
1317
+ return 0;
1318
+ #else
1319
+ throw std::runtime_error("The installed @geastack/core lacks native video export");
1320
+ #endif
1321
+ }
1322
+ preparePrerenderHost();
1323
+ if (!loadPrerenderPage(width, height, dpr)) {
1324
+ std::fputs("Gea prerender could not mount the page\n", stderr);
1325
+ return 1;
1326
+ }
1327
+ drawPrerenderFrames(fps, targetMs);
1328
+ } catch (const std::exception &error) {
1329
+ std::fprintf(stderr, "%s\n", error.what());
1330
+ return 1;
1331
+ }
1332
+ if (!gea_macos_write_prerender_png([NSString stringWithUTF8String:argv[2]])) {
1333
+ std::fprintf(stderr, "Could not write PNG to %s\n", argv[2]);
1334
+ return 1;
1335
+ }
1336
+ return 0;
1337
+ }
1338
+
1339
+ static bool writePrerenderReply(FILE *stream, NSDictionary *reply)
1340
+ {
1341
+ NSData *encoded = [NSJSONSerialization dataWithJSONObject:reply options:0 error:nil];
1342
+ return encoded && std::fwrite(encoded.bytes, 1, encoded.length, stream) == encoded.length &&
1343
+ std::fputc('\n', stream) != EOF && std::fflush(stream) == 0;
1344
+ }
1345
+
1346
+ static int prerenderWorker()
1347
+ {
1348
+ // Reserve stdout for the request protocol. Engine diagnostics use stderr.
1349
+ const int protocolFd = dup(STDOUT_FILENO);
1350
+ if (protocolFd < 0) return 1;
1351
+ FILE *protocol = fdopen(protocolFd, "w");
1352
+ if (!protocol) {
1353
+ close(protocolFd);
1354
+ return 1;
1355
+ }
1356
+ if (dup2(STDERR_FILENO, STDOUT_FILENO) < 0) {
1357
+ std::fclose(protocol);
1358
+ return 1;
1359
+ }
1360
+
1361
+ preparePrerenderHost();
1362
+ std::string mountedInput;
1363
+ int mountedWidth = 0, mountedHeight = 0;
1364
+ double mountedDpr = 0;
1365
+ std::string line;
1366
+ bool connected = true;
1367
+ while (connected && std::getline(std::cin, line)) {
1368
+ @autoreleasepool {
1369
+ NSData *data = [NSData dataWithBytes:line.data() length:line.size()];
1370
+ id decoded = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
1371
+ NSDictionary *request = [decoded isKindOfClass:NSDictionary.class] ? decoded : nil;
1372
+ NSString *input = request[@"input"];
1373
+ NSString *output = request[@"out"];
1374
+ NSNumber *widthNumber = request[@"width"] ?: @480;
1375
+ NSNumber *heightNumber = request[@"height"] ?: @220;
1376
+ NSNumber *dprNumber = request[@"dpr"] ?: @1;
1377
+ NSNumber *reuse = request[@"reusePage"] ?: @NO;
1378
+ if (![input isKindOfClass:NSString.class] || input.length == 0 ||
1379
+ ![output isKindOfClass:NSString.class] || output.length == 0 ||
1380
+ ![widthNumber isKindOfClass:NSNumber.class] ||
1381
+ ![heightNumber isKindOfClass:NSNumber.class] ||
1382
+ ![dprNumber isKindOfClass:NSNumber.class] ||
1383
+ ![reuse isKindOfClass:NSNumber.class] ||
1384
+ widthNumber.doubleValue != widthNumber.intValue ||
1385
+ heightNumber.doubleValue != heightNumber.intValue ||
1386
+ !validPrerenderViewport(widthNumber.intValue, heightNumber.intValue, dprNumber.doubleValue)) {
1387
+ connected = writePrerenderReply(protocol, @{@"ok": @NO, @"error": @"Invalid capture request"});
1388
+ continue;
1389
+ }
1390
+
1391
+ const int width = widthNumber.intValue, height = heightNumber.intValue;
1392
+ const double dpr = dprNumber.doubleValue;
1393
+ const bool reusePage = reuse.boolValue && mountedInput == input.UTF8String &&
1394
+ mountedWidth == width && mountedHeight == height && mountedDpr == dpr;
1395
+ const auto started = std::chrono::steady_clock::now();
1396
+ try {
1397
+ if (!reusePage) {
1398
+ mountedInput.clear();
1399
+ if (setenv("GEA_PRERENDER_INPUT", input.fileSystemRepresentation, 1) != 0 ||
1400
+ !loadPrerenderPage(width, height, dpr)) {
1401
+ connected = writePrerenderReply(protocol, @{@"ok": @NO, @"error": @"Could not mount the page"});
1402
+ continue;
1403
+ }
1404
+ drawPrerenderFrames(60, 0);
1405
+ mountedInput = input.UTF8String;
1406
+ mountedWidth = width;
1407
+ mountedHeight = height;
1408
+ mountedDpr = dpr;
1409
+ }
1410
+ if (!gea_macos_write_prerender_png(output)) {
1411
+ connected = writePrerenderReply(protocol, @{@"ok": @NO, @"error": @"Could not write the PNG"});
1412
+ continue;
1413
+ }
1414
+ const double ms = std::chrono::duration<double, std::milli>(
1415
+ std::chrono::steady_clock::now() - started).count();
1416
+ connected = writePrerenderReply(protocol, @{@"ok": @YES, @"ms": @(ms), @"reusedPage": @(reusePage)});
1417
+ } catch (const std::exception &error) {
1418
+ mountedInput.clear();
1419
+ NSString *message = [NSString stringWithUTF8String:error.what()] ?: @"Capture failed";
1420
+ connected = writePrerenderReply(protocol, @{@"ok": @NO, @"error": message});
1421
+ }
1422
+ }
1423
+ }
1424
+ std::fclose(protocol);
1425
+ return connected ? 0 : 1;
1426
+ }
1427
+
1239
1428
  int main(int argc, const char *argv[])
1240
1429
  {
1241
1430
  GeaNativeTerminationGuard terminationGuard;
1242
- (void)argc;
1243
- (void)argv;
1244
1431
  @autoreleasepool {
1432
+ if (argc > 1 && (std::strcmp(argv[1], "--gea-prerender") == 0 ||
1433
+ std::strcmp(argv[1], "--gea-prerender-video") == 0)) return prerender(argc, argv);
1434
+ if (argc == 2 && std::strcmp(argv[1], "--gea-prerender-worker") == 0) return prerenderWorker();
1245
1435
  gea_macos_smoke_log("[gea-macos] main entered");
1246
1436
  const bool backgroundTest = gea::macos::background_test::enabled();
1247
1437
  NSApplication *app = [NSApplication sharedApplication];
@@ -0,0 +1,8 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ @class NSString;
5
+
6
+ bool gea_macos_prepare_prerender(int width, int height);
7
+ bool gea_macos_write_prerender_png(NSString *path);
8
+ void gea_macos_set_prerender_time(int timestampMs);
@@ -1,12 +1,18 @@
1
1
  #import <Foundation/Foundation.h>
2
2
  #include "services/frame_scheduler.h"
3
+ #include "macos_prerender.h"
3
4
 
5
+ #include <atomic>
4
6
  #include <mach/mach_time.h>
5
7
 
6
8
  namespace {
7
9
 
10
+ std::atomic<int> prerenderMillis{-1};
11
+
8
12
  int monotonicMillis()
9
13
  {
14
+ const int captureTime = prerenderMillis.load(std::memory_order_relaxed);
15
+ if (captureTime >= 0) return captureTime;
10
16
  static mach_timebase_info_data_t tb = {0, 0};
11
17
  if (tb.denom == 0) mach_timebase_info(&tb);
12
18
  static const uint64_t start = mach_absolute_time();
@@ -18,6 +24,11 @@ int g_frame_interval_ms = gea::framework::services::FrameScheduler::kDefaultFram
18
24
 
19
25
  } // namespace
20
26
 
27
+ void gea_macos_set_prerender_time(int timestampMs)
28
+ {
29
+ prerenderMillis.store(timestampMs, std::memory_order_relaxed);
30
+ }
31
+
21
32
  extern "C" int gea_embedded_now_ms(void)
22
33
  {
23
34
  return monotonicMillis();
@@ -86,6 +86,7 @@ function walkCss(root, visit) {
86
86
  // not leave stale resources in the app bundle.
87
87
  const desiredFonts = new Map()
88
88
  const desiredFontLicenses = new Map()
89
+ const fontAliases = new Map()
89
90
  for (const root of [...appDirs, ...sharedCssDirs]) {
90
91
  walkCss(root, (cssPath) => {
91
92
  const css = fs.readFileSync(cssPath, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '')
@@ -100,6 +101,11 @@ for (const root of [...appDirs, ...sharedCssDirs]) {
100
101
  const resolved = path.resolve(path.dirname(cssPath), clean)
101
102
  if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) continue
102
103
  const basename = path.basename(resolved)
104
+ const family = face[1].match(/(?:^|;)\s*font-family\s*:\s*(?:"([^"]+)"|'([^']+)'|([^;]+))/i)
105
+ const alias = (family?.[1] || family?.[2] || family?.[3] || '').trim().toLowerCase()
106
+ if (alias && (!desiredFonts.has(basename) || desiredFonts.get(basename) === resolved) && !fontAliases.has(alias)) {
107
+ fontAliases.set(alias, basename)
108
+ }
103
109
  if (!desiredFonts.has(basename)) {
104
110
  desiredFonts.set(basename, resolved)
105
111
  // Preserve licenses alongside packaged font bytes, using a font-specific
@@ -157,6 +163,17 @@ if (fs.existsSync(fontLicensesDir)) {
157
163
  for (const [name, source] of desiredFontLicenses) syncFile(source, path.join(fontLicensesDir, name))
158
164
  if (fs.existsSync(fontLicensesDir) && fs.readdirSync(fontLicensesDir).length === 0) fs.rmdirSync(fontLicensesDir)
159
165
 
166
+ const aliasesPath = path.join(resourcesDir, 'font-aliases.json')
167
+ if (fontAliases.size) {
168
+ const contents = JSON.stringify(Object.fromEntries(fontAliases), null, 2) + '\n'
169
+ if (!fs.existsSync(aliasesPath) || fs.readFileSync(aliasesPath, 'utf8') !== contents) {
170
+ const temporary = `${aliasesPath}.tmp.${process.pid}`
171
+ fs.writeFileSync(temporary, contents)
172
+ fs.renameSync(temporary, aliasesPath)
173
+ changed = true
174
+ }
175
+ } else removeFile(aliasesPath)
176
+
160
177
  const windowConfig = path.join(resourcesDir, 'window.json')
161
178
  for (const entry of fs.readdirSync(resourcesDir, { withFileTypes: true })) {
162
179
  if (entry.isFile() && /^window\.json\.tmp\.\d+$/.test(entry.name)) removeFile(path.join(resourcesDir, entry.name))