@geastack/host 0.1.30 → 0.1.32

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/host/display.cpp CHANGED
@@ -44,6 +44,29 @@ void DisplayBackend::setBrightness(double brightness) {
44
44
  gea::platform::display::Display::setBrightness(static_cast<int>(brightness));
45
45
  }
46
46
 
47
+ // Panel power hooks. Weak defaults keep the surface on every target; a board
48
+ // whose panel can sleep provides the strong definitions in its display driver
49
+ // (display-off + sleep-in, stop presenting, resume on wake).
50
+ extern "C" __attribute__((weak)) void gea_display_set_powered(int on) {
51
+ (void)on;
52
+ }
53
+
54
+ extern "C" __attribute__((weak)) int gea_display_powered(void) {
55
+ return 1;
56
+ }
57
+
58
+ void DisplayBackend::sleep() {
59
+ gea_display_set_powered(0);
60
+ }
61
+
62
+ void DisplayBackend::wake() {
63
+ gea_display_set_powered(1);
64
+ }
65
+
66
+ bool DisplayBackend::awake() {
67
+ return gea_display_powered() != 0;
68
+ }
69
+
47
70
  void DisplayBackend::setAA(double samples) {
48
71
  gea::platform::display::Display::setAA(static_cast<int>(samples));
49
72
  }
package/host/http.cpp CHANGED
@@ -131,6 +131,158 @@ void runRequests() {
131
131
  }
132
132
  }
133
133
 
134
+ namespace {
135
+
136
+ std::mutex &bundleMutex() {
137
+ static std::mutex m;
138
+ return m;
139
+ }
140
+
141
+ std::vector<const HttpEmbeddedBundle *> &bundleTable() {
142
+ static std::vector<const HttpEmbeddedBundle *> table;
143
+ return table;
144
+ }
145
+
146
+ const HttpEmbeddedAsset *findAsset(const HttpEmbeddedBundle &bundle,
147
+ std::string_view path) {
148
+ for (std::size_t i = 0; i < bundle.count; ++i) {
149
+ if (bundle.assets[i].path && path == bundle.assets[i].path)
150
+ return &bundle.assets[i];
151
+ }
152
+ return nullptr;
153
+ }
154
+
155
+ // RFC 9110 If-None-Match: "*" or a comma-separated list of entity tags; weak
156
+ // comparison, so W/"x" matches "x".
157
+ bool etagMatches(std::string_view header, std::string_view etag) {
158
+ if (etag.empty() || header.empty())
159
+ return false;
160
+ std::size_t begin = 0;
161
+ while (begin < header.size()) {
162
+ auto end = header.find(',', begin);
163
+ if (end == std::string_view::npos)
164
+ end = header.size();
165
+ auto tag = header.substr(begin, end - begin);
166
+ while (!tag.empty() && (tag.front() == ' ' || tag.front() == '\t'))
167
+ tag.remove_prefix(1);
168
+ while (!tag.empty() && (tag.back() == ' ' || tag.back() == '\t'))
169
+ tag.remove_suffix(1);
170
+ if (tag == "*")
171
+ return true;
172
+ if (tag.substr(0, 2) == "W/")
173
+ tag.remove_prefix(2);
174
+ if (tag == etag)
175
+ return true;
176
+ begin = end + 1;
177
+ }
178
+ return false;
179
+ }
180
+
181
+ } // namespace
182
+
183
+ bool register_embedded_bundle(const HttpEmbeddedBundle *bundle) {
184
+ if (!bundle || !bundle->name)
185
+ return false;
186
+ std::lock_guard<std::mutex> lock(bundleMutex());
187
+ for (auto &entry : bundleTable()) {
188
+ if (std::string_view(entry->name) == bundle->name) {
189
+ entry = bundle;
190
+ return true;
191
+ }
192
+ }
193
+ bundleTable().push_back(bundle);
194
+ return true;
195
+ }
196
+
197
+ const HttpEmbeddedBundle *find_embedded_bundle(std::string_view name) {
198
+ std::lock_guard<std::mutex> lock(bundleMutex());
199
+ for (const auto *bundle : bundleTable()) {
200
+ if (name == bundle->name)
201
+ return bundle;
202
+ }
203
+ return nullptr;
204
+ }
205
+
206
+ EmbeddedAssetResponse resolve_embedded_asset(std::string_view file,
207
+ std::string_view ifNoneMatch) {
208
+ EmbeddedAssetResponse response;
209
+ if (!is_embedded_asset_file(file))
210
+ return response;
211
+ auto rest = file.substr(kEmbeddedAssetScheme.size());
212
+ const auto slash = rest.find('/');
213
+ const auto name = rest.substr(0, slash);
214
+ std::string_view path =
215
+ slash == std::string_view::npos ? std::string_view("/")
216
+ : rest.substr(slash);
217
+ const HttpEmbeddedBundle *bundle = find_embedded_bundle(name);
218
+ if (!bundle)
219
+ return response;
220
+ if (path.empty() || path == "/")
221
+ path = "/index.html";
222
+ const HttpEmbeddedAsset *asset = findAsset(*bundle, path);
223
+ if (!asset && bundle->fallback) {
224
+ const auto lastSlash = path.rfind('/');
225
+ const auto segment =
226
+ lastSlash == std::string_view::npos ? path : path.substr(lastSlash + 1);
227
+ // A route ("/apps", "/settings/wifi") reloads the app; a missing file
228
+ // ("/assets/old-1a2b.js", "/favicon.ico") stays a 404, so a stale hashed
229
+ // name never comes back as HTML parsed as script.
230
+ if (segment.find('.') == std::string_view::npos)
231
+ asset = findAsset(*bundle, bundle->fallback);
232
+ }
233
+ if (!asset)
234
+ return response;
235
+
236
+ response.asset = asset;
237
+ response.contentType =
238
+ asset->contentType ? asset->contentType : "application/octet-stream";
239
+ if (asset->gzip)
240
+ response.headers.push_back({"Content-Encoding", "gzip"});
241
+ response.headers.push_back({"Vary", "Accept-Encoding"});
242
+ response.headers.push_back(
243
+ {"Cache-Control", asset->immutable ? "public, max-age=31536000, immutable"
244
+ : "no-cache"});
245
+ if (asset->etag && *asset->etag)
246
+ response.headers.push_back({"ETag", asset->etag});
247
+ response.status =
248
+ asset->etag && etagMatches(ifNoneMatch, asset->etag) ? 304 : 200;
249
+ return response;
250
+ }
251
+
252
+ const char *status_reason(int status) {
253
+ switch (status) {
254
+ case 200: return "OK";
255
+ case 201: return "Created";
256
+ case 202: return "Accepted";
257
+ case 204: return "No Content";
258
+ case 206: return "Partial Content";
259
+ case 301: return "Moved Permanently";
260
+ case 302: return "Found";
261
+ case 303: return "See Other";
262
+ case 304: return "Not Modified";
263
+ case 307: return "Temporary Redirect";
264
+ case 308: return "Permanent Redirect";
265
+ case 400: return "Bad Request";
266
+ case 401: return "Unauthorized";
267
+ case 403: return "Forbidden";
268
+ case 404: return "Not Found";
269
+ case 405: return "Method Not Allowed";
270
+ case 409: return "Conflict";
271
+ case 410: return "Gone";
272
+ case 413: return "Content Too Large";
273
+ case 415: return "Unsupported Media Type";
274
+ case 422: return "Unprocessable Content";
275
+ case 423: return "Locked";
276
+ case 429: return "Too Many Requests";
277
+ case 500: return "Internal Server Error";
278
+ case 501: return "Not Implemented";
279
+ case 502: return "Bad Gateway";
280
+ case 503: return "Service Unavailable";
281
+ case 504: return "Gateway Timeout";
282
+ default: return "";
283
+ }
284
+ }
285
+
134
286
  HttpReply test_dispatch(NativeHttpServerHandle handle,
135
287
  const std::string &method, const std::string &path,
136
288
  const std::string &query) {
@@ -204,27 +356,66 @@ std::string methodName(int method) {
204
356
  }
205
357
  }
206
358
 
207
- const char *statusLine(int status) {
208
- switch (status) {
209
- case 200:
210
- return "200 OK";
211
- case 204:
212
- return "204 No Content";
213
- case 302:
214
- return "302 Found";
215
- case 303:
216
- return "303 See Other";
217
- case 400:
218
- return "400 Bad Request";
219
- case 404:
220
- return "404 Not Found";
221
- case 500:
222
- return "500 Internal Server Error";
223
- case 504:
224
- return "504 Gateway Timeout";
225
- default:
226
- return "200 OK";
359
+ // "404 Not Found". httpd_resp_set_status keeps the pointer until the reply
360
+ // is sent, so the caller holds the returned string for the whole send. Every
361
+ // status the app returns goes out as itself: an unknown code is still sent
362
+ // with its own number (an API 401/409/429 must never leave as "200 OK").
363
+ std::string statusLine(int status) {
364
+ if (status < 100 || status > 999)
365
+ status = 500;
366
+ const char *reason = status_reason(status);
367
+ std::string line = std::to_string(status);
368
+ line += ' ';
369
+ line += *reason ? reason : "Status";
370
+ return line;
371
+ }
372
+
373
+ bool sameHeaderName(const std::string &a, const char *b) {
374
+ const std::size_t n = std::strlen(b);
375
+ if (a.size() != n)
376
+ return false;
377
+ for (std::size_t i = 0; i < n; ++i) {
378
+ char x = a[i], y = b[i];
379
+ if (x >= 'A' && x <= 'Z')
380
+ x = static_cast<char>(x - 'A' + 'a');
381
+ if (y >= 'A' && y <= 'Z')
382
+ y = static_cast<char>(y - 'A' + 'a');
383
+ if (x != y)
384
+ return false;
227
385
  }
386
+ return true;
387
+ }
388
+
389
+ // Serve a compiled-in bundle file straight out of flash .rodata. Content-Type,
390
+ // encoding and caching come from the bundle; the app's own headers are added
391
+ // unless they name one of those.
392
+ esp_err_t sendEmbedded(httpd_req_t *r, const HttpRequest &req,
393
+ const HttpReply &reply) {
394
+ const EmbeddedAssetResponse resolved = resolve_embedded_asset(
395
+ reply.file, find_header(req.headers, "If-None-Match"));
396
+ const std::string status = statusLine(resolved.status);
397
+ httpd_resp_set_status(r, status.c_str());
398
+ if (!resolved.asset) {
399
+ httpd_resp_set_type(r, "text/plain");
400
+ return httpd_resp_sendstr(r, "Not found");
401
+ }
402
+ httpd_resp_set_type(r, resolved.contentType.c_str());
403
+ for (const auto &header : resolved.headers)
404
+ httpd_resp_set_hdr(r, header.name.c_str(), header.value.c_str());
405
+ for (const auto &header : reply.headers) {
406
+ if (!validHttpHeader(header))
407
+ continue;
408
+ bool owned = sameHeaderName(header.name, "Content-Type");
409
+ for (const auto &mine : resolved.headers)
410
+ owned = owned || sameHeaderName(header.name, mine.name.c_str());
411
+ if (!owned)
412
+ httpd_resp_set_hdr(r, header.name.c_str(), header.value.c_str());
413
+ }
414
+ if (resolved.status == 304 || req.method == "HEAD")
415
+ return httpd_resp_send(r, nullptr, 0);
416
+ return httpd_resp_send(
417
+ r, reinterpret_cast<const char *>(resolved.asset->data),
418
+ static_cast<ssize_t>(resolved.asset->size));
228
419
  }
229
420
 
230
421
  // Stream a file from disk to the client in chunks, so multi-MB recordings never
@@ -237,17 +428,19 @@ esp_err_t sendFile(httpd_req_t *r, const HttpReply &reply) {
237
428
  httpd_resp_sendstr(r, "File not found");
238
429
  return ESP_OK;
239
430
  }
240
- httpd_resp_set_status(r, statusLine(reply.status));
431
+ const std::string status = statusLine(reply.status);
432
+ httpd_resp_set_status(r, status.c_str());
241
433
  httpd_resp_set_type(r, reply.contentType.c_str());
242
434
  for (const auto &header : reply.headers) {
243
435
  if (validHttpHeader(header))
244
436
  httpd_resp_set_hdr(r, header.name.c_str(), header.value.c_str());
245
437
  }
246
- if (!reply.download.empty()) {
247
- const std::string disposition =
248
- "attachment; filename=\"" + reply.download + "\"";
438
+ const std::string disposition =
439
+ reply.download.empty()
440
+ ? std::string()
441
+ : "attachment; filename=\"" + reply.download + "\"";
442
+ if (!disposition.empty())
249
443
  httpd_resp_set_hdr(r, "Content-Disposition", disposition.c_str());
250
- }
251
444
  auto *buffer = static_cast<char *>(std::malloc(kStreamChunkBytes));
252
445
  if (!buffer) {
253
446
  std::fclose(f);
@@ -300,8 +493,9 @@ esp_err_t wildcardHandler(httpd_req_t *r) {
300
493
  #else
301
494
  // Older IDF does not expose header enumeration; retain the standard fields
302
495
  // needed by device upload handlers without using private httpd structures.
303
- for (const char *name : {"Host", "Content-Type", "Content-Length",
304
- "X-File-Name", "Authorization", "Origin"}) {
496
+ for (const char *name :
497
+ {"Host", "Content-Type", "Content-Length", "X-File-Name",
498
+ "Authorization", "Origin", "If-None-Match", "Accept-Encoding"}) {
305
499
  const auto length = httpd_req_get_hdr_value_len(r, name);
306
500
  if (!length)
307
501
  continue;
@@ -330,24 +524,34 @@ esp_err_t wildcardHandler(httpd_req_t *r) {
330
524
  received += static_cast<std::size_t>(count);
331
525
  }
332
526
 
527
+ // The embedded-asset path needs the request's validators after the
528
+ // rendezvous; keep the method and headers, the body has been consumed.
529
+ HttpRequest meta;
530
+ meta.method = req.method;
531
+ meta.headers = req.headers;
532
+
333
533
  const HttpReply reply = dispatchAndWait(
334
534
  server, std::move(req), kRendezvousTimeoutMs, kRendezvousPollMs,
335
535
  [](int ms) { vTaskDelay(pdMS_TO_TICKS(ms)); });
336
536
 
537
+ if (is_embedded_asset_file(reply.file))
538
+ return sendEmbedded(r, meta, reply);
337
539
  if (!reply.file.empty())
338
540
  return sendFile(r, reply);
339
541
 
340
- httpd_resp_set_status(r, statusLine(reply.status));
542
+ const std::string status = statusLine(reply.status);
543
+ httpd_resp_set_status(r, status.c_str());
341
544
  httpd_resp_set_type(r, reply.contentType.c_str());
342
545
  for (const auto &header : reply.headers) {
343
546
  if (validHttpHeader(header))
344
547
  httpd_resp_set_hdr(r, header.name.c_str(), header.value.c_str());
345
548
  }
346
- if (!reply.download.empty()) {
347
- const std::string disposition =
348
- "attachment; filename=\"" + reply.download + "\"";
549
+ const std::string disposition =
550
+ reply.download.empty()
551
+ ? std::string()
552
+ : "attachment; filename=\"" + reply.download + "\"";
553
+ if (!disposition.empty())
349
554
  httpd_resp_set_hdr(r, "Content-Disposition", disposition.c_str());
350
- }
351
555
  httpd_resp_send(r, reply.body.data(), reply.body.size());
352
556
  return ESP_OK;
353
557
  }
@@ -0,0 +1,199 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // UNUserNotificationCenter backend for `LocalNotifications` (LocalNotificationsDriver
3
+ // in host/local_notifications.h) on iOS and macOS.
4
+ //
5
+ // Nothing here blocks the frame thread. permission() answers from a cached
6
+ // authorization status that UNUserNotificationCenter refreshes asynchronously
7
+ // (at most once a second while the app keeps asking, so a change made in
8
+ // Settings shows up on its own); requestPermission(), post() and cancelAll()
9
+ // hand their work to the center and return at once.
10
+ //
11
+ // The center needs a bundled app with a bundle identifier — touching it from a
12
+ // bare executable throws — so without one the driver reports "unsupported".
13
+ // The delegate presents banners while the app is in the foreground: a
14
+ // notification the app posts on itself then also lands in Notification Center,
15
+ // which is what ANCS forwards to a paired accessory.
16
+ #if defined(__APPLE__)
17
+
18
+ #import <Foundation/Foundation.h>
19
+ #import <UserNotifications/UserNotifications.h>
20
+
21
+ #include <atomic>
22
+ #include <string>
23
+
24
+ #include "host/local_notifications.h"
25
+
26
+ __asm__(".linker_option \"-framework\", \"UserNotifications\"");
27
+
28
+ @interface GeaLocalNotificationsDelegate : NSObject <UNUserNotificationCenterDelegate>
29
+ @end
30
+
31
+ @implementation GeaLocalNotificationsDelegate
32
+
33
+ - (void)userNotificationCenter:(UNUserNotificationCenter *)center
34
+ willPresentNotification:(UNNotification *)notification
35
+ withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
36
+ (void)center;
37
+ (void)notification;
38
+ UNNotificationPresentationOptions options = UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge;
39
+ if (@available(iOS 14.0, macOS 11.0, tvOS 14.0, *)) {
40
+ options |= UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionList;
41
+ } else {
42
+ #pragma clang diagnostic push
43
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
44
+ options |= UNNotificationPresentationOptionAlert;
45
+ #pragma clang diagnostic pop
46
+ }
47
+ completionHandler(options);
48
+ }
49
+
50
+ - (void)userNotificationCenter:(UNUserNotificationCenter *)center
51
+ didReceiveNotificationResponse:(UNNotificationResponse *)response
52
+ withCompletionHandler:(void (^)(void))completionHandler {
53
+ (void)center;
54
+ (void)response;
55
+ completionHandler();
56
+ }
57
+
58
+ @end
59
+
60
+ namespace gea::host {
61
+ namespace {
62
+
63
+ enum Status : int { kUnknown = 0, kUndetermined, kGranted, kDenied, kUnsupported };
64
+
65
+ class AppleLocalNotificationsDriver final : public LocalNotificationsDriver {
66
+ public:
67
+ std::string permission() override {
68
+ UNUserNotificationCenter *center = this->center();
69
+ if (!center) return "unsupported";
70
+ refresh(center, false);
71
+ switch (status_.load()) {
72
+ case kGranted: return "granted";
73
+ case kDenied: return "denied";
74
+ case kUnsupported: return "unsupported";
75
+ default: return "undetermined";
76
+ }
77
+ }
78
+
79
+ void requestPermission() override {
80
+ UNUserNotificationCenter *center = this->center();
81
+ if (!center) return;
82
+ UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
83
+ [center requestAuthorizationWithOptions:options
84
+ completionHandler:^(BOOL granted, NSError *error) {
85
+ (void)error;
86
+ // The answer is final for this prompt; record it now and
87
+ // let the settings read confirm (provisional, ephemeral).
88
+ status_.store(granted ? kGranted : kDenied);
89
+ refresh(center, true);
90
+ }];
91
+ }
92
+
93
+ double post(const std::string &title, const std::string &body, double delaySeconds) override {
94
+ UNUserNotificationCenter *center = this->center();
95
+ if (!center || (title.empty() && body.empty())) return 0;
96
+ refresh(center, false);
97
+ const int status = status_.load();
98
+ if (status == kDenied || status == kUnsupported) return 0;
99
+
100
+ const double id = static_cast<double>(++lastId_);
101
+ UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
102
+ content.title = string(title);
103
+ content.body = string(body);
104
+ content.sound = UNNotificationSound.defaultSound;
105
+ // nil trigger = deliver now; a time-interval trigger must be positive.
106
+ UNNotificationTrigger *trigger =
107
+ delaySeconds > 0 ? [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:delaySeconds repeats:NO] : nil;
108
+ NSString *identifier = [NSString stringWithFormat:@"gea.local.%@.%.0f", launchTag(), id];
109
+ UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
110
+ content:content
111
+ trigger:trigger];
112
+ [center addNotificationRequest:request
113
+ withCompletionHandler:^(NSError *error) {
114
+ if (error) NSLog(@"[gea] LocalNotifications.post failed: %@", error.localizedDescription);
115
+ }];
116
+ return id;
117
+ }
118
+
119
+ void cancelAll() override {
120
+ UNUserNotificationCenter *center = this->center();
121
+ if (!center) return;
122
+ [center removeAllPendingNotificationRequests];
123
+ [center removeAllDeliveredNotifications];
124
+ }
125
+
126
+ // Called once from the main queue at launch: claim the delegate before any
127
+ // notification arrives and read the authorization status ahead of the first
128
+ // frame that asks for it.
129
+ void prepare() {
130
+ if (UNUserNotificationCenter *center = this->center()) refresh(center, true);
131
+ }
132
+
133
+ private:
134
+ static NSString *string(const std::string &text) {
135
+ return [[NSString alloc] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding] ?: @"";
136
+ }
137
+
138
+ // Unique per launch, so ids restarting at 1 never replace a notification an
139
+ // earlier run left pending.
140
+ static NSString *launchTag() {
141
+ static NSString *tag =
142
+ [NSString stringWithFormat:@"%llx", static_cast<unsigned long long>(NSDate.date.timeIntervalSince1970 * 1000)];
143
+ return tag;
144
+ }
145
+
146
+ UNUserNotificationCenter *center() {
147
+ if (status_.load() == kUnsupported) return nil;
148
+ if (center_) return center_;
149
+ if (!NSBundle.mainBundle.bundleIdentifier) {
150
+ status_.store(kUnsupported);
151
+ return nil;
152
+ }
153
+ center_ = UNUserNotificationCenter.currentNotificationCenter;
154
+ delegate_ = [[GeaLocalNotificationsDelegate alloc] init];
155
+ center_.delegate = delegate_;
156
+ return center_;
157
+ }
158
+
159
+ void refresh(UNUserNotificationCenter *center, bool force) {
160
+ const double now = NSDate.timeIntervalSinceReferenceDate;
161
+ if (!force && (refreshing_.load() || now - lastRefresh_.load() < 1.0)) return;
162
+ refreshing_.store(true);
163
+ lastRefresh_.store(now);
164
+ [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
165
+ switch (settings.authorizationStatus) {
166
+ case UNAuthorizationStatusNotDetermined: status_.store(kUndetermined); break;
167
+ case UNAuthorizationStatusDenied: status_.store(kDenied); break;
168
+ default: status_.store(kGranted); break; // authorized, provisional, ephemeral
169
+ }
170
+ refreshing_.store(false);
171
+ }];
172
+ }
173
+
174
+ UNUserNotificationCenter *center_ = nil;
175
+ GeaLocalNotificationsDelegate *delegate_ = nil;
176
+ std::atomic<int> status_{kUnknown};
177
+ std::atomic<bool> refreshing_{false};
178
+ std::atomic<double> lastRefresh_{0};
179
+ std::atomic<long long> lastId_{0};
180
+ };
181
+
182
+ AppleLocalNotificationsDriver &appleLocalNotifications() {
183
+ static AppleLocalNotificationsDriver driver;
184
+ return driver;
185
+ }
186
+
187
+ [[maybe_unused]] const bool installed = [] {
188
+ setLocalNotificationsDriver(&appleLocalNotifications());
189
+ // Runs once the app's main run loop starts, before the user can interact.
190
+ dispatch_async(dispatch_get_main_queue(), ^{
191
+ appleLocalNotifications().prepare();
192
+ });
193
+ return true;
194
+ }();
195
+
196
+ } // namespace
197
+ } // namespace gea::host
198
+
199
+ #endif
package/host/media.cpp CHANGED
@@ -699,6 +699,69 @@ void TrackPcmReader::beginDrain() {
699
699
  cursor->second.end = it->second.bufferStart + it->second.ringBuffer.size();
700
700
  }
701
701
 
702
+ namespace {
703
+ std::mutex &inputDeviceMutex() {
704
+ static std::mutex mutex;
705
+ return mutex;
706
+ }
707
+
708
+ std::string &inputDevice() {
709
+ static std::string device;
710
+ return device;
711
+ }
712
+
713
+ int &inputChannel() {
714
+ static int channel = -1;
715
+ return channel;
716
+ }
717
+ } // namespace
718
+
719
+ #ifndef ESP_PLATFORM
720
+ __attribute__((weak)) std::vector<MediaDeviceInfo> platform_input_devices() { return {}; }
721
+ __attribute__((weak)) void platform_input_device_changed() {}
722
+ #else
723
+ std::vector<MediaDeviceInfo> platform_input_devices() { return {}; }
724
+ void platform_input_device_changed() {}
725
+ #endif
726
+
727
+ std::vector<MediaDeviceInfo> enumerate_devices() {
728
+ auto inputs = platform_input_devices();
729
+ if (inputs.empty()) return inputs;
730
+ std::vector<MediaDeviceInfo> out;
731
+ out.reserve(inputs.size() + 1);
732
+ // As in a browser, the system default comes first under its own id; its label names the device it is now.
733
+ out.push_back(MediaDeviceInfo{"default", "audioinput", inputs.front().label, inputs.front().groupId,
734
+ inputs.front().channelCount});
735
+ for (auto &input : inputs) out.push_back(std::move(input));
736
+ return out;
737
+ }
738
+
739
+ std::string requested_input_device() {
740
+ std::lock_guard<std::mutex> lock(inputDeviceMutex());
741
+ return inputDevice();
742
+ }
743
+
744
+ int requested_input_channel() {
745
+ std::lock_guard<std::mutex> lock(inputDeviceMutex());
746
+ return inputChannel();
747
+ }
748
+
749
+ NativeMediaStreamHandle get_user_media_audio(const std::string &deviceId) { return get_user_media_audio(deviceId, -1); }
750
+
751
+ NativeMediaStreamHandle get_user_media_audio(const std::string &deviceId, int channel) {
752
+ const std::string next = deviceId == "default" ? std::string() : deviceId;
753
+ const int nextChannel = channel < 0 ? -1 : channel;
754
+ bool changed = false;
755
+ {
756
+ std::lock_guard<std::mutex> lock(inputDeviceMutex());
757
+ changed = inputDevice() != next || inputChannel() != nextChannel;
758
+ inputDevice() = next;
759
+ inputChannel() = nextChannel;
760
+ }
761
+ if (changed) platform_input_device_changed();
762
+ return get_user_media_audio();
763
+ }
764
+
702
765
  NativeMediaStreamHandle get_user_media_audio() {
703
766
  const auto handle = create_stream();
704
767
  const auto owner = workers::Context::current();
@@ -30,6 +30,7 @@ static double gCustomMenu = -1;
30
30
  @property(nonatomic, weak) NSWindow *window;
31
31
  @property(nonatomic, strong) NSTimer *timer;
32
32
  @property(nonatomic, strong) NSMenu *menu;
33
+ @property(nonatomic, strong) id keyMonitor;
33
34
  @end
34
35
 
35
36
  @implementation GeaMenuBar
@@ -83,17 +84,22 @@ static double gCustomMenu = -1;
83
84
  quit.target = NSApp;
84
85
  [self.menu addItem:quit];
85
86
 
86
- [NSNotificationCenter.defaultCenter addObserver:self
87
- selector:@selector(resigned:)
88
- name:NSApplicationDidResignActiveNotification
89
- object:nil];
90
-
91
- // Another of the app's windows (a `<window>` element) taking the keyboard
92
- // closes the panel, the way clicking into another app does.
93
- [NSNotificationCenter.defaultCenter addObserver:self
94
- selector:@selector(otherWindowBecameKey:)
95
- name:NSWindowDidBecomeKeyNotification
96
- object:nil];
87
+ // A menu bar app has no menu of its own in the main menu bar, so AppKit never
88
+ // matches its menu's shortcuts (Cmd+D in `shortcut: "Cmd+D"`) while that menu
89
+ // is closed. While the app is active, a key press with Command, Control or
90
+ // Option goes to that menu first, as it would to a regular app's main menu.
91
+ __weak GeaMenuBar *weakSelf = self;
92
+ self.keyMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown
93
+ handler:^NSEvent *(NSEvent *event) {
94
+ const NSEventModifierFlags flags = event.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask;
95
+ if (!(flags & (NSEventModifierFlagCommand | NSEventModifierFlagControl | NSEventModifierFlagOption))) return event;
96
+ NSMenu *menu = [weakSelf secondaryMenu];
97
+ if (menu && [menu performKeyEquivalent:event]) return nil;
98
+ return event;
99
+ }];
100
+
101
+ // The panel stays open while you work in other apps or windows: only a click
102
+ // on the icon (or hide()) closes it.
97
103
 
98
104
  self.timer = [NSTimer timerWithTimeInterval:kHiddenTick
99
105
  target:self
@@ -161,15 +167,6 @@ static double gCustomMenu = -1;
161
167
  [self.window orderOut:nil];
162
168
  }
163
169
 
164
- - (void)resigned:(NSNotification *)notification {
165
- [self hide];
166
- }
167
-
168
- - (void)otherWindowBecameKey:(NSNotification *)notification {
169
- NSWindow *window = notification.object;
170
- if (window != self.window && window.canBecomeMainWindow && self.shown) [self hide];
171
- }
172
-
173
170
  - (void)tickWhileHidden:(NSTimer *)timer {
174
171
  if (self.shown) return;
175
172
  id delegate = NSApp.delegate;