electron/shell/common/api/electron_api_native_image_mac.mm
electron-roller[bot] 53fd879043
chore: bump chromium to 138.0.7190.0 (main) (#47107)
* chore: bump chromium in DEPS to 138.0.7180.0

* 6546797: Add a metric for the overall success of the "safe storage" item retrieval.

Refs 6546797

* 6548078: extensions: Fix TODO in ScriptInjectionTracker for desktop Android

Refs 6548078

* 6544950: Revert "FSA: Only normalize the hardcoded rules once during initialization"

Refs 6544950

* chore: bump chromium in DEPS to 138.0.7181.0

* chore: update patches

* fix: correctly clamp HSL shift values between 0 and 1

* chore: bump DEPS to 138.0.7183.0

* 6553142: Remove SelectFileDialogLinuxKde | 6553142

* chore: update patches

* chore: bump chromium in DEPS to 138.0.7184.0

* chore: bump chromium in DEPS to 138.0.7186.0

* chore: bump chromium in DEPS to 138.0.7190.0

* chore: update patches

* 6547778: Remove some superfluous //ui/gfx includes from //chrome headers | 6547778

* 6556022: Reland FSA: Only normalize the hardcoded rules once during initialization | 6556022

* fix: remove pdf_extension_util::AddAdditionalData
4099130

This was removed 2 years ago in Chrome.

* fix: provide BrowserContext to pdf_extension_util::AddAdditionalData
6558173

* fixup! 6556022: Reland FSA: Only normalize the hardcoded rules once during initialization | 6556022

* fix: pass in navigation throttle registry
6536175

* fixup! 6556022: Reland "FSA: Only normalize the hardcoded rules once during initialization" | 6556022

This partially reverts commit 20d709dd15ba0ff332e24ee314149d642dc5d47c.

* 6545984: corner-shape: render dashed & dotted borders
Refs 6545984

* Update corner smoothing expected images

* Apply "future" revert commit to fix windows build

> Reason for revert: Multiple eng reporting that this is causing build failures due to too-long pathnames, with no immediate feasible workaround

This issue also affects our CI builds.

Problematic CL in current roll: 6494836: [webgl] Add stub WebGL[2]RenderingContextWebGPU | 6494836
"Future" revert CL: 6565622: Revert "[webgl] Add stub WebGL[2]RenderingContextWebGPU" | 6565622

This patch should automatically disappear when we roll the revert.

* 6533919: win: don't add WS_CAPTION style to popup windows
6533919

This mirrors the change made earlier to the code ours is based on: 6374074: [headless] Provide headless aware window metrics on Windows | 6374074

---------

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: David Sanders <dsanders11@ucsbalum.com>
Co-authored-by: Keeley Hammond <khammond@slack-corp.com>
Co-authored-by: Samuel Maddock <smaddock@slack-corp.com>
Co-authored-by: clavin <clavin@electronjs.org>
2025-06-03 11:19:20 -04:00

155 lines
5.4 KiB
Text

// 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 "shell/common/api/electron_api_native_image.h"
#include <string>
#include <utility>
#include <vector>
#import <Cocoa/Cocoa.h>
#import <QuickLook/QuickLook.h>
#import <QuickLookThumbnailing/QuickLookThumbnailing.h>
#include "base/apple/foundation_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/task/bind_post_task.h"
#include "gin/arguments.h"
#include "gin/handle.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/mac_util.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
namespace electron::api {
NSData* bufferFromNSImage(NSImage* image) {
CGImageRef ref = [image CGImageForProposedRect:nil context:nil hints:nil];
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCGImage:ref];
[rep setSize:[image size]];
return [rep representationUsingType:NSBitmapImageFileTypePNG
properties:[[NSDictionary alloc] init]];
}
double safeShift(double in, double def) {
if ((in >= 0 && in <= 1) || in == def)
return in;
return def;
}
void ReceivedThumbnailResult(CGSize size,
gin_helper::Promise<gfx::Image> p,
QLThumbnailRepresentation* thumbnail,
NSError* error) {
if (error || !thumbnail) {
std::string err_msg([error.localizedDescription UTF8String]);
p.RejectWithErrorMessage("unable to retrieve thumbnail preview "
"image for the given path: " +
err_msg);
} else {
NSImage* result = [[NSImage alloc] initWithCGImage:[thumbnail CGImage]
size:size];
gfx::Image image(result);
p.Resolve(image);
}
}
// static
v8::Local<v8::Promise> NativeImage::CreateThumbnailFromPath(
v8::Isolate* isolate,
const base::FilePath& path,
const gfx::Size& size) {
gin_helper::Promise<gfx::Image> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (size.IsEmpty()) {
promise.RejectWithErrorMessage("size must not be empty");
return handle;
}
CGSize cg_size = size.ToCGSize();
NSURL* nsurl = base::apple::FilePathToNSURL(path);
// We need to explicitly check if the user has passed an invalid path
// because QLThumbnailGenerationRequest will generate a stock file icon
// and pass silently if we do not.
if (![[NSFileManager defaultManager] fileExistsAtPath:[nsurl path]]) {
promise.RejectWithErrorMessage(
"unable to retrieve thumbnail preview image for the given path");
return handle;
}
NSScreen* screen = [[NSScreen screens] firstObject];
QLThumbnailGenerationRequest* request([[QLThumbnailGenerationRequest alloc]
initWithFileAtURL:nsurl
size:cg_size
scale:[screen backingScaleFactor]
representationTypes:QLThumbnailGenerationRequestRepresentationTypeAll]);
__block auto block_callback = base::BindPostTaskToCurrentDefault(
base::BindOnce(&ReceivedThumbnailResult, cg_size, std::move(promise)));
auto completionHandler =
^(QLThumbnailRepresentation* thumbnail, NSError* error) {
std::move(block_callback).Run(thumbnail, error);
};
[[QLThumbnailGenerator sharedGenerator]
generateBestRepresentationForRequest:request
completionHandler:completionHandler];
return handle;
}
gin::Handle<NativeImage> NativeImage::CreateFromNamedImage(gin::Arguments* args,
std::string name) {
@autoreleasepool {
std::vector<double> hsl_shift;
// The string representations of NSImageNames don't match the strings
// themselves; they instead follow the following pattern:
// * NSImageNameActionTemplate -> "NSActionTemplate"
// * NSImageNameMultipleDocuments -> "NSMultipleDocuments"
// To account for this, we strip out "ImageName" from the passed string.
std::string to_remove("ImageName");
size_t pos = name.find(to_remove);
if (pos != std::string::npos) {
name.erase(pos, to_remove.length());
}
NSImage* image = [NSImage imageNamed:base::SysUTF8ToNSString(name)];
if (!image.valid) {
return CreateEmpty(args->isolate());
}
NSData* png_data = bufferFromNSImage(image);
if (args->GetNext(&hsl_shift) && hsl_shift.size() == 3) {
auto gfx_image = gfx::Image::CreateFrom1xPNGBytes(
electron::util::as_byte_span(png_data));
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());
}
return CreateFromPNG(args->isolate(),
electron::util::as_byte_span(png_data));
}
}
void NativeImage::SetTemplateImage(bool setAsTemplate) {
[image_.AsNSImage() setTemplate:setAsTemplate];
}
bool NativeImage::IsTemplateImage() {
return [image_.AsNSImage() isTemplate];
}
} // namespace electron::api