atom_api_native_image_mac.mm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (c) 2015 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "atom/common/api/atom_api_native_image.h"
  5. #import <Cocoa/Cocoa.h>
  6. #include "base/strings/sys_string_conversions.h"
  7. #include "ui/gfx/color_utils.h"
  8. #include "ui/gfx/image/image.h"
  9. #include "ui/gfx/image/image_skia.h"
  10. #include "ui/gfx/image/image_skia_operations.h"
  11. namespace atom {
  12. namespace api {
  13. NSData* bufferFromNSImage(NSImage* image) {
  14. CGImageRef ref = [image CGImageForProposedRect:nil context:nil hints:nil];
  15. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCGImage:ref];
  16. [rep setSize:[image size]];
  17. return [rep representationUsingType:NSPNGFileType
  18. properties:[[NSDictionary alloc] init]];
  19. }
  20. double safeShift(double in, double def) {
  21. if (in >= 0 || in <= 1 || in == def)
  22. return in;
  23. return def;
  24. }
  25. mate::Handle<NativeImage> NativeImage::CreateFromNamedImage(
  26. mate::Arguments* args,
  27. const std::string& name) {
  28. @autoreleasepool {
  29. std::vector<double> hsl_shift;
  30. NSImage* image = [NSImage imageNamed:base::SysUTF8ToNSString(name)];
  31. if (!image.valid) {
  32. return CreateEmpty(args->isolate());
  33. }
  34. NSData* png_data = bufferFromNSImage(image);
  35. if (args->GetNext(&hsl_shift) && hsl_shift.size() == 3) {
  36. gfx::Image gfx_image = gfx::Image::CreateFrom1xPNGBytes(
  37. reinterpret_cast<const unsigned char*>((char*)[png_data bytes]),
  38. [png_data length]);
  39. color_utils::HSL shift = {safeShift(hsl_shift[0], -1),
  40. safeShift(hsl_shift[1], 0.5),
  41. safeShift(hsl_shift[2], 0.5)};
  42. png_data = bufferFromNSImage(
  43. gfx::Image(gfx::ImageSkiaOperations::CreateHSLShiftedImage(
  44. gfx_image.AsImageSkia(), shift))
  45. .CopyNSImage());
  46. }
  47. return CreateFromPNG(args->isolate(), (char*)[png_data bytes],
  48. [png_data length]);
  49. }
  50. }
  51. void NativeImage::SetTemplateImage(bool setAsTemplate) {
  52. [image_.AsNSImage() setTemplate:setAsTemplate];
  53. }
  54. bool NativeImage::IsTemplateImage() {
  55. return [image_.AsNSImage() isTemplate];
  56. }
  57. } // namespace api
  58. } // namespace atom