From d60141bb71eae53ddd0711d83bfad829b59829e1 Mon Sep 17 00:00:00 2001
From: ManoloFLTK <41016272+ManoloFLTK@users.noreply.github.com>
Date: Thu, 6 Feb 2025 12:25:39 +0100
Subject: [PATCH] fix "macOS Sonoma/Sequoia not capturing OpenGL 1 text on
 macOS"  (#1197)

---
 .../Cocoa/Fl_Cocoa_Gl_Window_Driver.mm        | 37 +++++++++++++++++++
 1 file changed, 37 insertions(+)

diff --git a/src/drivers/Cocoa/Fl_Cocoa_Gl_Window_Driver.mm b/src/drivers/Cocoa/Fl_Cocoa_Gl_Window_Driver.mm
index d52cae3ca..baa819621 100644
--- a/src/drivers/Cocoa/Fl_Cocoa_Gl_Window_Driver.mm
+++ b/src/drivers/Cocoa/Fl_Cocoa_Gl_Window_Driver.mm
@@ -452,6 +452,31 @@ static uchar *convert_BGRA_to_RGB(uchar *baseAddress, int w, int h, int mByteWid
   return newimg;
 }
 
+
+static Fl_RGB_Image *cgimage_to_rgb3(CGImageRef img) {
+  int w = (int)CGImageGetWidth(img);
+  int h = (int)CGImageGetHeight(img);
+  CGColorSpaceRef cspace = CGColorSpaceCreateDeviceRGB();
+  uchar *rgba = new uchar[4 * w * h];
+  CGContextRef auxgc = CGBitmapContextCreate(rgba, w, h, 8, 4 * w, cspace,
+                                             kCGImageAlphaPremultipliedLast);
+  CGColorSpaceRelease(cspace);
+  CGContextDrawImage(auxgc, CGRectMake(0, 0, w, h), img);
+  CGContextRelease(auxgc);
+  uchar *rgb3 = new uchar[3 * w * h]; // transform RGBA pixel array into RGB array
+  uchar *p = rgba, *q = rgb3, *last = rgba + 4 * w * h;
+  while ( p < last) {
+    memcpy(q, p, 3);
+    p += 4;
+    q += 3;
+  }
+  delete[] rgba;
+  Fl_RGB_Image *rgb = new Fl_RGB_Image(rgb3, w, h, 3);
+  rgb->alloc_array = 1;
+  return rgb;
+}
+
+
 Fl_RGB_Image* Fl_Cocoa_Gl_Window_Driver::capture_gl_rectangle(int x, int y, int w, int h)
 {
   Fl_Gl_Window* glw = pWindow;
@@ -459,6 +484,18 @@ Fl_RGB_Image* Fl_Cocoa_Gl_Window_Driver::capture_gl_rectangle(int x, int y, int
   if (factor != 1) {
     w *= factor; h *= factor; x *= factor; y *= factor;
   }
+#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
+  if (fl_mac_os_version >= 100600) {
+    NSWindow *nswin = (NSWindow*)fl_mac_xid(pWindow);
+    CGImageRef img_full = Fl_Cocoa_Window_Driver::capture_decorated_window_10_6(nswin);
+    CGRect cgr = CGRectMake(x, y, w, h);
+    CGImageRef cgimg = CGImageCreateWithImageInRect(img_full, cgr); // 10.4
+    CGImageRelease(img_full);
+    Fl_RGB_Image *rgb = cgimage_to_rgb3(cgimg);
+    CGImageRelease(cgimg);
+    return rgb;
+  }
+#endif
   [(NSOpenGLContext*)glw->context() makeCurrentContext];
 // to capture also the overlay and for directGL demo
   [(NSOpenGLContext*)glw->context() flushBuffer];
-- 
GitLab