@geastack/apple 0.2.33 → 0.2.34

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.
@@ -1,4 +1,7 @@
1
1
  #include <cstdio>
2
+ #include "host/files.h"
3
+ #include "host/menu_bar.h"
4
+ #include "host/menu_bar.h"
2
5
  #include "host/timers.h"
3
6
  #include "host/worker.h"
4
7
  #include "ui/tree_events.h"
@@ -120,6 +123,11 @@ static int geaKeyboardTarget(int root) {
120
123
  return root;
121
124
  }
122
125
  #include "macos_key_event.h"
126
+ #include "macos_content_view.h"
127
+ #include "macos_windows.h"
128
+ // The app's `cssDevicePixelRatio` (window.json): points per CSS px, 1 unless
129
+ // the app declares another. The window size stays in points.
130
+ static double gMacosCssDevicePixelRatio = 1.0;
123
131
  // Authored silhouettes own their press layer; a rectangular engine fill would
124
132
  // paint outside their transparent corners. Ancestors cover image/text hits.
125
133
  static bool geaOwnsContourPress(int x, int y) {
@@ -128,16 +136,16 @@ static bool geaOwnsContourPress(int x, int y) {
128
136
  if (std::strcmp(tree.getAttribute(id,"data-gea-contour"),"true")==0) return true;
129
137
  return false;
130
138
  }
131
- @interface GeaContentView : NSView <NSTextInputClient>
132
- @property(nonatomic,copy) NSAttributedString *geaMarkedText;
133
- @property(nonatomic) BOOL geaInterpretingDispatchedKey;
134
- @property(nonatomic,strong) GCController *geaActiveController;
135
- @property(nonatomic) unsigned int geaGamepadButtons;
136
- @property(nonatomic) NSTimeInterval geaGamepadRepeat;
137
- @property(nonatomic,strong) id geaCursorMonitor;
138
- @property(nonatomic,strong) NSTrackingArea *geaPointerTracking;
139
- @end
140
139
  @implementation GeaContentView
140
+ - (instancetype)initWithFrame:(NSRect)frame {
141
+ if ((self = [super initWithFrame:frame])) _geaHostedRoot = -1;
142
+ return self;
143
+ }
144
+ // The keyboard root of this view: a `<window>`'s node for the content view of
145
+ // that window (macos_windows.mm), else the main window's (custom editor or
146
+ // mounted root). App-owned editors (data-gea-inputs) belong to the main window.
147
+ - (int)geaInputRoot { return self.geaHostedRoot >= 0 ? self.geaHostedRoot : geaKeyboardInputRoot(); }
148
+ - (int)geaCustomRoot { return self.geaHostedRoot >= 0 ? -1 : geaCustomInputRoot(); }
141
149
  // Optional app cursor is scoped to the content bounds; AppKit restores the
142
150
  // standard pointer over the title bar, other windows, and other applications.
143
151
  - (void)resetCursorRects {
@@ -199,7 +207,7 @@ static bool geaOwnsContourPress(int x, int y) {
199
207
  auto &tree=gea::embedded::ui::Tree::instance();
200
208
  const bool inside=NSPointInRect(point,view.bounds);
201
209
  const int x=std::lround(point.x), y=std::lround(view.bounds.size.height-point.y);
202
- if (!std::getenv("GEA_MACOS_REPLAY_PLAN") && geaCustomInputRoot()>=0) {
210
+ if (!std::getenv("GEA_MACOS_REPLAY_PLAN") && [view geaCustomRoot]>=0) {
203
211
  tree.pointerHover(inside?x:-1,inside?y:-1);
204
212
  if (event.type==NSEventTypeLeftMouseDown && inside && !geaOwnsContourPress(x,y)) tree.pointerDown(x,y);
205
213
  if (event.type==NSEventTypeLeftMouseUp) { tree.pointerUp(); gea::embedded::ui::StyleSheet::instance().hoverChanged(); }
@@ -228,14 +236,14 @@ static bool geaOwnsContourPress(int x, int y) {
228
236
  [self addTrackingArea:self.geaPointerTracking];
229
237
  }
230
238
  - (void)mouseExited:(NSEvent *)event {
231
- if (geaCustomInputRoot()>=0 && !std::getenv("GEA_MACOS_REPLAY_PLAN")) gea::embedded::ui::Tree::instance().pointerHover(-1,-1);
239
+ if ([self geaCustomRoot]>=0 && !std::getenv("GEA_MACOS_REPLAY_PLAN")) gea::embedded::ui::Tree::instance().pointerHover(-1,-1);
232
240
  [super mouseExited:event];
233
241
  }
234
242
  - (void)dealloc {
235
243
  if (self.geaCursorMonitor) [NSEvent removeMonitor:self.geaCursorMonitor];
236
244
  }
237
245
  - (void)geaPollGamepad {
238
- if (!NSApp.isActive || !self.window.isKeyWindow || geaCustomInputRoot()<0) {
246
+ if (!NSApp.isActive || !self.window.isKeyWindow || [self geaCustomRoot]<0) {
239
247
  self.geaGamepadButtons=0; self.geaGamepadRepeat=0; return;
240
248
  }
241
249
  GCController *controller=nil;
@@ -261,17 +269,23 @@ static bool geaOwnsContourPress(int x, int y) {
261
269
  for(int i=0;i<15;i++) if(pressed & (1u<<i)) [self geaSendKey:2000+i];
262
270
  }
263
271
  - (BOOL)isFlipped { return NO; }
264
- - (BOOL)acceptsFirstResponder { return geaKeyboardInputRoot()>=0; }
265
- - (BOOL)becomeFirstResponder {const BOOL accepted=[super becomeFirstResponder];if(accepted)gea::macos::nativeRootFocusChanged(self,true,geaKeyboardTarget(geaKeyboardInputRoot()));return accepted;}
272
+ - (BOOL)acceptsFirstResponder { return [self geaInputRoot]>=0; }
273
+ - (BOOL)becomeFirstResponder {const BOOL accepted=[super becomeFirstResponder];if(accepted)gea::macos::nativeRootFocusChanged(self,true,geaKeyboardTarget([self geaInputRoot]));return accepted;}
266
274
  - (BOOL)resignFirstResponder {const BOOL accepted=[super resignFirstResponder];if(accepted)gea::macos::nativeRootFocusChanged(self,false,-1);return accepted;}
267
275
 
268
276
  - (BOOL)geaDispatchKey:(gea::framework::events::PointerEvent &)event {
269
- const int root=geaKeyboardInputRoot();if(root<0)return NO;
270
- event.targetId=geaKeyboardTarget(root);
277
+ const int root=[self geaInputRoot];if(root<0)return NO;
278
+ // With no focused input inside it, the mounted root leaves the target to the
279
+ // engine, which aims at the app's own element so its onKeyDown runs; aiming
280
+ // at the mount container skipped every app-level key handler. A `<window>`
281
+ // aims at its own first element the same way, then the window itself.
282
+ int target=geaKeyboardTarget(root);
283
+ if(self.geaHostedRoot>=0 && target==root){const int first=gea::embedded::ui::Tree::instance().firstChildOf(root);if(first>=0)target=first;}
284
+ event.targetId=(self.geaHostedRoot<0 && geaCustomInputRoot()<0 && target==root)?-1:target;
271
285
  event.target=gea::framework::events::EventTarget(event.targetId);
272
286
  event.currentTargetId=root;
273
287
  event.currentTarget=gea::framework::events::EventTarget(root);
274
- gea::embedded::ui::dispatchRootKeyEvent(event, geaCustomInputRoot()>=0);
288
+ gea::embedded::ui::dispatchRootKeyEvent(event, [self geaCustomRoot]>=0);
275
289
  return event.defaultPrevented;
276
290
  }
277
291
  - (void)geaSendKey:(int)code {
@@ -280,15 +294,15 @@ static bool geaOwnsContourPress(int x, int y) {
280
294
  [self geaDispatchKey:event];
281
295
  }
282
296
  - (void)keyDown:(NSEvent *)native {
283
- if(geaKeyboardInputRoot()<0){[super keyDown:native];return;}
297
+ if([self geaInputRoot]<0){[super keyDown:native];return;}
284
298
  auto event=geaNativeKey(native,[self hasMarkedText],false);
285
299
  // Preserve the app-owned editor's historical select-all command only there.
286
- const bool selectAll=geaCustomInputRoot()>=0 && event.metaKey && event.key=="a";
300
+ const bool selectAll=[self geaCustomRoot]>=0 && event.metaKey && event.key=="a";
287
301
  if(selectAll)event.keyCode=1001;
288
302
  if([self geaDispatchKey:event] || selectAll)return;
289
303
  // Ordinary native text controls own AppKit text services themselves. Only
290
304
  // the explicit app-owned editor root interprets text into Gea attributes.
291
- if(geaCustomInputRoot()<0) {
305
+ if([self geaCustomRoot]<0) {
292
306
  // Unhandled navigation and commands retain AppKit's responder defaults.
293
307
  // Handled Gea events returned above and cannot also move native focus.
294
308
  if(native.keyCode==48) {
@@ -302,12 +316,12 @@ static bool geaOwnsContourPress(int x, int y) {
302
316
  @finally { self.geaInterpretingDispatchedKey=NO; }
303
317
  }
304
318
  - (void)keyUp:(NSEvent *)native {
305
- if(geaKeyboardInputRoot()<0){[super keyUp:native];return;}
319
+ if([self geaInputRoot]<0){[super keyUp:native];return;}
306
320
  auto event=geaNativeKey(native,[self hasMarkedText],true);
307
321
  [self geaDispatchKey:event];
308
322
  }
309
323
  - (void)insertText:(id)text replacementRange:(NSRange)range {
310
- (void)range;const int root=geaCustomInputRoot();if(root<0)return;
324
+ (void)range;const int root=[self geaCustomRoot];if(root<0)return;
311
325
  NSString *value=[text isKindOfClass:[NSAttributedString class]]?[text string]:text;
312
326
  auto &tree=gea::embedded::ui::Tree::instance();
313
327
  tree.setAttribute(root,"value",value.UTF8String?:"");
@@ -331,7 +345,7 @@ static bool geaOwnsContourPress(int x, int y) {
331
345
  }
332
346
  - (void)paste:(id)sender { (void)sender;NSString *value=[[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString];if(value)[self insertText:value replacementRange:NSMakeRange(NSNotFound,0)]; }
333
347
  - (void)copy:(id)sender {
334
- (void)sender;const int root=geaCustomInputRoot();if(root<0)return;
348
+ (void)sender;const int root=[self geaCustomRoot];if(root<0)return;
335
349
  NSString *text=[NSString stringWithUTF8String:gea::embedded::ui::Tree::instance().getAttribute(root,"data-gea-selected-text")];
336
350
  if(text.length){NSPasteboard *board=[NSPasteboard generalPasteboard];[board clearContents];[board setString:text forType:NSPasteboardTypeString];}
337
351
  }
@@ -355,6 +369,17 @@ static bool geaOwnsContourPress(int x, int y) {
355
369
  static void installStorageProviders()
356
370
  {
357
371
  gea::platform::storage::setMountProvider(+[]() { return true; });
372
+ // A Mac has no card: "/sdcard" is the app's own data directory, the same
373
+ // folder `Files.dataDirectory()` names (on a board both are "/sdcard"), so
374
+ // recordings, caches and app files written there land in Application
375
+ // Support/<app name>. Files the app ships stay readable through the read
376
+ // provider below.
377
+ gea::platform::storage::setPathProvider(+[](const std::string &path) -> std::string {
378
+ if (path != "/sdcard" && !path.starts_with("/sdcard/")) return path;
379
+ const std::string root = gea::host::Files.dataDirectory();
380
+ if (root.empty()) return path;
381
+ return root + path.substr(7);
382
+ });
358
383
  gea::platform::storage::setReadPathProvider(+[](const std::string &path) -> std::string {
359
384
  if (!path.starts_with("/sdcard/")) return path;
360
385
  NSString *relative = [NSString stringWithUTF8String:path.c_str() + 1];
@@ -517,6 +542,8 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
517
542
  if ([parsed isKindOfClass:[NSDictionary class]]) {
518
543
  NSDictionary *cfg = parsed;
519
544
  NSDictionary *win = cfg[@"window"] ?: cfg;
545
+ id dpr = cfg[@"cssDevicePixelRatio"];
546
+ if ([dpr respondsToSelector:@selector(doubleValue)] && [dpr doubleValue] > 0) gMacosCssDevicePixelRatio = [dpr doubleValue];
520
547
  id w = win[@"width"]; if ([w respondsToSelector:@selector(intValue)]) winW = [w intValue];
521
548
  id h = win[@"height"]; if ([h respondsToSelector:@selector(intValue)]) winH = [h intValue];
522
549
  id mw = win[@"minWidth"]; if ([mw respondsToSelector:@selector(intValue)]) minW = [mw intValue];
@@ -575,7 +602,8 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
575
602
  // steady clock (time since boot) while frames pass time since launch,
576
603
  // and its deadline never arrives.
577
604
  gea::host::runAnimationFrameCallbacks(gea_embedded_now_ms());
578
- gea::framework::app::Application::init(static_cast<int>(size.width), static_cast<int>(size.height));
605
+ gea::framework::app::Application::init(static_cast<int>(size.width), static_cast<int>(size.height),
606
+ gMacosCssDevicePixelRatio);
579
607
  gea_macos_smoke_log("[gea-macos] after Application::init");
580
608
 
581
609
  // If the app's mounted root is a <glass-split>, swap the flat content view
@@ -776,14 +804,21 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
776
804
 
777
805
  // Native split-shell apps: each pane lays out + syncs against its own
778
806
  // resizable AppKit container. Skip the flat single-view path entirely.
807
+ // `<window>` elements (macos_windows.mm): while any is mounted, every root
808
+ // -- this window's and each `<window>`'s -- lays out and renders together.
809
+ NSSize size = self.rootView.bounds.size;
810
+ const int w = static_cast<int>(size.width);
811
+ const int h = static_cast<int>(size.height);
812
+ [GeaWindows reconcile];
813
+ if ([GeaWindows hasWindows]) {
814
+ [GeaWindows layoutAndSyncMainView:self.rootView mainShell:self.splitShell mainRoot:root];
815
+ if (self.splitShell) return;
816
+ } else {
779
817
  if (self.splitShell) {
780
818
  [self.splitShell layoutAndSync];
781
819
  return;
782
820
  }
783
821
 
784
- NSSize size = self.rootView.bounds.size;
785
- const int w = static_cast<int>(size.width);
786
- const int h = static_cast<int>(size.height);
787
822
  // macOS target convention: the mounted root view fills the window. This
788
823
  // gives apps a viewport that tracks resize without per-app code; if an
789
824
  // app wants different sizing it puts a sized child inside the root.
@@ -791,6 +826,7 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
791
826
  gea::embedded::ui::NodeHandle(root).style().height(h);
792
827
  tree.computeLayout(root, w, h);
793
828
  gea::macos::MacosRenderer::instance().sync(self.rootView, root);
829
+ }
794
830
 
795
831
 
796
832
  // Opt-in deterministic Gea event replay for recorded demos. No OS events or
@@ -827,7 +863,12 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
827
863
  if (pending && ++settleFrames >= 3) {
828
864
  NSString *expected = pending[@"expect"];
829
865
  std::string text;
830
- for (int i=0;i<tree.nodeCount();++i) { text += tree.node(i).text; text += " "; }
866
+ // With `window`, `expect` reads only that `<window>`'s subtree.
867
+ const int expectScope = pending[@"window"] ? [GeaWindows nodeForWindow:[GeaWindows windowNamed:[pending[@"window"] description]]] : -1;
868
+ for (int i=0;i<tree.nodeCount();++i) {
869
+ if (expectScope >= 0) { int a=i; while (a>=0 && a!=expectScope) a=tree.node(a).parent; if (a<0) continue; }
870
+ text += tree.node(i).text; text += " ";
871
+ }
831
872
  if (expected.length && text.find(expected.UTF8String) == std::string::npos) replayFail([NSString stringWithFormat:@"Step %@ did not show %@", pending[@"label"], expected]);
832
873
  if (NSDictionary *check=pending[@"expectTextIn"]) {
833
874
  auto subtreeText = [&](auto &&visit, int node) -> std::string {
@@ -845,26 +886,164 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
845
886
  }
846
887
  if(!matched) replayFail([NSString stringWithFormat:@"Step %@ did not show %@ in %@",pending[@"label"],check[@"contains"],check[@"class"]]);
847
888
  }
848
- replayLog(@{@"verified":pending[@"label"], @"elapsed":@(elapsed)});
889
+ replayLog(@{@"verified":pending[@"label"] ?: @"", @"elapsed":@(elapsed)});
849
890
  pending = nil;
850
891
  }
851
892
  if (!pending && nextStep < steps.count && elapsed >= [steps[nextStep][@"at"] doubleValue]) {
852
893
  NSDictionary *step = steps[nextStep++];
853
894
  using gea::framework::events::PointerEvent;
854
895
  using gea::framework::events::PointerEventType;
855
- if (NSString *text = step[@"text"]) {
896
+ // `window` (a `<window>`'s title, or its index in opening order) aims a
897
+ // click, key, wheel or text step at that window instead of the main one.
898
+ NSWindow *stepWindow = self.window;
899
+ NSView *stepRoot = self.rootView;
900
+ int stepWindowNode = -1;
901
+ if (id windowName = step[@"window"]) {
902
+ stepWindow = [GeaWindows windowNamed:[windowName description]];
903
+ if (!stepWindow) replayFail([NSString stringWithFormat:@"No window %@ for %@", windowName, step[@"label"]]);
904
+ stepRoot = stepWindow.contentView;
905
+ stepWindowNode = [GeaWindows nodeForWindow:stepWindow];
906
+ }
907
+ if ([step[@"kind"] isEqual:@"windows"]) {
908
+ // Logs every open `<window>`: title, windowNumber, size, visible, key.
909
+ // `policy` is the activation policy: "regular" (Dock icon) or "accessory".
910
+ replayLog(@{@"windows":[GeaWindows describe], @"label":step[@"label"] ?: @"",
911
+ @"policy":NSApp.activationPolicy==NSApplicationActivationPolicyRegular ? @"regular" : @"accessory"});
912
+ } else if ([step[@"kind"] isEqual:@"dragWindow"]) {
913
+ // A drag from (x,y) by (dx,dy) points: the point must be on a
914
+ // `data-window-drag` area (as a real drag's would); the window then moves
915
+ // as performWindowDragWithEvent moves it.
916
+ if (!step[@"window"]) replayFail(@"dragWindow needs a window");
917
+ const int x=[step[@"x"] intValue], y=[step[@"y"] intValue];
918
+ const NSPoint inWindow=[stepRoot convertPoint:NSMakePoint(x,stepRoot.bounds.size.height-y) toView:nil];
919
+ const int node=gea::macos::nodeAtWindowPoint(stepWindow,inWindow,nullptr,nullptr);
920
+ const int drag=node>=0 ? [GeaWindows windowDragElementForNode:node window:stepWindow] : -1;
921
+ if (drag<0) replayFail([NSString stringWithFormat:@"No drag area under %@",step[@"label"]]);
922
+ const NSPoint origin=stepWindow.frame.origin;
923
+ [stepWindow setFrameOrigin:NSMakePoint(origin.x+[step[@"dx"] doubleValue],origin.y-[step[@"dy"] doubleValue])];
924
+ replayLog(@{@"drag":step[@"label"] ?: @"", @"element":@(drag)});
925
+ } else if ([step[@"kind"] isEqual:@"resizeWindow"]) {
926
+ // A new content size, as a resize drag ending there.
927
+ if (!step[@"window"]) replayFail(@"resizeWindow needs a window");
928
+ [stepWindow setContentSize:NSMakeSize([step[@"width"] doubleValue],[step[@"height"] doubleValue])];
929
+ } else if ([step[@"kind"] isEqual:@"closeWindow"]) {
930
+ // The window's close button, as clicked.
931
+ if (!step[@"window"]) replayFail(@"closeWindow needs a window");
932
+ [stepWindow performClose:nil];
933
+ } else if (NSNumber *keyCode = step[@"keyCode"]) {
934
+ // A real key press through the window, as AppKit delivers one: it reaches
935
+ // whichever view holds the keyboard, then the app's key listeners.
936
+ NSString *characters = step[@"characters"] ?: @"";
937
+ for (NSEventType type : {NSEventTypeKeyDown, NSEventTypeKeyUp}) {
938
+ NSEvent *native=[NSEvent keyEventWithType:type location:NSZeroPoint modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:stepWindow.windowNumber context:nil characters:characters charactersIgnoringModifiers:characters isARepeat:NO keyCode:keyCode.unsignedShortValue];
939
+ [stepWindow sendEvent:native];
940
+ }
941
+ } else if ([step[@"kind"] isEqual:@"statusMenu"]) {
942
+ // The menu bar icon's right-click menu, as clicked: shows it: logs its
943
+ // items, then (with `choose`) picks the one with that title through its
944
+ // own target/action, exactly as a click in the open menu does.
945
+ NSMenu *menu=(__bridge NSMenu *)gea::host::menu_bar_platform::nativeSecondaryMenu();
946
+ if (!menu) replayFail(@"No menu bar menu");
947
+ NSMutableArray *items=[NSMutableArray array];
948
+ for (NSMenuItem *item in menu.itemArray)
949
+ [items addObject:item.isSeparatorItem ? @"---" : [NSString stringWithFormat:@"%@%@%@", item.title, item.enabled ? @"" : @" (disabled)", item.keyEquivalent.length ? [@" key:" stringByAppendingString:item.keyEquivalent] : @""]];
950
+ replayLog(@{@"statusMenu":step[@"label"] ?: @"", @"items":items});
951
+ if (NSString *choose=step[@"choose"]) {
952
+ const NSInteger index=[menu indexOfItemWithTitle:choose];
953
+ if (index<0) replayFail([NSString stringWithFormat:@"Menu has no %@",choose]);
954
+ [menu performActionForItemAtIndex:index];
955
+ }
956
+ } else if ([step[@"kind"] isEqual:@"wheel"]) {
957
+ // A trackpad/mouse-wheel scroll at (x,y): a real scroll-wheel NSEvent
958
+ // through the same bridge the app-wide scroll monitor uses, then -- unless
959
+ // a `wheel` listener called preventDefault() -- on to the view under the
960
+ // point, whose responder chain reaches the enclosing NSScrollView.
961
+ // deltaX/deltaY use the DOM convention (positive deltaY scrolls down);
962
+ // phase/momentumPhase: "mayBegin"|"began"|"changed"|"ended"|"cancelled".
963
+ const int x=[step[@"x"] intValue], y=[step[@"y"] intValue];
964
+ const double dx=[step[@"deltaX"] doubleValue], dy=[step[@"deltaY"] doubleValue];
965
+ auto scrollPhase=[](NSString *name) -> int64_t {
966
+ if ([name isEqual:@"mayBegin"]) return kCGScrollPhaseMayBegin;
967
+ if ([name isEqual:@"began"]) return kCGScrollPhaseBegan;
968
+ if ([name isEqual:@"changed"]) return kCGScrollPhaseChanged;
969
+ if ([name isEqual:@"ended"]) return kCGScrollPhaseEnded;
970
+ if ([name isEqual:@"cancelled"]) return kCGScrollPhaseCancelled;
971
+ return 0;
972
+ };
973
+ auto momentumPhase=[](NSString *name) -> int64_t {
974
+ if ([name isEqual:@"began"]) return kCGMomentumScrollPhaseBegin;
975
+ if ([name isEqual:@"changed"]) return kCGMomentumScrollPhaseContinue;
976
+ if ([name isEqual:@"ended"] || [name isEqual:@"cancelled"]) return kCGMomentumScrollPhaseEnd;
977
+ return kCGMomentumScrollPhaseNone;
978
+ };
979
+ const NSPoint inRoot=NSMakePoint(x,stepRoot.bounds.size.height-y);
980
+ const NSPoint inWindow=[stepRoot convertPoint:inRoot toView:nil];
981
+ CGEventRef cg=CGEventCreateScrollWheelEvent2(nullptr,kCGScrollEventUnitPixel,2,static_cast<int32_t>(std::lround(-dy)),static_cast<int32_t>(std::lround(-dx)),0);
982
+ CGEventSetIntegerValueField(cg,kCGScrollWheelEventIsContinuous,1);
983
+ CGEventSetDoubleValueField(cg,kCGScrollWheelEventPointDeltaAxis1,-dy);
984
+ CGEventSetDoubleValueField(cg,kCGScrollWheelEventPointDeltaAxis2,-dx);
985
+ CGEventSetDoubleValueField(cg,kCGScrollWheelEventFixedPtDeltaAxis1,-dy);
986
+ CGEventSetDoubleValueField(cg,kCGScrollWheelEventFixedPtDeltaAxis2,-dx);
987
+ CGEventSetIntegerValueField(cg,kCGScrollWheelEventScrollPhase,scrollPhase(step[@"phase"]));
988
+ CGEventSetIntegerValueField(cg,kCGScrollWheelEventMomentumPhase,momentumPhase(step[@"momentumPhase"]));
989
+ const NSPoint onScreen=[stepWindow convertPointToScreen:inWindow];
990
+ const CGFloat primaryHeight=NSScreen.screens.firstObject.frame.size.height;
991
+ CGEventSetLocation(cg,CGPointMake(onScreen.x,primaryHeight-onScreen.y));
992
+ NSEvent *native=[NSEvent eventWithCGEvent:cg];
993
+ CFRelease(cg);
994
+ const bool consumed=gea::macos::dispatchWheelEvent(native,stepWindow,inWindow);
995
+ if (!consumed) {
996
+ NSView *hit=[stepRoot hitTest:[stepRoot convertPoint:inRoot toView:stepRoot.superview]];
997
+ [hit scrollWheel:native];
998
+ }
999
+ replayLog(@{@"wheel":step[@"label"] ?: @"", @"consumed":@(consumed)});
1000
+ } else if (step[@"text"] && stepWindowNode >= 0) {
1001
+ // A `<window>`'s first text field takes the text, through its onInput.
1002
+ int field=-1;
1003
+ for (int i=0;i<tree.nodeCount() && field<0;++i) {
1004
+ const char *tag=tree.tagName(i);
1005
+ if (!tag || (std::strcmp(tag,"input")!=0 && std::strcmp(tag,"textarea")!=0)) continue;
1006
+ for (int a=i;a>=0;a=tree.node(a).parent) if (a==stepWindowNode) { field=i; break; }
1007
+ }
1008
+ if (field<0 || gea_macos_fire_input_for_node(field,[step[@"text"] UTF8String])<0) replayFail([NSString stringWithFormat:@"No text field in window %@",step[@"window"]]);
1009
+ } else if (NSString *text = step[@"text"]) {
856
1010
  const int inputRoot = geaCustomInputRoot();
857
1011
  if (inputRoot < 0) replayFail(@"No Gea input root");
858
1012
  tree.setAttribute(inputRoot,"value",text.UTF8String);
859
1013
  PointerEvent event; event.type=PointerEventType::Input; event.targetId=inputRoot; tree.dispatchEvent(event);
1014
+ } else if (stepWindowNode >= 0) {
1015
+ // A click in a `<window>`, at (x,y) from its content area's top left:
1016
+ // the view under the point names the target, as a real click's does.
1017
+ const int x=[step[@"x"] intValue], y=[step[@"y"] intValue];
1018
+ const NSPoint inWindow=[stepRoot convertPoint:NSMakePoint(x,stepRoot.bounds.size.height-y) toView:nil];
1019
+ int treeX=0, treeY=0;
1020
+ const int target=gea::macos::nodeAtWindowPoint(stepWindow,inWindow,&treeX,&treeY);
1021
+ int ancestor=target;
1022
+ NSString *targetClass=step[@"target"];
1023
+ const std::string expected=targetClass ? targetClass.UTF8String : "";
1024
+ while (ancestor>=0 && tree.className(ancestor).find(expected)==std::string::npos) ancestor=tree.node(ancestor).parent;
1025
+ if (target<0 || ancestor<0) replayFail([NSString stringWithFormat:@"Wrong hit target for %@",step[@"label"]]);
1026
+ if (stepWindow.firstResponder!=stepRoot && stepRoot.acceptsFirstResponder) [stepWindow makeFirstResponder:stepRoot];
1027
+ for (auto phase : {PointerEventType::TouchStart,PointerEventType::TouchEnd,PointerEventType::Click}) {
1028
+ PointerEvent event; event.type=phase; event.targetId=target; event.pointerId=1;
1029
+ event.x=treeX; event.y=treeY; event.clientX=treeX; event.clientY=treeY; event.pageX=treeX; event.pageY=treeY;
1030
+ tree.dispatchEvent(event);
1031
+ }
1032
+ // A `data-window-action` control then closes, minimizes or zooms the window.
1033
+ if ([GeaWindows performWindowActionForNode:target window:stepWindow]) replayLog(@{@"windowAction":step[@"label"] ?: @""});
860
1034
  } else {
861
1035
  const int x=[step[@"x"] intValue], y=[step[@"y"] intValue];
862
1036
  NSPoint point=NSMakePoint(x,self.rootView.bounds.size.height-y);
863
1037
  NSView *hit=[self.rootView hitTest:[self.rootView convertPoint:point toView:self.rootView.superview]];
864
1038
  int target=gea::macos::nodeIdForView(hit), ancestor=target;
865
- const std::string expected=[step[@"target"] UTF8String];
1039
+ // `target` (a class the hit node or an ancestor carries) is optional; without it any hit passes.
1040
+ NSString *targetClass=step[@"target"];
1041
+ const std::string expected=targetClass ? targetClass.UTF8String : "";
866
1042
  while (ancestor>=0 && tree.className(ancestor).find(expected)==std::string::npos) ancestor=tree.node(ancestor).parent;
867
1043
  if (target<0 || ancestor<0) replayFail([NSString stringWithFormat:@"Wrong hit target for %@",step[@"label"]]);
1044
+ // A click leaves the keyboard with the root, as the click recognizer does.
1045
+ if (geaCustomInputRoot()<0 && self.window.firstResponder!=self.rootView && self.rootView.acceptsFirstResponder)
1046
+ [self.window makeFirstResponder:self.rootView];
868
1047
  tree.pointerHover(x,y);
869
1048
  if (!geaOwnsContourPress(x,y)) tree.pointerDown(x,y);
870
1049
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW,80*NSEC_PER_MSEC),dispatch_get_main_queue(),^{
@@ -876,7 +1055,7 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
876
1055
  tree.dispatchEvent(event);
877
1056
  }
878
1057
  }
879
- replayLog(@{@"action":step[@"label"], @"elapsed":@(elapsed), @"index":@(nextStep-1)});
1058
+ replayLog(@{@"action":step[@"label"] ?: @"", @"elapsed":@(elapsed), @"index":@(nextStep-1)});
880
1059
  pending=step; settleFrames=0;
881
1060
  }
882
1061
  }
@@ -951,10 +1130,29 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
951
1130
  }
952
1131
  }
953
1132
 
1133
+ // While the main window is hidden (a menu bar app's closed panel), an open
1134
+ // `<window>` element's display link drives frames (macos_windows.mm).
1135
+ - (BOOL)geaAuxiliaryWindowDrivesFrames
1136
+ {
1137
+ if (@available(macOS 14.0, *)) return [GeaWindows anyVisible];
1138
+ return NO;
1139
+ }
1140
+
1141
+ // A Dock icon click brings the `<window>` elements back.
1142
+ - (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)visible
1143
+ {
1144
+ (void)sender;
1145
+ (void)visible;
1146
+ if ([GeaWindows hasWindows]) [GeaWindows showAll];
1147
+ return YES;
1148
+ }
1149
+
954
1150
  - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
955
1151
  {
956
1152
  (void)sender;
957
1153
  if (gea::macos::thermalright::enabled()) return NO;
1154
+ // A menu bar app hides its only window whenever the panel closes; that is not a quit.
1155
+ if (gea::host::MenuBar.active()) return NO;
958
1156
  return YES;
959
1157
  }
960
1158
 
@@ -989,8 +1187,9 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
989
1187
  (width != gea::embedded::ui::Document::preferredMountWidth() ||
990
1188
  height != gea::embedded::ui::Document::preferredMountHeight())) {
991
1189
  gea::embedded::ui::Document::setPreferredMountSize(width, height);
992
- // AppKit layout uses points; a CSS px is one point, including on Retina.
993
- gea::embedded::ui::setViewportMetrics(width, height, 1.0);
1190
+ // AppKit layout uses points; a CSS px is `cssDevicePixelRatio` points
1191
+ // (one by default), whatever the screen's backing scale.
1192
+ gea::embedded::ui::setViewportMetrics(width, height, gMacosCssDevicePixelRatio);
994
1193
  }
995
1194
  }
996
1195
  gea::embedded::ui::dispatchWindowLifecycleEvent(gea::framework::events::PointerEventType::WindowResize);
@@ -0,0 +1,134 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Microphone capture for `navigator.mediaDevices.getUserMedia({ audio: true })`
3
+ // on macOS: an AVAudioEngine input tap converted to the device sample rate,
4
+ // mono 16-bit, and handed to every live capture track (host/media.cpp), which
5
+ // feeds MediaRecorder, Web Audio sources and streams alike. The iOS twin is
6
+ // targets/ios/main/ios_microphone.mm; macOS has no AVAudioSession, and asks for
7
+ // the microphone through AVCaptureDevice instead.
8
+ //
9
+ // The app's Info.plist must carry NSMicrophoneUsageDescription (macos.json
10
+ // `infoPlist`): asking without it makes macOS terminate the process, so the
11
+ // backend logs and captures nothing instead.
12
+ #import <AVFoundation/AVFoundation.h>
13
+ #include <cstdio>
14
+ #include <mutex>
15
+ #include <unordered_set>
16
+ #include "audio.h"
17
+ #include "host/media.h"
18
+
19
+ __asm__(".linker_option \"-framework\", \"AVFoundation\"");
20
+
21
+ namespace gea::host::media {
22
+ namespace {
23
+ AVAudioEngine *capture;
24
+ std::unordered_set<NativeMediaTrackHandle> tracks;
25
+ std::mutex tracksMutex;
26
+ bool requestingPermission = false;
27
+
28
+ bool hasTracks() {
29
+ std::lock_guard lock(tracksMutex);
30
+ return !tracks.empty();
31
+ }
32
+
33
+ void stopCapture() {
34
+ if (!capture) return;
35
+ [capture.inputNode removeTapOnBus:0];
36
+ [capture stop];
37
+ capture = nil;
38
+ }
39
+
40
+ void startCapture() {
41
+ if (capture || !hasTracks()) return;
42
+
43
+ AVAudioEngine *engine = [[AVAudioEngine alloc] init];
44
+ AVAudioInputNode *input = engine.inputNode;
45
+ AVAudioFormat *source = [input outputFormatForBus:0];
46
+ constexpr double sampleRate = gea::platform::audio::deviceSampleRate;
47
+ AVAudioFormat *format = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatInt16
48
+ sampleRate:sampleRate
49
+ channels:1
50
+ interleaved:YES];
51
+ AVAudioConverter *converter = source.sampleRate > 0 && source.channelCount
52
+ ? [[AVAudioConverter alloc] initFromFormat:source toFormat:format]
53
+ : nil;
54
+ if (!converter) {
55
+ std::fprintf(stderr, "[gea macos] microphone: no input device\n");
56
+ return;
57
+ }
58
+ [input installTapOnBus:0
59
+ bufferSize:2048
60
+ format:source
61
+ block:^(AVAudioPCMBuffer *buffer, AVAudioTime *) {
62
+ auto capacity = (AVAudioFrameCount)(buffer.frameLength * sampleRate / source.sampleRate) + 32;
63
+ AVAudioPCMBuffer *pcm = [[AVAudioPCMBuffer alloc] initWithPCMFormat:format frameCapacity:capacity];
64
+ __block BOOL sent = NO;
65
+ [converter convertToBuffer:pcm
66
+ error:NULL
67
+ withInputFromBlock:^AVAudioBuffer *(AVAudioPacketCount, AVAudioConverterInputStatus *status) {
68
+ *status = sent ? AVAudioConverterInputStatus_NoDataNow : AVAudioConverterInputStatus_HaveData;
69
+ if (sent) return nil;
70
+ sent = YES;
71
+ return buffer;
72
+ }];
73
+ if (!pcm.frameLength) return;
74
+ std::lock_guard lock(tracksMutex);
75
+ for (const auto track : tracks) track_inject_pcm(track, pcm.int16ChannelData[0], pcm.frameLength);
76
+ }];
77
+ NSError *error = nil;
78
+ if (![engine startAndReturnError:&error]) {
79
+ [input removeTapOnBus:0];
80
+ std::fprintf(stderr, "[gea macos] microphone: %s\n", error.localizedDescription.UTF8String ?: "did not start");
81
+ return;
82
+ }
83
+ capture = engine;
84
+ }
85
+
86
+ void requestCapture() {
87
+ if (![NSBundle.mainBundle objectForInfoDictionaryKey:@"NSMicrophoneUsageDescription"]) {
88
+ std::fprintf(stderr, "[gea macos] microphone: add NSMicrophoneUsageDescription to the app's Info.plist\n");
89
+ return;
90
+ }
91
+ const AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
92
+ if (status == AVAuthorizationStatusAuthorized) {
93
+ startCapture();
94
+ } else if (status == AVAuthorizationStatusNotDetermined && !requestingPermission) {
95
+ requestingPermission = true;
96
+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio
97
+ completionHandler:^(BOOL granted) {
98
+ dispatch_async(dispatch_get_main_queue(), ^{
99
+ requestingPermission = false;
100
+ if (granted) startCapture();
101
+ });
102
+ }];
103
+ } else if (status != AVAuthorizationStatusNotDetermined) {
104
+ std::fprintf(stderr, "[gea macos] microphone: access denied in System Settings\n");
105
+ }
106
+ }
107
+
108
+ void attach(NativeMediaTrackHandle track) {
109
+ {
110
+ std::lock_guard lock(tracksMutex);
111
+ tracks.insert(track);
112
+ }
113
+ requestCapture();
114
+ }
115
+
116
+ void detach(NativeMediaTrackHandle track) {
117
+ {
118
+ std::lock_guard lock(tracksMutex);
119
+ tracks.erase(track);
120
+ }
121
+ if (!hasTracks()) stopCapture();
122
+ }
123
+ } // namespace
124
+
125
+ void platform_attach_track(NativeMediaTrackHandle track) {
126
+ if (NSThread.isMainThread) attach(track);
127
+ else dispatch_async(dispatch_get_main_queue(), ^{ attach(track); });
128
+ }
129
+
130
+ void platform_detach_track(NativeMediaTrackHandle track) {
131
+ if (NSThread.isMainThread) detach(track);
132
+ else dispatch_async(dispatch_get_main_queue(), ^{ detach(track); });
133
+ }
134
+ } // namespace gea::host::media
@@ -27,5 +27,17 @@
27
27
  // flex layout for that pane, and sync the gea subtrees into the pane views.
28
28
  - (void)layoutAndSync;
29
29
 
30
+ // The same work split for a frame that syncs several roots at once (a
31
+ // `<window>` beside the main window, see macos_windows.mm). Each pane's root
32
+ // is re-read from its `<glass-pane>` every frame, so a pane whose child is
33
+ // swapped (a conditional list) keeps rendering.
34
+ // Re-frames each pane's content view; YES when one moved or resized.
35
+ - (BOOL)updatePaneFrames;
36
+ // Lays every pane out at its content view's size.
37
+ - (void)layoutPanes;
38
+ // Appends one gea::macos::SyncRoot per pane (an opaque vector pointer, so this
39
+ // header stays plain Objective-C).
40
+ - (void)appendSyncRoots:(void *)roots;
41
+
30
42
  @end
31
43
  #endif