electron/atom/common/api/atom_api_native_image_mac.mm

77 lines
2.2 KiB
Text
Raw Normal View History

// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/atom_api_native_image.h"
#include <string>
#include <vector>
#import <Cocoa/Cocoa.h>
#include "base/strings/sys_string_conversions.h"
2017-10-10 06:05:13 +00:00
#include "ui/gfx/color_utils.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
namespace atom {
namespace api {
2017-10-10 06:05:13 +00:00
NSData* bufferFromNSImage(NSImage* image) {
CGImageRef ref = [image CGImageForProposedRect:nil context:nil hints:nil];
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCGImage:ref];
[rep setSize:[image size]];
2018-04-20 18:47:04 +00:00
return [rep representationUsingType:NSPNGFileType
properties:[[NSDictionary alloc] init]];
2017-10-10 06:05:13 +00:00
}
double safeShift(double in, double def) {
2018-04-20 18:47:04 +00:00
if (in >= 0 || in <= 1 || in == def)
return in;
2017-10-10 06:05:13 +00:00
return def;
}
mate::Handle<NativeImage> NativeImage::CreateFromNamedImage(
2018-04-20 18:47:04 +00:00
mate::Arguments* args,
const std::string& name) {
@autoreleasepool {
2017-10-10 06:05:13 +00:00
std::vector<double> hsl_shift;
NSImage* image = [NSImage imageNamed:base::SysUTF8ToNSString(name)];
if (!image.valid) {
return CreateEmpty(args->isolate());
}
2017-10-10 06:20:55 +00:00
NSData* png_data = bufferFromNSImage(image);
2017-10-10 06:05:13 +00:00
if (args->GetNext(&hsl_shift) && hsl_shift.size() == 3) {
2017-10-10 06:20:55 +00:00
gfx::Image gfx_image = gfx::Image::CreateFrom1xPNGBytes(
2018-04-20 18:47:04 +00:00
reinterpret_cast<const unsigned char*>((char*)[png_data bytes]),
[png_data length]);
color_utils::HSL shift = {safeShift(hsl_shift[0], -1),
safeShift(hsl_shift[1], 0.5),
safeShift(hsl_shift[2], 0.5)};
png_data = bufferFromNSImage(
gfx::Image(gfx::ImageSkiaOperations::CreateHSLShiftedImage(
gfx_image.AsImageSkia(), shift))
.AsNSImage());
2017-10-10 06:05:13 +00:00
}
2018-04-20 18:47:04 +00:00
return CreateFromPNG(args->isolate(), (char*)[png_data bytes],
[png_data length]);
}
}
void NativeImage::SetTemplateImage(bool setAsTemplate) {
[image_.AsNSImage() setTemplate:setAsTemplate];
}
bool NativeImage::IsTemplateImage() {
2015-07-29 03:48:40 +00:00
return [image_.AsNSImage() isTemplate];
}
} // namespace api
} // namespace atom