#import "ScreenPreview.h" #import "Permissions.h" #import #include "../common/commands.h" // ScreenPreviewStatus / SCREEN_PREVIEW_FMT_BGRX #include namespace { // 目标尺寸:与 Linux/Windows 端同一套规则——等比缩到 maxWidth 以内(不放大), // 高度再压到 1080(竖屏/超宽屏的原始像素包会大到没意义),宽高取偶数。 bool ComputeTargetSize(int sw, int sh, int maxWidth, int& tw, int& th) { if (sw <= 0 || sh <= 0) return false; tw = sw; th = sh; if (tw > maxWidth) { th = (int)((long long)sh * maxWidth / sw); tw = maxWidth; } if (th > 1080) { tw = (int)((long long)tw * 1080 / th); th = 1080; } tw &= ~1; th &= ~1; if (tw < 2) tw = 2; if (th < 2) th = 2; if (tw > sw) tw = sw; if (th > sh) th = sh; return tw > 0 && th > 0; } } // namespace bool ScreenPreview::IsAvailable() { // 没有录屏授权时 CGDisplayCreateImage 仍然会返回一张图(macOS 15 起是壁纸 + // 窗口占位),看起来"成功"却什么都看不到,所以不能只靠试抓一次。 if (CGMainDisplayID() == 0) return false; // 预检只读 TCC 状态位,ad-hoc 重签之后可能假阴性;启动时的授权判定因此用的是 // 真抓一帧(Permissions::checkScreenCapture)。这里两者取或:宁可多发几次注定 // 失败的预览请求,也不要出现「远程能看屏、get_screenshot 却一直 -32005」。 return Permissions::checkScreenCapturePreflight() || Permissions::checkScreenCapture(); } int ScreenPreview::Capture(int maxWidth, std::vector& out, int& outW, int& outH) { outW = 0; outH = 0; out.clear(); // 与 Linux 端一致:上限防滥用,下限防止 1 像素宽的退化请求 if (maxWidth < 64) maxWidth = 64; if (maxWidth > 1920) maxWidth = 1920; const CGDirectDisplayID display = CGMainDisplayID(); if (display == 0) return SCREEN_PREVIEW_NOT_SUPPORTED; const int sw = (int)CGDisplayPixelsWide(display); const int sh = (int)CGDisplayPixelsHigh(display); int tw = 0, th = 0; if (!ComputeTargetSize(sw, sh, maxWidth, tw, th)) return SCREEN_PREVIEW_CAPTURE_FAILED; // CGDisplayCreateImage 从 macOS 14 起标记废弃(官方推荐 ScreenCaptureKit 的异步 // SCScreenshotManager),但没有删除;一次几十毫秒的抓图用异步 API 要额外起 run loop, // 不划算。这里显式压掉废弃告警,并在构建机升级到真正移除该 API 时再换实现。 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CGImageRef image = CGDisplayCreateImage(display); #pragma clang diagnostic pop if (image == nullptr) return SCREEN_PREVIEW_CAPTURE_FAILED; // kCGImageAlphaNoneSkipFirst + 32Little 在内存里就是 B,G,R,X 的字节序,与协议里 // SCREEN_PREVIEW_FMT_BGRX 的定义一致;缩放交给 CoreGraphics 在绘制时完成。 const size_t stride = (size_t)tw * 4; out.resize(stride * (size_t)th); CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); CGContextRef ctx = CGBitmapContextCreate(out.data(), (size_t)tw, (size_t)th, 8, stride, cs, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little); CGColorSpaceRelease(cs); if (ctx == nullptr) { CGImageRelease(image); out.clear(); return SCREEN_PREVIEW_CAPTURE_FAILED; } CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium); CGContextSetShouldAntialias(ctx, false); CGContextDrawImage(ctx, CGRectMake(0, 0, tw, th), image); CGContextRelease(ctx); CGImageRelease(image); // Alpha 字节协议要求 0xFF;kCGImageAlphaNoneSkipFirst 不会写它 for (size_t i = 3; i < out.size(); i += 4) out[i] = 0xFF; outW = tw; outH = th; return SCREEN_PREVIEW_OK; }