Tk Source Code

Artifact [b505bcc113]
Login

Artifact b505bcc11317dc8ced194e815fe95002f877145d71102210ddce685241dd02ec:

Attachment "macmenubarcolor.m" to ticket [2a2dc34e08] added by bll 2020-09-26 19:50:33.
#import "ApplicationServices/ApplicationServices.h"
#import "Foundation/NSObject.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <MacTypes.h>
#import <Cocoa/Cocoa.h>

char *
macmenubarcolor_cmd () {
  char *rgbstring;
  CGImageRef screenShot = CGWindowListCreateImage (CGRectInfinite, 
      kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);

  NSBitmapImageRep *image = [[NSBitmapImageRep alloc] 
      initWithCGImage:screenShot];

#if 0
  // creates a png file with the screenshot 
  NSData *bitmapData = [image
      representationUsingType:NSBitmapImageFileTypePNG
      properties:@{}];
  [bitmapData writeToFile: @"ss.png" atomically: false];
#endif

  NSSize imgsize = [image size];
  NSRect imageRect = NSMakeRect (0, 0, imgsize.width, imgsize.height);

  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB ();
  CGContextRef ctx = CGBitmapContextCreate (NULL, 
      imgsize.width, imgsize.height, 8, 0, colorSpace, 
      kCGImageAlphaPremultipliedLast);
  NSGraphicsContext *gctx = 
      [NSGraphicsContext graphicsContextWithCGContext:ctx flipped:NO];
    
  [NSGraphicsContext setCurrentContext:gctx];
  [image drawInRect:imageRect];

  uint32_t* pixel = (uint32_t*) CGBitmapContextGetData (ctx);
  pixel += (uint32_t) (4 * imgsize.width);
  pixel += 4;
  uint32_t rgba = *pixel;
  uint8_t red   = (rgba & 0x000000ff) >> 0;
  uint8_t green = (rgba & 0x0000ff00) >> 8;
  uint8_t blue  = (rgba & 0x00ff0000) >> 16;
  // uint8_t alpha = (rgba & 0xff000000) >> 24;
  /* the string should be 14 bytes max (assuming a 32 bit color) */
  rgbstring = malloc (30); 
  sprintf (rgbstring, "#%02x%02x%02x", red, green, blue);

#if 0
  for (size_t y = 0; y < imgsize.height; y++) {
    for (size_t x = 0; x < imgsize.width; x++) {
      // Extract colour components
      uint32_t rgba = *pixel;
      uint8_t red   = (rgba & 0x000000ff) >> 0;
      uint8_t green = (rgba & 0x0000ff00) >> 8;
      uint8_t blue  = (rgba & 0x00ff0000) >> 16;
      // uint8_t alpha = (rgba & 0xff000000) >> 24;
      printf ("#%02x%02x%02x\n", red, green, blue);
      pixel++;
    }
  }
#endif

  [NSGraphicsContext setCurrentContext:nil];
  CGContextRelease (ctx);
  CGColorSpaceRelease (colorSpace);
  CFRelease(screenShot);
  return rgbstring;
}