refactor: remove path from nativeImage converter (#26546)

This commit is contained in:
Shelley Vohr 2021-01-04 12:58:31 -08:00 committed by GitHub
parent 4db3e3a08a
commit 3455136e9d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 167 additions and 103 deletions

View file

@ -17,6 +17,7 @@
#include "gin/arguments.h"
#include "gin/object_template_builder.h"
#include "gin/per_isolate_data.h"
#include "gin/wrappable.h"
#include "net/base/data_url.h"
#include "shell/common/asar/asar_util.h"
#include "shell/common/gin_converters/file_path_converter.h"
@ -134,6 +135,33 @@ NativeImage::~NativeImage() {
}
}
// static
bool NativeImage::TryConvertNativeImage(v8::Isolate* isolate,
v8::Local<v8::Value> image,
NativeImage** native_image) {
base::FilePath icon_path;
if (gin::ConvertFromV8(isolate, image, &icon_path)) {
*native_image = NativeImage::CreateFromPath(isolate, icon_path).get();
if ((*native_image)->image().IsEmpty()) {
#if defined(OS_WIN)
const auto img_path = base::UTF16ToUTF8(icon_path.value());
#else
const auto img_path = icon_path.value();
#endif
isolate->ThrowException(v8::Exception::Error(gin::StringToV8(
isolate, "Failed to load image from path '" + img_path + "'")));
return false;
}
} else {
if (!gin::ConvertFromV8(isolate, image, native_image)) {
isolate->ThrowException(v8::Exception::Error(gin::StringToV8(
isolate, "Argument must be a file path or a NativeImage")));
return false;
}
}
return true;
}
#if defined(OS_WIN)
HICON NativeImage::GetHICON(int size) {
auto iter = hicons_.find(size);
@ -571,50 +599,6 @@ gin::WrapperInfo NativeImage::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron
namespace gin {
v8::Local<v8::Value> Converter<electron::api::NativeImage*>::ToV8(
v8::Isolate* isolate,
electron::api::NativeImage* val) {
v8::Local<v8::Object> ret;
if (val && val->GetWrapper(isolate).ToLocal(&ret))
return ret;
else
return v8::Null(isolate);
}
bool Converter<electron::api::NativeImage*>::FromV8(
v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::NativeImage** out) {
// Try converting from file path.
base::FilePath path;
if (ConvertFromV8(isolate, val, &path)) {
*out = electron::api::NativeImage::CreateFromPath(isolate, path).get();
if ((*out)->image().IsEmpty()) {
#if defined(OS_WIN)
const auto img_path = base::UTF16ToUTF8(path.value());
#else
const auto img_path = path.value();
#endif
isolate->ThrowException(v8::Exception::Error(
StringToV8(isolate, "Image could not be created from " + img_path)));
return false;
}
return true;
}
// reinterpret_cast is safe here because NativeImage is the only subclass of
// gin::Wrappable<NativeImage>.
*out = static_cast<electron::api::NativeImage*>(
static_cast<gin::WrappableBase*>(gin::internal::FromV8Impl(
isolate, val, &electron::api::NativeImage::kWrapperInfo)));
return *out != nullptr;
}
} // namespace gin
namespace {
using electron::api::NativeImage;