@geastack/apple 0.2.31 → 0.2.33

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/dist/index.js CHANGED
@@ -2442,6 +2442,14 @@ function declarationForFramework(framework) {
2442
2442
  for (const cls of framework.classes ?? []) {
2443
2443
  const base = cls.extends ? ` extends ${shortTypeName(cls.extends)}` : '';
2444
2444
  lines.push(`export declare class ${cls.name}${base} {`);
2445
+ // A root class states a private brand, which every subclass inherits. A
2446
+ // class with no instance members is structurally `{}`: every object type,
2447
+ // a `Record<string, T>` included, is assignable to it, so geatsc's
2448
+ // host-mutation census read any dictionary the program writes with
2449
+ // `Object.assign` as a possible native object and revoked every intrinsic
2450
+ // prototype proof in the program. The brand makes these classes nominal.
2451
+ if (!cls.extends)
2452
+ lines.push(' private readonly __geaNativeObject: never');
2445
2453
  for (const constructor of cls.constructors ?? []) {
2446
2454
  lines.push(` constructor(${parametersSignature(constructor.parameters ?? [], framework.name)})`);
2447
2455
  }
@@ -6,5 +6,6 @@ export declare function updateLiveActivity(activity: LiveActivityHandle, content
6
6
  export declare function endLiveActivity(activity: LiveActivityHandle): void
7
7
 
8
8
  export declare class LiveActivityHandle {
9
+ private readonly __geaNativeObject: never
9
10
  readonly id: string
10
11
  }
@@ -111,6 +111,7 @@ export declare class NSLayoutGuide extends NSObject {
111
111
  }
112
112
 
113
113
  export declare class ObjCTarget {
114
+ private readonly __geaNativeObject: never
114
115
  static create(callback: () => void): NSObject
115
116
  }
116
117
 
@@ -14,6 +14,7 @@ export declare function watchPath(path: string, changed: () => void): number
14
14
  export declare function stopWatchingPath(handle: number): void
15
15
 
16
16
  export declare class NSObject {
17
+ private readonly __geaNativeObject: never
17
18
  }
18
19
 
19
20
  export declare class NSData extends NSObject {
@@ -18,10 +18,12 @@ export interface MTLClearColor {
18
18
  }
19
19
 
20
20
  export declare class MTLCompileOptions {
21
+ private readonly __geaNativeObject: never
21
22
  constructor()
22
23
  }
23
24
 
24
25
  export declare class MTLDevice {
26
+ private readonly __geaNativeObject: never
25
27
  newCommandQueue(): MTLCommandQueue | null
26
28
  newLibraryWithSourceOptionsError(source: string, options: MTLCompileOptions): MTLLibrary | null
27
29
  newBufferWithBytesLengthOptions(bytes: number[], length: number, options: number): MTLBuffer | null
@@ -30,23 +32,28 @@ export declare class MTLDevice {
30
32
  }
31
33
 
32
34
  export declare class MTLCommandQueue {
35
+ private readonly __geaNativeObject: never
33
36
  commandBuffer(): MTLCommandBuffer | null
34
37
  }
35
38
 
36
39
  export declare class MTLCommandBuffer {
40
+ private readonly __geaNativeObject: never
37
41
  renderCommandEncoderWithDescriptor(descriptor: MTLRenderPassDescriptor): MTLRenderCommandEncoder | null
38
42
  presentDrawable(drawable: MTLDrawable): void
39
43
  commit(): void
40
44
  }
41
45
 
42
46
  export declare class MTLLibrary {
47
+ private readonly __geaNativeObject: never
43
48
  newFunctionWithName(name: string): MTLFunction | null
44
49
  }
45
50
 
46
51
  export declare class MTLFunction {
52
+ private readonly __geaNativeObject: never
47
53
  }
48
54
 
49
55
  export declare class MTLRenderPipelineDescriptor {
56
+ private readonly __geaNativeObject: never
50
57
  constructor()
51
58
  vertexFunction: MTLFunction | null
52
59
  fragmentFunction: MTLFunction | null
@@ -55,29 +62,36 @@ export declare class MTLRenderPipelineDescriptor {
55
62
  }
56
63
 
57
64
  export declare class MTLRenderPipelineColorAttachmentDescriptorArray {
65
+ private readonly __geaNativeObject: never
58
66
  objectAtIndexedSubscript(index: number): MTLRenderPipelineColorAttachmentDescriptor
59
67
  }
60
68
 
61
69
  export declare class MTLRenderPipelineColorAttachmentDescriptor {
70
+ private readonly __geaNativeObject: never
62
71
  pixelFormat: number
63
72
  }
64
73
 
65
74
  export declare class MTLRenderPipelineState {
75
+ private readonly __geaNativeObject: never
66
76
  }
67
77
 
68
78
  export declare class MTLBuffer {
79
+ private readonly __geaNativeObject: never
69
80
  }
70
81
 
71
82
  export declare class MTLDepthStencilDescriptor {
83
+ private readonly __geaNativeObject: never
72
84
  constructor()
73
85
  depthCompareFunction: number
74
86
  depthWriteEnabled: boolean
75
87
  }
76
88
 
77
89
  export declare class MTLDepthStencilState {
90
+ private readonly __geaNativeObject: never
78
91
  }
79
92
 
80
93
  export declare class MTLRenderCommandEncoder {
94
+ private readonly __geaNativeObject: never
81
95
  setRenderPipelineState(pipelineState: MTLRenderPipelineState): void
82
96
  setDepthStencilState(depthStencilState: MTLDepthStencilState): void
83
97
  setVertexBufferOffsetAtIndex(buffer: MTLBuffer, offset: number, index: number): void
@@ -87,7 +101,9 @@ export declare class MTLRenderCommandEncoder {
87
101
  }
88
102
 
89
103
  export declare class MTLRenderPassDescriptor {
104
+ private readonly __geaNativeObject: never
90
105
  }
91
106
 
92
107
  export declare class MTLDrawable {
108
+ private readonly __geaNativeObject: never
93
109
  }
@@ -18,5 +18,6 @@ export declare class MTKView extends UIView {
18
18
  }
19
19
 
20
20
  export declare class MTKViewDelegate {
21
+ private readonly __geaNativeObject: never
21
22
  static create(drawInMTKView: () => void): MTKViewDelegate
22
23
  }
@@ -10,7 +10,9 @@ export declare function saveModelContext(context: ModelContext): void
10
10
  export declare function fetchModelsJSON(context: ModelContext, descriptorJSON: string): string
11
11
 
12
12
  export declare class ModelContainer {
13
+ private readonly __geaNativeObject: never
13
14
  }
14
15
 
15
16
  export declare class ModelContext {
17
+ private readonly __geaNativeObject: never
16
18
  }
@@ -85,6 +85,7 @@ export declare class UIAction extends NSObject {
85
85
  }
86
86
 
87
87
  export declare class ObjCTarget {
88
+ private readonly __geaNativeObject: never
88
89
  static create(callback: () => void): NSObject
89
90
  }
90
91
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/apple",
3
- "version": "0.2.31",
3
+ "version": "0.2.33",
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": {
@@ -115,14 +115,13 @@
115
115
  "access": "public"
116
116
  },
117
117
  "dependencies": {
118
- "@geastack/compiler": "^1.0.34",
119
- "@geastack/core": "^0.1.64",
118
+ "@geastack/compiler": "^1.0.71",
119
+ "@geastack/core": "^0.1.70",
120
120
  "@geastack/elements": "^0.1.7",
121
- "@geastack/engine": "^0.1.31",
122
- "@geastack/geaos": "^0.1.3",
121
+ "@geastack/engine": "^0.1.36",
123
122
  "@geastack/geatsc-plugin-apple-native": "^0.1.4",
124
- "@geastack/geatsc-plugin-gea": "^0.1.28",
125
- "@geastack/host": "^0.1.25"
123
+ "@geastack/geatsc-plugin-gea": "^0.1.31",
124
+ "@geastack/host": "^0.1.28"
126
125
  },
127
126
  "scripts": {
128
127
  "prepublishOnly": "npm run build",
@@ -12,6 +12,7 @@
12
12
  <key>CFBundleShortVersionString</key><string>0.1.0</string>
13
13
  <key>CFBundleVersion</key><string>1</string>
14
14
  <key>LSRequiresIPhoneOS</key><true/>
15
+ <key>NSMicrophoneUsageDescription</key><string>$(PRODUCT_NAME) uses the microphone when you enable audio capture.</string>
15
16
  <key>NSCameraUsageDescription</key><string>Gea native examples use the camera to demonstrate AVFoundation preview layers from TypeScript.</string>
16
17
  <key>NSLocationWhenInUseUsageDescription</key><string>Gea native examples use location to demonstrate CoreLocation and MapKit from TypeScript.</string>
17
18
  <key>NSPhotoLibraryAddUsageDescription</key><string>Gea native examples save captured camera photos to demonstrate Photos library writes from TypeScript.</string>
@@ -58,12 +58,11 @@ fi
58
58
  GEA_HOST_DIR="${GEA_HOST_DIR:-$GEA_CORE/../host}"
59
59
  GEA_ENGINE_DIR="${GEA_ENGINE_DIR:-$GEA_CORE/../engine}"
60
60
  GEA_ELEMENTS_DIR="${GEA_ELEMENTS_DIR:-$GEA_CORE/../elements}"
61
- GEA_GEAOS_PACKAGE_DIR="${GEA_GEAOS_PACKAGE_DIR:-$GEA_CORE/../geaos}"
62
61
  # The source manifest reads these from the ENVIRONMENT: gea_sources.sh is a
63
62
  # front end for gea_sources.mjs, which runs as a child process. A plain shell
64
63
  # variable never reaches it and it reports "<name> unset" while the include
65
64
  # roots come back empty.
66
- export GEA_CORE GEA_HOST_DIR GEA_ENGINE_DIR GEA_ELEMENTS_DIR GEA_GEAOS_PACKAGE_DIR
65
+ export GEA_CORE GEA_HOST_DIR GEA_ENGINE_DIR GEA_ELEMENTS_DIR
67
66
  # This script IS @geastack/apple, so the generator must bind against this
68
67
  # working copy rather than whatever installed copy it would resolve from the app.
69
68
  export GEA_APPLE_ROOT="$ROOT_DIR"
@@ -85,6 +84,19 @@ source "$GEA_CORE/gea_sources.sh"
85
84
  export GEA_FW_CXX_SOURCES="$(gea_fw_cxx_sources | grep -vE "/(runtime|services/[a-z_]+)\.cpp\$")"
86
85
  export GEA_FW_C_SOURCES="$(gea_fw_c_sources)"
87
86
  export GEA_FW_INCLUDE_DIRS="$(gea_fw_include_flags | sed "s/^-I//")"
87
+ # A single app never compiles, includes or links GeaOS. GEA_GEAOS=1 requests a
88
+ # GeaOS build: generate-xcode-project.mjs then adds these sources and include
89
+ # roots, GEA_GEAOS=1 and the iOS GeaOS app host (main/ios_app_platform.mm).
90
+ GEA_GEAOS_CXX_SOURCES=""
91
+ GEA_GEAOS_INCLUDE_DIRS=""
92
+ if [[ "${GEA_GEAOS:-0}" == "1" ]]; then
93
+ GEA_GEAOS_PACKAGE_DIR="${GEA_GEAOS_PACKAGE_DIR:-$GEA_CORE/../geaos}"
94
+ [[ -f "$GEA_GEAOS_PACKAGE_DIR/geaos.h" ]] || { echo "GEA_GEAOS=1 but no @geastack/geaos at $GEA_GEAOS_PACKAGE_DIR (set GEA_GEAOS_PACKAGE_DIR)" >&2; exit 1; }
95
+ export GEA_GEAOS_PACKAGE_DIR
96
+ GEA_GEAOS_CXX_SOURCES="$(gea_geaos_cxx_sources)"
97
+ GEA_GEAOS_INCLUDE_DIRS="$(gea_geaos_include_flags | sed "s/^-I//")"
98
+ fi
99
+ export GEA_GEAOS_CXX_SOURCES GEA_GEAOS_INCLUDE_DIRS
88
100
  APP_ID="${1:-bouncing-balls-jsx}"
89
101
  DESTINATION="${2:-simulator}"
90
102
  export GEA_APPLE_UIKIT_PLATFORM="${3:-ios}"
@@ -62,6 +62,7 @@ const appIconAssetsDir = path.join(generatedDir, 'Assets.xcassets')
62
62
  // exactly (e.g. SDK 23F81a needs a 23F81a runtime, not a 23F73 one) — a skew that
63
63
  // blocks otherwise-fine builds. Skipping it yields an app with the default icon.
64
64
  const tvos = process.env.GEA_APPLE_UIKIT_PLATFORM === 'tvos'
65
+ const geaosBuild = process.env.GEA_GEAOS === '1'
65
66
  const buildConfig = process.env.GEA_BUILD_CONFIG_JSON
66
67
  ? JSON.parse(fs.readFileSync(process.env.GEA_BUILD_CONFIG_JSON, 'utf8'))
67
68
  : {}
@@ -205,13 +206,16 @@ const sources = [
205
206
  source(path.join(iosDir, 'main/press_bridge.mm'), 'sourcecode.cpp.objcpp'),
206
207
  source(path.join(iosDir, 'main/ios_display.mm'), 'sourcecode.cpp.objcpp'),
207
208
  source(path.join(iosDir, 'main/ios_timers.mm'), 'sourcecode.cpp.objcpp'),
208
- source(path.join(iosDir, 'main/ios_app_platform.mm'), 'sourcecode.cpp.objcpp'),
209
209
  source(path.join(iosDir, 'main/ios_memory.cpp')),
210
210
  // gea::platform::audio — the AVAudioEngine backend, shared verbatim with macOS.
211
211
  source(path.join(iosDir, '../shared/apple_audio.mm'), 'sourcecode.cpp.objcpp'),
212
212
  source(path.join(iosDir, 'main/ios_sensors.mm'), 'sourcecode.cpp.objcpp'),
213
+ ...(!tvos ? [
214
+ source(path.join(iosDir, 'main/ios_http.mm'), 'sourcecode.cpp.objcpp'),
215
+ source(path.join(iosDir, 'main/ios_microphone.mm'), 'sourcecode.cpp.objcpp'),
216
+ source(path.join(iosDir, 'main/ios_websocket.mm'), 'sourcecode.cpp.objcpp'),
217
+ ] : []),
213
218
  source(path.join(iosDir, 'main/ios_camera.mm'), 'sourcecode.cpp.objcpp'),
214
- source(path.join(iosDir, 'main/ios_apps.c'), 'sourcecode.c.c'),
215
219
  ...appNativeSources,
216
220
  // Framework C/C++ sources come from @geastack/core/gea_sources.sh,
217
221
  // passed by build-ios.sh via env (iOS-curated: camera kept since ios_camera.mm
@@ -225,6 +229,19 @@ const sources = [
225
229
  ...generatedProgramSources,
226
230
  appleNativeBridgeSource,
227
231
  ].filter(existing)
232
+ // A single app never compiles GeaOS. A GeaOS build (GEA_GEAOS=1, set up by
233
+ // build-ios.sh) adds the manifest's geaos sources and the iOS GeaOS app host.
234
+ if (geaosBuild) {
235
+ const geaosAppHost = source(path.join(iosDir, 'main/ios_app_platform.mm'), 'sourcecode.cpp.objcpp')
236
+ if (!existing(geaosAppHost)) {
237
+ console.error(`GEA_GEAOS=1 but the iOS GeaOS app host ${geaosAppHost.file} does not exist`)
238
+ process.exit(1)
239
+ }
240
+ sources.push(
241
+ ...(process.env.GEA_GEAOS_CXX_SOURCES || '').split('\n').filter(Boolean).map((f) => source(f)),
242
+ geaosAppHost,
243
+ )
244
+ }
228
245
 
229
246
  const fontGenerated = source(path.join(generatedDir, 'gea_embedded_font_generated.cpp'))
230
247
  if (existing(fontGenerated)) sources.push(fontGenerated)
@@ -262,7 +279,7 @@ const frameworks = [
262
279
  'Photos.framework',
263
280
  'Security.framework',
264
281
  'UserNotifications.framework',
265
- ...(!tvos ? ['EventKit.framework'] : []),
282
+ ...(!tvos ? ['EventKit.framework', 'Network.framework', 'CFNetwork.framework'] : []),
266
283
  'Metal.framework',
267
284
  'MetalKit.framework',
268
285
  'Foundation.framework',
@@ -354,6 +371,8 @@ const includePaths = [
354
371
  // Framework include roots (core/host/engine includes + vendor/stb + AnimatedGIF)
355
372
  // from the shared manifest gea_sources.sh, passed by build-ios.sh via env.
356
373
  ...(process.env.GEA_FW_INCLUDE_DIRS || '').split('\n').filter(Boolean),
374
+ ...(geaosBuild ? (process.env.GEA_GEAOS_INCLUDE_DIRS || '').split('\n').filter(Boolean) : []),
375
+ ...(!tvos && process.env.GEA_HOST_DIR ? [process.env.GEA_HOST_DIR] : []),
357
376
  ]
358
377
 
359
378
  // OTHER_LDFLAGS -no_deduplicate: ld64 folds functions with identical code by
@@ -363,6 +382,7 @@ const includePaths = [
363
382
  function buildSettings(configuration) {
364
383
  const preprocessorDefinitions = [
365
384
  'GEA_EMBEDDED_GIF_C_API=1',
385
+ ...(geaosBuild ? ['GEA_GEAOS=1'] : []),
366
386
  ...(viewport.width === undefined ? [] : [
367
387
  `GEA_UIKIT_VIEWPORT_WIDTH=${viewport.width}`,
368
388
  `GEA_UIKIT_VIEWPORT_HEIGHT=${viewport.height}`,
@@ -0,0 +1,181 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #import <CFNetwork/CFNetwork.h>
3
+ #import <Foundation/Foundation.h>
4
+ #import <Network/Network.h>
5
+
6
+ #include "host/http.h"
7
+
8
+ #include <charconv>
9
+ #include <memory>
10
+ #include <unordered_map>
11
+
12
+ namespace gea::host::http {
13
+ namespace {
14
+ constexpr size_t maxHeader = 16 * 1024;
15
+ constexpr size_t maxBody = 1024 * 1024;
16
+ constexpr size_t maxFile = 4 * 1024 * 1024;
17
+ std::unordered_map<NativeHttpServerHandle, nw_listener_t> listeners;
18
+ size_t activeConnections = 0;
19
+
20
+ std::string utf8(NSString *value) { return value.UTF8String ?: ""; }
21
+
22
+ NSString *ns(const std::string &value) {
23
+ return [[NSString alloc] initWithBytes:value.data() length:value.size() encoding:NSUTF8StringEncoding];
24
+ }
25
+
26
+ struct Connection {
27
+ explicit Connection(nw_connection_t socket, NativeHttpServerHandle server) : socket(socket), server(server) {}
28
+ ~Connection() { if (message) CFRelease(message); }
29
+ nw_connection_t socket;
30
+ NativeHttpServerHandle server;
31
+ CFHTTPMessageRef message = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true);
32
+ size_t received = 0;
33
+ bool done = false;
34
+ };
35
+
36
+ void close(const std::shared_ptr<Connection> &client) {
37
+ if (client->done) return;
38
+ client->done = true;
39
+ CFRelease(client->message);
40
+ client->message = nullptr;
41
+ --activeConnections;
42
+ nw_connection_cancel(client->socket);
43
+ }
44
+
45
+ void respond(std::shared_ptr<Connection> client, HttpReply reply) {
46
+ if (client->done) return;
47
+ NSData *body = nil;
48
+ if (!reply.file.empty()) {
49
+ NSString *path = ns(reply.file);
50
+ NSNumber *size = [[NSFileManager.defaultManager attributesOfItemAtPath:path error:NULL] objectForKey:NSFileSize];
51
+ if (size && size.unsignedLongLongValue <= maxFile) body = [NSData dataWithContentsOfFile:path];
52
+ if (!body) {
53
+ reply.status = 404;
54
+ reply.contentType = "text/plain";
55
+ reply.body = "File not found";
56
+ }
57
+ }
58
+ if (!body) body = [NSData dataWithBytes:reply.body.data() length:reply.body.size()];
59
+ CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, reply.status, nullptr, kCFHTTPVersion1_1);
60
+ for (const auto &header : reply.headers) {
61
+ CFHTTPMessageSetHeaderFieldValue(response, (__bridge CFStringRef)ns(header.name), (__bridge CFStringRef)ns(header.value));
62
+ }
63
+ CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), (__bridge CFStringRef)ns(reply.contentType));
64
+ CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), (__bridge CFStringRef)[@(body.length) stringValue]);
65
+ CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Connection"), CFSTR("close"));
66
+ CFHTTPMessageSetBody(response, (__bridge CFDataRef)body);
67
+ NSData *packet = CFBridgingRelease(CFHTTPMessageCopySerializedMessage(response));
68
+ CFRelease(response);
69
+ auto bytes = dispatch_data_create(packet.bytes, packet.length, dispatch_get_main_queue(), ^{
70
+ (void)packet;
71
+ });
72
+ nw_connection_send(client->socket, bytes, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, ^(nw_error_t) {
73
+ close(client);
74
+ });
75
+ }
76
+
77
+ HttpReply failure(int status, const char *message) {
78
+ HttpReply reply;
79
+ reply.status = status;
80
+ reply.body = message;
81
+ return reply;
82
+ }
83
+
84
+ void receive(std::shared_ptr<Connection> client) {
85
+ nw_connection_receive(client->socket, 1, 8192, ^(dispatch_data_t data, nw_content_context_t, bool complete, nw_error_t error) {
86
+ if (client->done) return;
87
+ if (error || !data) { close(client); return; }
88
+ const void *buffer = nullptr;
89
+ size_t length = 0;
90
+ auto contiguous = dispatch_data_create_map(data, &buffer, &length);
91
+ client->received += length;
92
+ if (client->received > maxHeader + maxBody) {
93
+ respond(client, failure(413, "Request too large"));
94
+ return;
95
+ }
96
+ if (!CFHTTPMessageAppendBytes(client->message, static_cast<const UInt8 *>(buffer), length)) {
97
+ respond(client, failure(400, "Invalid HTTP request"));
98
+ return;
99
+ }
100
+ (void)contiguous;
101
+ if (!CFHTTPMessageIsHeaderComplete(client->message)) {
102
+ if (client->received > maxHeader || complete) respond(client, failure(400, "Invalid HTTP headers"));
103
+ else receive(client);
104
+ return;
105
+ }
106
+ NSDictionary<NSString *, NSString *> *fields = CFBridgingRelease(CFHTTPMessageCopyAllHeaderFields(client->message));
107
+ auto header = [&](NSString *name) -> std::string {
108
+ NSString *value = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(client->message, (__bridge CFStringRef)name));
109
+ return utf8(value);
110
+ };
111
+ if (!header(@"Transfer-Encoding").empty()) {
112
+ respond(client, failure(400, "Transfer encoding is not supported"));
113
+ return;
114
+ }
115
+ size_t expected = 0;
116
+ const std::string size = header(@"Content-Length");
117
+ if (!size.empty()) {
118
+ const auto result = std::from_chars(size.data(), size.data() + size.size(), expected);
119
+ if (result.ec != std::errc() || result.ptr != size.data() + size.size() || expected > maxBody) {
120
+ respond(client, failure(413, "Invalid request size"));
121
+ return;
122
+ }
123
+ }
124
+ NSData *body = CFBridgingRelease(CFHTTPMessageCopyBody(client->message));
125
+ if (body.length < expected) {
126
+ if (complete) respond(client, failure(400, "Incomplete request"));
127
+ else receive(client);
128
+ return;
129
+ }
130
+ HttpRequest request;
131
+ NSURL *url = CFBridgingRelease(CFHTTPMessageCopyRequestURL(client->message));
132
+ request.method = utf8(CFBridgingRelease(CFHTTPMessageCopyRequestMethod(client->message)));
133
+ request.path = utf8(url.path);
134
+ request.query = utf8(url.query);
135
+ for (NSString *name in fields) request.headers.push_back({utf8(name), utf8(fields[name])});
136
+ if (expected) {
137
+ const auto *first = static_cast<const uint8_t *>(body.bytes);
138
+ request.body.assign(first, first + expected);
139
+ }
140
+ auto &table = handlerTable();
141
+ const auto entry = table.find(client->server);
142
+ if (entry == table.end() || !entry->second) { respond(client, failure(404, "Server stopped")); return; }
143
+ const RequestHandler handler = entry->second;
144
+ try {
145
+ respond(client, handler(request));
146
+ } catch (...) {
147
+ respond(client, failure(500, "Request failed"));
148
+ }
149
+ });
150
+ }
151
+ } // namespace
152
+
153
+ bool platform_listen(NativeHttpServerHandle handle, int port) {
154
+ if (port < 1 || port > 65535 || listeners.contains(handle)) return false;
155
+ auto params = nw_parameters_create_secure_tcp(NW_PARAMETERS_DISABLE_PROTOCOL, NW_PARAMETERS_DEFAULT_CONFIGURATION);
156
+ auto listener = nw_listener_create_with_port(std::to_string(port).c_str(), params);
157
+ if (!listener) return false;
158
+ listeners.emplace(handle, listener);
159
+ nw_listener_set_queue(listener, dispatch_get_main_queue());
160
+ nw_listener_set_new_connection_handler(listener, ^(nw_connection_t socket) {
161
+ if (activeConnections >= 12) { nw_connection_cancel(socket); return; }
162
+ ++activeConnections;
163
+ auto client = std::make_shared<Connection>(socket, handle);
164
+ nw_connection_set_queue(socket, dispatch_get_main_queue());
165
+ nw_connection_start(socket);
166
+ receive(client);
167
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
168
+ close(client);
169
+ });
170
+ });
171
+ nw_listener_start(listener);
172
+ return true;
173
+ }
174
+
175
+ void platform_close(NativeHttpServerHandle handle) {
176
+ const auto listener = listeners.find(handle);
177
+ if (listener == listeners.end()) return;
178
+ nw_listener_cancel(listener->second);
179
+ listeners.erase(listener);
180
+ }
181
+ } // namespace gea::host::http
@@ -8,10 +8,10 @@
8
8
  #endif
9
9
 
10
10
  #include "app.h"
11
- #include "apps.h"
12
11
  #include "canvas.h"
13
12
  #include "css/animation.h"
14
13
  #include "css/declarative.h"
14
+ #include "host/timers.h"
15
15
  #include "display.h"
16
16
  #include "display_underlay.h"
17
17
  #include "event.h"
@@ -831,6 +831,11 @@ static void dispatchRemoteKey(int keyCode)
831
831
  self.extensionLayout = CGSizeMake(rootSize.width, rootSize.height * viewportScale);
832
832
  gea_uikit_host_attach((__bridge void *)self.rootView, rootSize.width, rootSize.height, viewportScale);
833
833
  const bool extensionsBegun = gea_uikit_host_begin_frame() != 0;
834
+ // Seed the timer clock with the frame clock before the program's top level
835
+ // runs: a setTimeout scheduled during init otherwise reads the host's
836
+ // steady clock (time since boot) while frames pass time since launch,
837
+ // and its deadline never arrives.
838
+ gea::host::runAnimationFrameCallbacks(gea_embedded_now_ms());
834
839
  gea::framework::app::Application::init(viewportWidth, viewportHeight, devicePixelRatio);
835
840
  if (extensionsBegun) gea_uikit_host_end_frame();
836
841
  [self syncAppBackgroundColor];
@@ -0,0 +1,117 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #import <AVFoundation/AVFoundation.h>
3
+ #import <UIKit/UIKit.h>
4
+ #include <mutex>
5
+ #include <unordered_set>
6
+ #include "audio.h"
7
+ #include "host/media.h"
8
+
9
+ namespace gea::host::media {
10
+ namespace {
11
+ AVAudioEngine *capture;
12
+ std::unordered_set<NativeMediaTrackHandle> tracks;
13
+ std::mutex tracksMutex;
14
+ bool requestingPermission = false;
15
+
16
+ bool hasTracks() {
17
+ std::lock_guard lock(tracksMutex);
18
+ return !tracks.empty();
19
+ }
20
+
21
+ void stopCapture() {
22
+ if (!capture) return;
23
+ [capture.inputNode removeTapOnBus:0];
24
+ [capture stop];
25
+ capture = nil;
26
+ [AVAudioSession.sharedInstance setActive:NO error:NULL];
27
+ }
28
+
29
+ void startCapture() {
30
+ if (capture || !hasTracks()) return;
31
+ AVAudioSession *session = AVAudioSession.sharedInstance;
32
+ if (![session setCategory:AVAudioSessionCategoryRecord mode:AVAudioSessionModeMeasurement options:0 error:NULL] ||
33
+ ![session setActive:YES error:NULL]) return;
34
+
35
+ AVAudioEngine *engine = [[AVAudioEngine alloc] init];
36
+ AVAudioInputNode *input = engine.inputNode;
37
+ AVAudioFormat *source = [input outputFormatForBus:0];
38
+ constexpr double sampleRate = gea::platform::audio::deviceSampleRate;
39
+ AVAudioFormat *format = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatInt16 sampleRate:sampleRate channels:1 interleaved:YES];
40
+ AVAudioConverter *converter = source.sampleRate > 0 && source.channelCount
41
+ ? [[AVAudioConverter alloc] initFromFormat:source toFormat:format]
42
+ : nil;
43
+ if (!converter) {
44
+ [session setActive:NO error:NULL];
45
+ return;
46
+ }
47
+ [input installTapOnBus:0 bufferSize:2048 format:source block:^(AVAudioPCMBuffer *buffer, AVAudioTime *) {
48
+ auto capacity = (AVAudioFrameCount)(buffer.frameLength * sampleRate / source.sampleRate) + 32;
49
+ AVAudioPCMBuffer *pcm = [[AVAudioPCMBuffer alloc] initWithPCMFormat:format frameCapacity:capacity];
50
+ __block BOOL sent = NO;
51
+ [converter convertToBuffer:pcm error:NULL withInputFromBlock:^AVAudioBuffer *(AVAudioPacketCount, AVAudioConverterInputStatus *status) {
52
+ *status = sent ? AVAudioConverterInputStatus_NoDataNow : AVAudioConverterInputStatus_HaveData;
53
+ if (sent) return nil;
54
+ sent = YES;
55
+ return buffer;
56
+ }];
57
+ if (!pcm.frameLength) return;
58
+ std::lock_guard lock(tracksMutex);
59
+ for (const auto track : tracks) track_inject_pcm(track, pcm.int16ChannelData[0], pcm.frameLength);
60
+ }];
61
+ if (![engine startAndReturnError:NULL]) {
62
+ [input removeTapOnBus:0];
63
+ [session setActive:NO error:NULL];
64
+ return;
65
+ }
66
+ capture = engine;
67
+ }
68
+
69
+ void requestCapture() {
70
+ AVAudioSession *session = AVAudioSession.sharedInstance;
71
+ if (session.recordPermission == AVAudioSessionRecordPermissionGranted) {
72
+ startCapture();
73
+ } else if (session.recordPermission == AVAudioSessionRecordPermissionUndetermined && !requestingPermission) {
74
+ requestingPermission = true;
75
+ [session requestRecordPermission:^(BOOL granted) {
76
+ dispatch_async(dispatch_get_main_queue(), ^{
77
+ requestingPermission = false;
78
+ if (granted) startCapture();
79
+ });
80
+ }];
81
+ }
82
+ }
83
+
84
+ void attach(NativeMediaTrackHandle track) {
85
+ {
86
+ std::lock_guard lock(tracksMutex);
87
+ tracks.insert(track);
88
+ }
89
+ static dispatch_once_t observers;
90
+ dispatch_once(&observers, ^{
91
+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
92
+ [center addObserverForName:UISceneDidEnterBackgroundNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(__unused NSNotification *note) {
93
+ stopCapture();
94
+ }];
95
+ });
96
+ requestCapture();
97
+ }
98
+
99
+ void detach(NativeMediaTrackHandle track) {
100
+ {
101
+ std::lock_guard lock(tracksMutex);
102
+ tracks.erase(track);
103
+ }
104
+ if (!hasTracks()) stopCapture();
105
+ }
106
+ } // namespace
107
+
108
+ void platform_attach_track(NativeMediaTrackHandle track) {
109
+ if (NSThread.isMainThread) attach(track);
110
+ else dispatch_async(dispatch_get_main_queue(), ^{ attach(track); });
111
+ }
112
+
113
+ void platform_detach_track(NativeMediaTrackHandle track) {
114
+ if (NSThread.isMainThread) detach(track);
115
+ else dispatch_async(dispatch_get_main_queue(), ^{ detach(track); });
116
+ }
117
+ } // namespace gea::host::media
@@ -0,0 +1,34 @@
1
+ // Compile the common Apple WebSocket provider in this translation unit so
2
+ // binary sends share its live URLSession, admission checks and queue accounting.
3
+ #include "host/websocket_apple.mm"
4
+
5
+ extern "C" bool gea_ios_websocket_send_binary_base64(const gea::host::WebSocket &socket, const std::string &base64) {
6
+ using namespace gea::host::websocket;
7
+ const auto state = apple::find(socket.nativeHandle);
8
+ if (!state) return false;
9
+ NSString *encoded = [[NSString alloc] initWithBytes:base64.data() length:base64.size() encoding:NSUTF8StringEncoding];
10
+ NSData *data = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
11
+ if (!data.length) return false;
12
+
13
+ NSURLSessionWebSocketTask *task;
14
+ {
15
+ std::lock_guard lock(state->mutex);
16
+ if (state->stopped || !state->opened || state->sending || data.length > apple::maxBuffered - state->bytes) return false;
17
+ task = state->task;
18
+ state->bytes += data.length;
19
+ }
20
+
21
+ const auto size = data.length;
22
+ std::weak_ptr<apple::State> weak = state;
23
+ [task sendMessage:[[NSURLSessionWebSocketMessage alloc] initWithData:data] completionHandler:^(NSError *error) {
24
+ if (auto current = weak.lock()) {
25
+ if (error) {
26
+ current->failed("WebSocket binary send failed");
27
+ return;
28
+ }
29
+ std::lock_guard lock(current->mutex);
30
+ if (!current->stopped) current->bytes -= size;
31
+ }
32
+ }];
33
+ return true;
34
+ }