refactor: migrates util::Promise to gin (#20871)

* refactor: use gin in Promise

* refactor: separate Promise impl that returns nothing

* refactor: use Promise<void> for promise that returns nothing

* fix: methods should be able to run on both browser and renderer process

* fix: should not pass base::StringPiece across threads

* refactor: no more need to use different ResolvePromise for empty Promise

* refactor: move Promise to gin_helper
This commit is contained in:
Cheng Zhao 2019-11-01 15:10:32 +09:00 committed by GitHub
parent bff113760a
commit eaf2c61bef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
48 changed files with 483 additions and 479 deletions

View file

@ -504,6 +504,8 @@ filenames = {
"shell/common/gin_helper/object_template_builder.h",
"shell/common/gin_helper/persistent_dictionary.cc",
"shell/common/gin_helper/persistent_dictionary.h",
"shell/common/gin_helper/promise.h",
"shell/common/gin_helper/promise.cc",
"shell/common/gin_helper/trackable_object.cc",
"shell/common/gin_helper/trackable_object.h",
"shell/common/heap_snapshot.cc",
@ -534,8 +536,6 @@ filenames = {
"shell/common/platform_util_linux.cc",
"shell/common/platform_util_mac.mm",
"shell/common/platform_util_win.cc",
"shell/common/promise_util.h",
"shell/common/promise_util.cc",
"shell/common/skia_util.h",
"shell/common/skia_util.cc",
"shell/common/v8_value_converter.cc",

View file

@ -532,9 +532,10 @@ int ImportIntoCertStore(CertificateManagerModel* model,
}
#endif
void OnIconDataAvailable(util::Promise<gfx::Image> promise, gfx::Image icon) {
void OnIconDataAvailable(gin_helper::Promise<gfx::Image> promise,
gfx::Image icon) {
if (!icon.IsEmpty()) {
promise.ResolveWithGin(icon);
promise.Resolve(icon);
} else {
promise.RejectWithErrorMessage("Failed to get file icon.");
}
@ -1175,7 +1176,7 @@ JumpListResult App::SetJumpList(v8::Local<v8::Value> val,
v8::Local<v8::Promise> App::GetFileIcon(const base::FilePath& path,
gin_helper::Arguments* args) {
util::Promise<gfx::Image> promise(isolate());
gin_helper::Promise<gfx::Image> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
base::FilePath normalized_path = path.NormalizePathSeparators();
@ -1193,7 +1194,7 @@ v8::Local<v8::Promise> App::GetFileIcon(const base::FilePath& path,
gfx::Image* icon =
icon_manager->LookupIconFromFilepath(normalized_path, icon_size);
if (icon) {
promise.ResolveWithGin(*icon);
promise.Resolve(*icon);
} else {
icon_manager->LoadIcon(
normalized_path, icon_size,
@ -1285,7 +1286,7 @@ v8::Local<v8::Value> App::GetGPUFeatureStatus(v8::Isolate* isolate) {
v8::Local<v8::Promise> App::GetGPUInfo(v8::Isolate* isolate,
const std::string& info_type) {
auto* const gpu_data_manager = content::GpuDataManagerImpl::GetInstance();
util::Promise<base::DictionaryValue> promise(isolate);
gin_helper::Promise<base::DictionaryValue> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (info_type != "basic" && info_type != "complete") {
promise.RejectWithErrorMessage(

View file

@ -28,7 +28,7 @@
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/event_emitter.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
#if defined(USE_NSS_CERTS)
#include "chrome/browser/certificate_manager_model.h"

View file

@ -14,8 +14,8 @@
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/promise_util.h"
using content::TracingController;
@ -63,14 +63,13 @@ base::Optional<base::FilePath> CreateTemporaryFileOnIO() {
return base::make_optional(std::move(temp_file_path));
}
void StopTracing(electron::util::Promise<base::FilePath> promise,
void StopTracing(gin_helper::Promise<base::FilePath> promise,
base::Optional<base::FilePath> file_path) {
if (file_path) {
auto endpoint = TracingController::CreateFileEndpoint(
*file_path,
base::AdaptCallbackForRepeating(base::BindOnce(
&electron::util::Promise<base::FilePath>::ResolvePromise,
std::move(promise), *file_path)));
*file_path, base::AdaptCallbackForRepeating(base::BindOnce(
&gin_helper::Promise<base::FilePath>::ResolvePromise,
std::move(promise), *file_path)));
TracingController::GetInstance()->StopTracing(endpoint);
} else {
promise.RejectWithErrorMessage(
@ -79,7 +78,7 @@ void StopTracing(electron::util::Promise<base::FilePath> promise,
}
v8::Local<v8::Promise> StopRecording(gin_helper::Arguments* args) {
electron::util::Promise<base::FilePath> promise(args->isolate());
gin_helper::Promise<base::FilePath> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
base::FilePath path;
@ -99,12 +98,12 @@ v8::Local<v8::Promise> StopRecording(gin_helper::Arguments* args) {
}
v8::Local<v8::Promise> GetCategories(v8::Isolate* isolate) {
electron::util::Promise<const std::set<std::string>&> promise(isolate);
gin_helper::Promise<const std::set<std::string>&> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// Note: This method always succeeds.
TracingController::GetInstance()->GetCategories(base::BindOnce(
electron::util::Promise<const std::set<std::string>&>::ResolvePromise,
gin_helper::Promise<const std::set<std::string>&>::ResolvePromise,
std::move(promise)));
return handle;
@ -113,35 +112,35 @@ v8::Local<v8::Promise> GetCategories(v8::Isolate* isolate) {
v8::Local<v8::Promise> StartTracing(
v8::Isolate* isolate,
const base::trace_event::TraceConfig& trace_config) {
electron::util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!TracingController::GetInstance()->StartTracing(
trace_config,
base::BindOnce(electron::util::Promise<void*>::ResolveEmptyPromise,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)))) {
// If StartTracing returns false, that means it didn't invoke its callback.
// Return an already-resolved promise and abandon the previous promise (it
// was std::move()d into the StartTracing callback and has been deleted by
// this point).
return electron::util::Promise<void*>::ResolvedPromise(isolate);
return gin_helper::Promise<void>::ResolvedPromise(isolate);
}
return handle;
}
void OnTraceBufferUsageAvailable(
electron::util::Promise<gin_helper::Dictionary> promise,
gin_helper::Promise<gin_helper::Dictionary> promise,
float percent_full,
size_t approximate_count) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("percentage", percent_full);
dict.Set("value", approximate_count);
promise.ResolveWithGin(dict);
promise.Resolve(dict);
}
v8::Local<v8::Promise> GetTraceBufferUsage(v8::Isolate* isolate) {
electron::util::Promise<gin_helper::Dictionary> promise(isolate);
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// Note: This method always succeeds.

View file

@ -121,18 +121,18 @@ bool MatchesCookie(const base::Value& filter,
// Remove cookies from |list| not matching |filter|, and pass it to |callback|.
void FilterCookies(const base::Value& filter,
util::Promise<net::CookieList> promise,
gin_helper::Promise<net::CookieList> promise,
const net::CookieList& cookies) {
net::CookieList result;
for (const auto& cookie : cookies) {
if (MatchesCookie(filter, cookie))
result.push_back(cookie);
}
promise.ResolveWithGin(result);
promise.Resolve(result);
}
void FilterCookieWithStatuses(const base::Value& filter,
util::Promise<net::CookieList> promise,
gin_helper::Promise<net::CookieList> promise,
const net::CookieStatusList& list,
const net::CookieStatusList& excluded_list) {
FilterCookies(filter, std::move(promise),
@ -176,7 +176,7 @@ Cookies::Cookies(v8::Isolate* isolate, AtomBrowserContext* browser_context)
Cookies::~Cookies() = default;
v8::Local<v8::Promise> Cookies::Get(const gin_helper::Dictionary& filter) {
util::Promise<net::CookieList> promise(isolate());
gin_helper::Promise<net::CookieList> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* storage_partition = content::BrowserContext::GetDefaultStoragePartition(
@ -208,7 +208,7 @@ v8::Local<v8::Promise> Cookies::Get(const gin_helper::Dictionary& filter) {
v8::Local<v8::Promise> Cookies::Remove(const GURL& url,
const std::string& name) {
util::Promise<void*> promise(isolate());
gin_helper::Promise<void> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
auto cookie_deletion_filter = network::mojom::CookieDeletionFilter::New();
@ -222,8 +222,8 @@ v8::Local<v8::Promise> Cookies::Remove(const GURL& url,
manager->DeleteCookies(
std::move(cookie_deletion_filter),
base::BindOnce(
[](util::Promise<void*> promise, uint32_t num_deleted) {
util::Promise<void*>::ResolveEmptyPromise(std::move(promise));
[](gin_helper::Promise<void> promise, uint32_t num_deleted) {
gin_helper::Promise<void>::ResolvePromise(std::move(promise));
},
std::move(promise)));
@ -231,7 +231,7 @@ v8::Local<v8::Promise> Cookies::Remove(const GURL& url,
}
v8::Local<v8::Promise> Cookies::Set(base::DictionaryValue details) {
util::Promise<void*> promise(isolate());
gin_helper::Promise<void> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
const std::string* url_string = details.FindStringKey("url");
@ -296,7 +296,7 @@ v8::Local<v8::Promise> Cookies::Set(base::DictionaryValue details) {
manager->SetCanonicalCookie(
*canonical_cookie, url.scheme(), options,
base::BindOnce(
[](util::Promise<void*> promise,
[](gin_helper::Promise<void> promise,
net::CanonicalCookie::CookieInclusionStatus status) {
if (status.IsInclude()) {
promise.Resolve();
@ -310,7 +310,7 @@ v8::Local<v8::Promise> Cookies::Set(base::DictionaryValue details) {
}
v8::Local<v8::Promise> Cookies::FlushStore() {
util::Promise<void*> promise(isolate());
gin_helper::Promise<void> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* storage_partition = content::BrowserContext::GetDefaultStoragePartition(
@ -318,7 +318,7 @@ v8::Local<v8::Promise> Cookies::FlushStore() {
auto* manager = storage_partition->GetCookieManagerForBrowserProcess();
manager->FlushCookieStore(base::BindOnce(
util::Promise<void*>::ResolveEmptyPromise, std::move(promise)));
gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
return handle;
}

View file

@ -12,8 +12,8 @@
#include "gin/handle.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_change_dispatcher.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/gin_helper/trackable_object.h"
#include "shell/common/promise_util.h"
namespace base {
class DictionaryValue;

View file

@ -12,8 +12,8 @@
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "net/base/net_errors.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/key_weak_map.h"
#include "shell/common/promise_util.h"
#include "shell/common/node_includes.h"
@ -32,7 +32,7 @@ KeyWeakMap<std::string> g_weak_map;
// Utility class to read from data pipe.
class DataPipeReader {
public:
DataPipeReader(util::Promise<v8::Local<v8::Value>> promise,
DataPipeReader(gin_helper::Promise<v8::Local<v8::Value>> promise,
mojo::Remote<network::mojom::DataPipeGetter> data_pipe_getter)
: promise_(std::move(promise)),
data_pipe_getter_(std::move(data_pipe_getter)),
@ -116,7 +116,7 @@ class DataPipeReader {
delete static_cast<DataPipeReader*>(self);
}
util::Promise<v8::Local<v8::Value>> promise_;
gin_helper::Promise<v8::Local<v8::Value>> promise_;
mojo::Remote<network::mojom::DataPipeGetter> data_pipe_getter_;
mojo::ScopedDataPipeConsumerHandle data_pipe_;
@ -148,7 +148,7 @@ DataPipeHolder::DataPipeHolder(const network::DataElement& element)
DataPipeHolder::~DataPipeHolder() = default;
v8::Local<v8::Promise> DataPipeHolder::ReadAll(v8::Isolate* isolate) {
util::Promise<v8::Local<v8::Value>> promise(isolate);
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!data_pipe_) {
promise.RejectWithErrorMessage("Could not get blob data");

View file

@ -65,8 +65,7 @@ void Debugger::DispatchProtocolMessage(DevToolsAgentHost* agent_host,
if (it == pending_requests_.end())
return;
electron::util::Promise<base::DictionaryValue> promise =
std::move(it->second);
gin_helper::Promise<base::DictionaryValue> promise = std::move(it->second);
pending_requests_.erase(it);
base::DictionaryValue* error = nullptr;
@ -80,7 +79,7 @@ void Debugger::DispatchProtocolMessage(DevToolsAgentHost* agent_host,
if (dict->GetDictionary("result", &result_body)) {
result.Swap(result_body);
}
promise.ResolveWithGin(result);
promise.Resolve(result);
}
}
}
@ -130,7 +129,7 @@ void Debugger::Detach() {
}
v8::Local<v8::Promise> Debugger::SendCommand(gin_helper::Arguments* args) {
electron::util::Promise<base::DictionaryValue> promise(isolate());
gin_helper::Promise<base::DictionaryValue> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!agent_host_) {

View file

@ -13,8 +13,8 @@
#include "content/public/browser/devtools_agent_host_client.h"
#include "content/public/browser/web_contents_observer.h"
#include "gin/handle.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/gin_helper/trackable_object.h"
#include "shell/common/promise_util.h"
namespace content {
class DevToolsAgentHost;
@ -51,7 +51,7 @@ class Debugger : public gin_helper::TrackableObject<Debugger>,
private:
using PendingRequestMap =
std::map<int, electron::util::Promise<base::DictionaryValue>>;
std::map<int, gin_helper::Promise<base::DictionaryValue>>;
void Attach(gin_helper::Arguments* args);
bool IsAttached();

View file

@ -16,8 +16,8 @@
#include "shell/common/gin_converters/native_window_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/promise_util.h"
namespace {
@ -25,24 +25,23 @@ int ShowMessageBoxSync(const electron::MessageBoxSettings& settings) {
return electron::ShowMessageBoxSync(settings);
}
void ResolvePromiseObject(
electron::util::Promise<gin_helper::Dictionary> promise,
int result,
bool checkbox_checked) {
void ResolvePromiseObject(gin_helper::Promise<gin_helper::Dictionary> promise,
int result,
bool checkbox_checked) {
v8::Isolate* isolate = promise.isolate();
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("response", result);
dict.Set("checkboxChecked", checkbox_checked);
promise.ResolveWithGin(dict);
promise.Resolve(dict);
}
v8::Local<v8::Promise> ShowMessageBox(
const electron::MessageBoxSettings& settings,
gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
electron::util::Promise<gin_helper::Dictionary> promise(isolate);
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
electron::ShowMessageBox(
@ -61,7 +60,7 @@ void ShowOpenDialogSync(const file_dialog::DialogSettings& settings,
v8::Local<v8::Promise> ShowOpenDialog(
const file_dialog::DialogSettings& settings,
gin::Arguments* args) {
electron::util::Promise<gin_helper::Dictionary> promise(args->isolate());
gin_helper::Promise<gin_helper::Dictionary> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
file_dialog::ShowOpenDialog(settings, std::move(promise));
return handle;
@ -77,7 +76,7 @@ void ShowSaveDialogSync(const file_dialog::DialogSettings& settings,
v8::Local<v8::Promise> ShowSaveDialog(
const file_dialog::DialogSettings& settings,
gin::Arguments* args) {
electron::util::Promise<gin_helper::Dictionary> promise(args->isolate());
gin_helper::Promise<gin_helper::Dictionary> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
file_dialog::ShowSaveDialog(settings, std::move(promise));

View file

@ -104,7 +104,7 @@ v8::Local<v8::Promise> InAppPurchase::PurchaseProduct(
const std::string& product_id,
gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
electron::util::Promise<bool> promise(isolate);
gin_helper::Promise<bool> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
int quantity = 1;
@ -112,7 +112,8 @@ v8::Local<v8::Promise> InAppPurchase::PurchaseProduct(
in_app_purchase::PurchaseProduct(
product_id, quantity,
base::BindOnce(util::Promise<bool>::ResolvePromise, std::move(promise)));
base::BindOnce(gin_helper::Promise<bool>::ResolvePromise,
std::move(promise)));
return handle;
}
@ -121,15 +122,14 @@ v8::Local<v8::Promise> InAppPurchase::GetProducts(
const std::vector<std::string>& productIDs,
gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
electron::util::Promise<std::vector<in_app_purchase::Product>> promise(
isolate);
gin_helper::Promise<std::vector<in_app_purchase::Product>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
in_app_purchase::GetProducts(
productIDs,
base::BindOnce(
util::Promise<std::vector<in_app_purchase::Product>>::ResolvePromise,
std::move(promise)));
base::BindOnce(gin_helper::Promise<
std::vector<in_app_purchase::Product>>::ResolvePromise,
std::move(promise)));
return handle;
}

View file

@ -13,7 +13,7 @@
#include "shell/browser/mac/in_app_purchase_observer.h"
#include "shell/browser/mac/in_app_purchase_product.h"
#include "shell/common/gin_helper/event_emitter.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
namespace electron {

View file

@ -62,7 +62,8 @@ base::File OpenFileForWriting(base::FilePath path) {
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
}
void ResolvePromiseWithNetError(util::Promise<void*> promise, int32_t error) {
void ResolvePromiseWithNetError(gin_helper::Promise<void> promise,
int32_t error) {
if (error == net::OK) {
promise.Resolve();
} else {
@ -117,7 +118,8 @@ v8::Local<v8::Promise> NetLog::StartLogging(base::FilePath log_path,
return v8::Local<v8::Promise>();
}
pending_start_promise_ = base::make_optional<util::Promise<void*>>(isolate());
pending_start_promise_ =
base::make_optional<gin_helper::Promise<void>>(isolate());
v8::Local<v8::Promise> handle = pending_start_promise_->GetHandle();
auto command_line_string =
@ -187,7 +189,7 @@ bool NetLog::IsCurrentlyLogging() const {
}
v8::Local<v8::Promise> NetLog::StopLogging(gin_helper::Arguments* args) {
util::Promise<void*> promise(isolate());
gin_helper::Promise<void> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
if (net_log_exporter_) {
@ -197,8 +199,8 @@ v8::Local<v8::Promise> NetLog::StopLogging(gin_helper::Arguments* args) {
net_log_exporter_->Stop(
base::Value(base::Value::Type::DICTIONARY),
base::BindOnce(
[](network::mojom::NetLogExporterPtr, util::Promise<void*> promise,
int32_t error) {
[](network::mojom::NetLogExporterPtr,
gin_helper::Promise<void> promise, int32_t error) {
ResolvePromiseWithNetError(std::move(promise), error);
},
std::move(net_log_exporter_), std::move(promise)));

View file

@ -14,8 +14,8 @@
#include "base/values.h"
#include "gin/handle.h"
#include "services/network/public/mojom/net_log.mojom.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/gin_helper/trackable_object.h"
#include "shell/common/promise_util.h"
namespace electron {
@ -53,7 +53,7 @@ class NetLog : public gin_helper::TrackableObject<NetLog> {
network::mojom::NetLogExporterPtr net_log_exporter_;
base::Optional<util::Promise<void*>> pending_start_promise_;
base::Optional<gin_helper::Promise<void>> pending_start_promise_;
scoped_refptr<base::TaskRunner> file_task_runner_;

View file

@ -17,8 +17,8 @@
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/options_switches.h"
#include "shell/common/promise_util.h"
#include "url/url_util.h"
namespace {
@ -223,7 +223,7 @@ v8::Local<v8::Promise> Protocol::IsProtocolHandled(const std::string& scheme,
"protocol.isProtocolRegistered or protocol.isProtocolIntercepted "
"instead.",
"ProtocolDeprecateIsProtocolHandled");
return util::Promise<bool>::ResolvedPromise(
return gin_helper::Promise<bool>::ResolvedPromise(
isolate(), IsProtocolRegistered(scheme) ||
IsProtocolIntercepted(scheme) ||
// The |isProtocolHandled| should return true for builtin

View file

@ -246,14 +246,14 @@ void Session::OnDownloadCreated(content::DownloadManager* manager,
v8::Local<v8::Promise> Session::ResolveProxy(gin_helper::Arguments* args) {
v8::Isolate* isolate = args->isolate();
util::Promise<std::string> promise(isolate);
gin_helper::Promise<std::string> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
GURL url;
args->GetNext(&url);
browser_context_->GetResolveProxyHelper()->ResolveProxy(
url, base::BindOnce(util::Promise<std::string>::ResolvePromise,
url, base::BindOnce(gin_helper::Promise<std::string>::ResolvePromise,
std::move(promise)));
return handle;
@ -261,7 +261,7 @@ v8::Local<v8::Promise> Session::ResolveProxy(gin_helper::Arguments* args) {
v8::Local<v8::Promise> Session::GetCacheSize() {
auto* isolate = v8::Isolate::GetCurrent();
util::Promise<int64_t> promise(isolate);
gin_helper::Promise<int64_t> promise(isolate);
auto handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_.get())
@ -269,7 +269,7 @@ v8::Local<v8::Promise> Session::GetCacheSize() {
->ComputeHttpCacheSize(
base::Time(), base::Time::Max(),
base::BindOnce(
[](util::Promise<int64_t> promise, bool is_upper_bound,
[](gin_helper::Promise<int64_t> promise, bool is_upper_bound,
int64_t size_or_error) {
if (size_or_error < 0) {
promise.RejectWithErrorMessage(
@ -285,13 +285,13 @@ v8::Local<v8::Promise> Session::GetCacheSize() {
v8::Local<v8::Promise> Session::ClearCache() {
auto* isolate = v8::Isolate::GetCurrent();
util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
auto handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_.get())
->GetNetworkContext()
->ClearHttpCache(base::Time(), base::Time::Max(), nullptr,
base::BindOnce(util::Promise<void*>::ResolveEmptyPromise,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
@ -299,7 +299,7 @@ v8::Local<v8::Promise> Session::ClearCache() {
v8::Local<v8::Promise> Session::ClearStorageData(gin_helper::Arguments* args) {
v8::Isolate* isolate = args->isolate();
util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ClearStorageDataOptions options;
@ -316,7 +316,7 @@ v8::Local<v8::Promise> Session::ClearStorageData(gin_helper::Arguments* args) {
storage_partition->ClearData(
options.storage_types, options.quota_types, options.origin, base::Time(),
base::Time::Max(),
base::BindOnce(util::Promise<void*>::ResolveEmptyPromise,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
@ -329,7 +329,7 @@ void Session::FlushStorageData() {
v8::Local<v8::Promise> Session::SetProxy(gin_helper::Arguments* args) {
v8::Isolate* isolate = args->isolate();
util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary options;
@ -362,7 +362,7 @@ v8::Local<v8::Promise> Session::SetProxy(gin_helper::Arguments* args) {
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(util::Promise<void*>::ResolveEmptyPromise,
FROM_HERE, base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
@ -464,13 +464,13 @@ void Session::SetPermissionCheckHandler(v8::Local<v8::Value> val,
v8::Local<v8::Promise> Session::ClearHostResolverCache(
gin_helper::Arguments* args) {
v8::Isolate* isolate = args->isolate();
util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_.get())
->GetNetworkContext()
->ClearHostCache(nullptr,
base::BindOnce(util::Promise<void*>::ResolveEmptyPromise,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
@ -478,14 +478,14 @@ v8::Local<v8::Promise> Session::ClearHostResolverCache(
v8::Local<v8::Promise> Session::ClearAuthCache() {
auto* isolate = v8::Isolate::GetCurrent();
util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_.get())
->GetNetworkContext()
->ClearHttpAuthCache(
base::Time(),
base::BindOnce(util::Promise<void*>::ResolveEmptyPromise,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
@ -515,7 +515,7 @@ v8::Local<v8::Promise> Session::GetBlobData(v8::Isolate* isolate,
const std::string& uuid) {
gin::Handle<DataPipeHolder> holder = DataPipeHolder::From(isolate, uuid);
if (holder.IsEmpty()) {
util::Promise<v8::Local<v8::Value>> promise(isolate);
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
promise.RejectWithErrorMessage("Could not get blob data handle");
return promise.GetHandle();
}

View file

@ -13,8 +13,8 @@
#include "electron/buildflags/buildflags.h"
#include "gin/handle.h"
#include "shell/browser/net/resolve_proxy_helper.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/gin_helper/trackable_object.h"
#include "shell/common/promise_util.h"
class GURL;

View file

@ -12,7 +12,7 @@
#include "gin/handle.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/event_emitter.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
#if defined(OS_WIN)
#include "shell/browser/browser.h"

View file

@ -444,7 +444,7 @@ bool SystemPreferences::CanPromptTouchID() {
v8::Local<v8::Promise> SystemPreferences::PromptTouchID(
v8::Isolate* isolate,
const std::string& reason) {
util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (@available(macOS 10.12.2, *)) {
@ -461,7 +461,7 @@ v8::Local<v8::Promise> SystemPreferences::PromptTouchID(
scoped_refptr<base::SequencedTaskRunner> runner =
base::SequencedTaskRunnerHandle::Get();
__block util::Promise<void*> p = std::move(promise);
__block gin_helper::Promise<void> p = std::move(promise);
[context
evaluateAccessControl:access_control
operation:LAAccessControlOperationUseKeySign
@ -473,13 +473,13 @@ v8::Local<v8::Promise> SystemPreferences::PromptTouchID(
runner->PostTask(
FROM_HERE,
base::BindOnce(
util::Promise<void*>::RejectPromise,
gin_helper::Promise<void>::RejectPromise,
std::move(p), std::move(err_msg)));
} else {
runner->PostTask(
FROM_HERE,
base::BindOnce(
util::Promise<void*>::ResolveEmptyPromise,
gin_helper::Promise<void>::ResolvePromise,
std::move(p)));
}
}];
@ -606,12 +606,12 @@ std::string SystemPreferences::GetMediaAccessStatus(
v8::Local<v8::Promise> SystemPreferences::AskForMediaAccess(
v8::Isolate* isolate,
const std::string& media_type) {
util::Promise<bool> promise(isolate);
gin_helper::Promise<bool> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (auto type = ParseMediaType(media_type)) {
if (@available(macOS 10.14, *)) {
__block util::Promise<bool> p = std::move(promise);
__block gin_helper::Promise<bool> p = std::move(promise);
[AVCaptureDevice requestAccessForMediaType:type
completionHandler:^(BOOL granted) {
dispatch_async(dispatch_get_main_queue(), ^{

View file

@ -320,10 +320,10 @@ namespace api {
namespace {
// Called when CapturePage is done.
void OnCapturePageDone(util::Promise<gfx::Image> promise,
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.ResolveWithGin(gfx::Image::CreateFrom1xBitmap(bitmap));
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
}
base::Optional<base::TimeDelta> GetCursorBlinkInterval() {
@ -1494,7 +1494,7 @@ std::string WebContents::GetUserAgent() {
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
util::Promise<void*> promise(isolate());
gin_helper::Promise<void> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
@ -1864,7 +1864,7 @@ std::vector<printing::PrinterBasicInfo> WebContents::GetPrinterList() {
}
v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) {
util::Promise<v8::Local<v8::Value>> promise(isolate());
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
PrintPreviewMessageHandler::FromWebContents(web_contents())
->PrintToPDF(std::move(settings), std::move(promise));
@ -2167,7 +2167,7 @@ void WebContents::StartDrag(const gin_helper::Dictionary& item,
v8::Local<v8::Promise> WebContents::CapturePage(gin_helper::Arguments* args) {
gfx::Rect rect;
util::Promise<gfx::Image> promise(isolate());
gin_helper::Promise<gfx::Image> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
// get rect arguments if they exist
@ -2175,7 +2175,7 @@ v8::Local<v8::Promise> WebContents::CapturePage(gin_helper::Arguments* args) {
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.ResolveWithGin(gfx::Image());
promise.Resolve(gfx::Image());
return handle;
}
@ -2433,7 +2433,7 @@ void WebContents::GrantOriginAccess(const GURL& url) {
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
const base::FilePath& file_path) {
util::Promise<void*> promise(isolate());
gin_helper::Promise<void> promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
base::ThreadRestrictions::ScopedAllowIO allow_io;
@ -2462,7 +2462,7 @@ v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
mojo::WrapPlatformFile(file.TakePlatformFile()),
base::BindOnce(
[](mojo::AssociatedRemote<mojom::ElectronRenderer>* ep,
util::Promise<void*> promise, bool success) {
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {

View file

@ -47,7 +47,7 @@ void GPUInfoManager::ProcessCompleteInfo() {
// We have received the complete information, resolve all promises that
// were waiting for this info.
for (auto& promise : complete_info_promise_set_) {
promise.ResolveWithGin(*result);
promise.Resolve(*result);
}
complete_info_promise_set_.clear();
}
@ -63,7 +63,7 @@ void GPUInfoManager::OnGpuInfoUpdate() {
// Should be posted to the task runner
void GPUInfoManager::CompleteInfoFetcher(
util::Promise<base::DictionaryValue> promise) {
gin_helper::Promise<base::DictionaryValue> promise) {
complete_info_promise_set_.emplace_back(std::move(promise));
if (NeedsCompleteGpuInfoCollection()) {
@ -75,7 +75,7 @@ void GPUInfoManager::CompleteInfoFetcher(
}
void GPUInfoManager::FetchCompleteInfo(
util::Promise<base::DictionaryValue> promise) {
gin_helper::Promise<base::DictionaryValue> promise) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&GPUInfoManager::CompleteInfoFetcher,
base::Unretained(this), std::move(promise)));
@ -84,10 +84,10 @@ void GPUInfoManager::FetchCompleteInfo(
// This fetches the info synchronously, so no need to post to the task queue.
// There cannot be multiple promises as they are resolved synchronously.
void GPUInfoManager::FetchBasicInfo(
util::Promise<base::DictionaryValue> promise) {
gin_helper::Promise<base::DictionaryValue> promise) {
gpu::GPUInfo gpu_info;
CollectBasicGraphicsInfo(&gpu_info);
promise.ResolveWithGin(*EnumerateGPUInfo(gpu_info));
promise.Resolve(*EnumerateGPUInfo(gpu_info));
}
std::unique_ptr<base::DictionaryValue> GPUInfoManager::EnumerateGPUInfo(

View file

@ -12,7 +12,7 @@
#include "content/browser/gpu/gpu_data_manager_impl.h" // nogncheck
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/gpu_data_manager_observer.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
namespace electron {
@ -24,8 +24,8 @@ class GPUInfoManager : public content::GpuDataManagerObserver {
GPUInfoManager();
~GPUInfoManager() override;
bool NeedsCompleteGpuInfoCollection() const;
void FetchCompleteInfo(util::Promise<base::DictionaryValue> promise);
void FetchBasicInfo(util::Promise<base::DictionaryValue> promise);
void FetchCompleteInfo(gin_helper::Promise<base::DictionaryValue> promise);
void FetchBasicInfo(gin_helper::Promise<base::DictionaryValue> promise);
void OnGpuInfoUpdate() override;
private:
@ -33,12 +33,13 @@ class GPUInfoManager : public content::GpuDataManagerObserver {
gpu::GPUInfo gpu_info) const;
// These should be posted to the task queue
void CompleteInfoFetcher(util::Promise<base::DictionaryValue> promise);
void CompleteInfoFetcher(gin_helper::Promise<base::DictionaryValue> promise);
void ProcessCompleteInfo();
// This set maintains all the promises that should be fulfilled
// once we have the complete information data
std::vector<util::Promise<base::DictionaryValue>> complete_info_promise_set_;
std::vector<gin_helper::Promise<base::DictionaryValue>>
complete_info_promise_set_;
content::GpuDataManager* gpu_data_manager_;
DISALLOW_COPY_AND_ASSIGN(GPUInfoManager);

View file

@ -17,7 +17,7 @@ namespace electron {
namespace api {
SavePageHandler::SavePageHandler(content::WebContents* web_contents,
util::Promise<void*> promise)
gin_helper::Promise<void> promise)
: web_contents_(web_contents), promise_(std::move(promise)) {}
SavePageHandler::~SavePageHandler() = default;

View file

@ -10,7 +10,7 @@
#include "components/download/public/common/download_item.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/save_page_type.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
#include "v8/include/v8.h"
namespace base {
@ -30,7 +30,7 @@ class SavePageHandler : public content::DownloadManager::Observer,
public download::DownloadItem::Observer {
public:
SavePageHandler(content::WebContents* web_contents,
electron::util::Promise<void*> promise);
gin_helper::Promise<void> promise);
~SavePageHandler() override;
bool Handle(const base::FilePath& full_path,
@ -47,7 +47,7 @@ class SavePageHandler : public content::DownloadManager::Observer,
void OnDownloadUpdated(download::DownloadItem* item) override;
content::WebContents* web_contents_; // weak
electron::util::Promise<void*> promise_;
gin_helper::Promise<void> promise_;
};
} // namespace api

View file

@ -124,7 +124,7 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
settings.force_detached = offscreen;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
electron::util::Promise<gin_helper::Dictionary> dialog_promise(isolate);
gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate);
auto dialog_callback =
base::BindOnce(&AtomDownloadManagerDelegate::OnDownloadSaveDialogDone,
base::Unretained(this), download_id, callback);

View file

@ -168,7 +168,7 @@ void Browser::DidFinishLaunching(base::DictionaryValue launch_info) {
v8::Local<v8::Value> Browser::WhenReady(v8::Isolate* isolate) {
if (!ready_promise_) {
ready_promise_ = std::make_unique<util::Promise<void*>>(isolate);
ready_promise_ = std::make_unique<gin_helper::Promise<void>>(isolate);
if (is_ready()) {
ready_promise_->Resolve();
}

View file

@ -16,7 +16,7 @@
#include "base/values.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/window_list_observer.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
#if defined(OS_WIN)
#include <windows.h>
@ -304,7 +304,7 @@ class Browser : public WindowListObserver {
int badge_count_ = 0;
std::unique_ptr<util::Promise<void*>> ready_promise_;
std::unique_ptr<gin_helper::Promise<void>> ready_promise_;
#if defined(OS_LINUX) || defined(OS_WIN)
base::Value about_panel_options_;

View file

@ -21,8 +21,8 @@
#include "shell/browser/window_list.h"
#include "shell/common/application_info.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/platform_util.h"
#include "shell/common/promise_util.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
@ -314,7 +314,7 @@ bool Browser::DockIsVisible() {
}
v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
BOOL active = [[NSRunningApplication currentApplication] isActive];
@ -328,7 +328,7 @@ v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
__block util::Promise<void*> p = std::move(promise);
__block gin_helper::Promise<void> p = std::move(promise);
dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms, dispatch_get_main_queue(), ^{
TransformProcessType(&psn, kProcessTransformToForegroundApplication);

View file

@ -144,7 +144,7 @@ void PrintPreviewMessageHandler::OnPrintPreviewCancelled(
void PrintPreviewMessageHandler::PrintToPDF(
base::DictionaryValue options,
electron::util::Promise<v8::Local<v8::Value>> promise) {
gin_helper::Promise<v8::Local<v8::Value>> promise) {
int request_id;
options.GetInteger(printing::kPreviewRequestID, &request_id);
promise_map_.emplace(request_id, std::move(promise));
@ -156,12 +156,12 @@ void PrintPreviewMessageHandler::PrintToPDF(
rfh->Send(new PrintMsg_PrintPreview(rfh->GetRoutingID(), options));
}
util::Promise<v8::Local<v8::Value>> PrintPreviewMessageHandler::GetPromise(
int request_id) {
gin_helper::Promise<v8::Local<v8::Value>>
PrintPreviewMessageHandler::GetPromise(int request_id) {
auto it = promise_map_.find(request_id);
DCHECK(it != promise_map_.end());
util::Promise<v8::Local<v8::Value>> promise = std::move(it->second);
gin_helper::Promise<v8::Local<v8::Value>> promise = std::move(it->second);
promise_map_.erase(it);
return promise;
@ -172,7 +172,7 @@ void PrintPreviewMessageHandler::ResolvePromise(
scoped_refptr<base::RefCountedMemory> data_bytes) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
util::Promise<v8::Local<v8::Value>> promise = GetPromise(request_id);
gin_helper::Promise<v8::Local<v8::Value>> promise = GetPromise(request_id);
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
@ -192,7 +192,7 @@ void PrintPreviewMessageHandler::ResolvePromise(
void PrintPreviewMessageHandler::RejectPromise(int request_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
util::Promise<v8::Local<v8::Value>> promise = GetPromise(request_id);
gin_helper::Promise<v8::Local<v8::Value>> promise = GetPromise(request_id);
promise.RejectWithErrorMessage("Failed to generate PDF");
}

View file

@ -12,7 +12,7 @@
#include "components/services/pdf_compositor/public/mojom/pdf_compositor.mojom.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
#include "v8/include/v8.h"
struct PrintHostMsg_DidPreviewDocument_Params;
@ -32,7 +32,7 @@ class PrintPreviewMessageHandler
~PrintPreviewMessageHandler() override;
void PrintToPDF(base::DictionaryValue options,
util::Promise<v8::Local<v8::Value>> promise);
gin_helper::Promise<v8::Local<v8::Value>> promise);
protected:
// content::WebContentsObserver implementation.
@ -56,14 +56,13 @@ class PrintPreviewMessageHandler
void OnPrintPreviewCancelled(int document_cookie,
const PrintHostMsg_PreviewIds& ids);
util::Promise<v8::Local<v8::Value>> GetPromise(int request_id);
gin_helper::Promise<v8::Local<v8::Value>> GetPromise(int request_id);
void ResolvePromise(int request_id,
scoped_refptr<base::RefCountedMemory> data_bytes);
void RejectPromise(int request_id);
using PromiseMap =
std::map<int, electron::util::Promise<v8::Local<v8::Value>>>;
using PromiseMap = std::map<int, gin_helper::Promise<v8::Local<v8::Value>>>;
PromiseMap promise_map_;
base::WeakPtrFactory<PrintPreviewMessageHandler> weak_ptr_factory_;

View file

@ -9,7 +9,7 @@
#include "base/memory/ref_counted.h"
#include "net/cert/x509_certificate.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
namespace electron {
class NativeWindow;

View file

@ -19,7 +19,7 @@
@interface TrustDelegate : NSObject {
@private
std::unique_ptr<electron::util::Promise<void*>> promise_;
std::unique_ptr<gin_helper::Promise<void>> promise_;
SFCertificateTrustPanel* panel_;
scoped_refptr<net::X509Certificate> cert_;
SecTrustRef trust_;
@ -27,7 +27,7 @@
SecPolicyRef sec_policy_;
}
- (id)initWithPromise:(electron::util::Promise<void*>)promise
- (id)initWithPromise:(gin_helper::Promise<void>)promise
panel:(SFCertificateTrustPanel*)panel
cert:(const scoped_refptr<net::X509Certificate>&)cert
trust:(SecTrustRef)trust
@ -51,14 +51,14 @@
[super dealloc];
}
- (id)initWithPromise:(electron::util::Promise<void*>)promise
- (id)initWithPromise:(gin_helper::Promise<void>)promise
panel:(SFCertificateTrustPanel*)panel
cert:(const scoped_refptr<net::X509Certificate>&)cert
trust:(SecTrustRef)trust
certChain:(CFArrayRef)certChain
secPolicy:(SecPolicyRef)secPolicy {
if ((self = [super init])) {
promise_.reset(new electron::util::Promise<void*>(std::move(promise)));
promise_.reset(new gin_helper::Promise<void>(std::move(promise)));
panel_ = panel;
cert_ = cert;
trust_ = trust;
@ -90,7 +90,7 @@ v8::Local<v8::Promise> ShowCertificateTrust(
const scoped_refptr<net::X509Certificate>& cert,
const std::string& message) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
electron::util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* sec_policy = SecPolicyCreateBasicX509();

View file

@ -61,7 +61,7 @@ v8::Local<v8::Promise> ShowCertificateTrust(
const scoped_refptr<net::X509Certificate>& cert,
const std::string& message) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
electron::util::Promise<void*> promise(isolate);
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
PCCERT_CHAIN_CONTEXT chain_context;

View file

@ -11,7 +11,7 @@
#include "base/files/file_path.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
namespace electron {
class NativeWindow;
@ -65,12 +65,12 @@ bool ShowOpenDialogSync(const DialogSettings& settings,
std::vector<base::FilePath>* paths);
void ShowOpenDialog(const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise);
gin_helper::Promise<gin_helper::Dictionary> promise);
bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path);
void ShowSaveDialog(const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise);
gin_helper::Promise<gin_helper::Dictionary> promise);
} // namespace file_dialog

View file

@ -141,17 +141,17 @@ class FileChooserDialog {
}
void RunSaveAsynchronous(
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
save_promise_ =
std::make_unique<electron::util::Promise<gin_helper::Dictionary>>(
std::make_unique<gin_helper::Promise<gin_helper::Dictionary>>(
std::move(promise));
RunAsynchronous();
}
void RunOpenAsynchronous(
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
open_promise_ =
std::make_unique<electron::util::Promise<gin_helper::Dictionary>>(
std::make_unique<gin_helper::Promise<gin_helper::Dictionary>>(
std::move(promise));
RunAsynchronous();
}
@ -193,10 +193,8 @@ class FileChooserDialog {
GtkWidget* preview_;
Filters filters_;
std::unique_ptr<electron::util::Promise<gin_helper::Dictionary>>
save_promise_;
std::unique_ptr<electron::util::Promise<gin_helper::Dictionary>>
open_promise_;
std::unique_ptr<gin_helper::Promise<gin_helper::Dictionary>> save_promise_;
std::unique_ptr<gin_helper::Promise<gin_helper::Dictionary>> open_promise_;
// Callback for when we update the preview for the selection.
CHROMEG_CALLBACK_0(FileChooserDialog, void, OnUpdatePreview, GtkWidget*);
@ -216,7 +214,7 @@ void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) {
dict.Set("canceled", true);
dict.Set("filePath", base::FilePath());
}
save_promise_->ResolveWithGin(dict);
save_promise_->Resolve(dict);
} else if (open_promise_) {
gin_helper::Dictionary dict =
gin::Dictionary::CreateEmpty(open_promise_->isolate());
@ -227,7 +225,7 @@ void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) {
dict.Set("canceled", true);
dict.Set("filePaths", std::vector<base::FilePath>());
}
open_promise_->ResolveWithGin(dict);
open_promise_->Resolve(dict);
}
delete this;
}
@ -301,7 +299,7 @@ bool ShowOpenDialogSync(const DialogSettings& settings,
}
void ShowOpenDialog(const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
if (settings.properties & OPEN_DIALOG_OPEN_DIRECTORY)
action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
@ -324,7 +322,7 @@ bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) {
}
void ShowSaveDialog(const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
FileChooserDialog* save_dialog =
new FileChooserDialog(GTK_FILE_CHOOSER_ACTION_SAVE, settings);
save_dialog->RunSaveAsynchronous(std::move(promise));

View file

@ -298,11 +298,10 @@ bool ShowOpenDialogSync(const DialogSettings& settings,
return true;
}
void OpenDialogCompletion(
int chosen,
NSOpenPanel* dialog,
bool security_scoped_bookmarks,
electron::util::Promise<gin_helper::Dictionary> promise) {
void OpenDialogCompletion(int chosen,
NSOpenPanel* dialog,
bool security_scoped_bookmarks,
gin_helper::Promise<gin_helper::Dictionary> promise) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
if (chosen == NSFileHandlingPanelCancelButton) {
dict.Set("canceled", true);
@ -310,7 +309,7 @@ void OpenDialogCompletion(
#if defined(MAS_BUILD)
dict.Set("bookmarks", std::vector<std::string>());
#endif
promise.ResolveWithGin(dict);
promise.Resolve(dict);
} else {
std::vector<base::FilePath> paths;
dict.Set("canceled", false);
@ -326,12 +325,12 @@ void OpenDialogCompletion(
ReadDialogPaths(dialog, &paths);
dict.Set("filePaths", paths);
#endif
promise.ResolveWithGin(dict);
promise.Resolve(dict);
}
}
void ShowOpenDialog(const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
NSOpenPanel* dialog = [NSOpenPanel openPanel];
SetupDialog(dialog, settings);
@ -341,8 +340,7 @@ void ShowOpenDialog(const DialogSettings& settings,
// and pass it to the completion handler.
bool security_scoped_bookmarks = settings.security_scoped_bookmarks;
__block electron::util::Promise<gin_helper::Dictionary> p =
std::move(promise);
__block gin_helper::Promise<gin_helper::Dictionary> p = std::move(promise);
if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
settings.force_detached) {
@ -377,11 +375,10 @@ bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) {
return true;
}
void SaveDialogCompletion(
int chosen,
NSSavePanel* dialog,
bool security_scoped_bookmarks,
electron::util::Promise<gin_helper::Dictionary> promise) {
void SaveDialogCompletion(int chosen,
NSSavePanel* dialog,
bool security_scoped_bookmarks,
gin_helper::Promise<gin_helper::Dictionary> promise) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
if (chosen == NSFileHandlingPanelCancelButton) {
dict.Set("canceled", true);
@ -401,11 +398,11 @@ void SaveDialogCompletion(
}
#endif
}
promise.ResolveWithGin(dict);
promise.Resolve(dict);
}
void ShowSaveDialog(const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
NSSavePanel* dialog = [NSSavePanel savePanel];
SetupDialog(dialog, settings);
@ -416,8 +413,7 @@ void ShowSaveDialog(const DialogSettings& settings,
// and pass it to the completion handler.
bool security_scoped_bookmarks = settings.security_scoped_bookmarks;
__block electron::util::Promise<gin_helper::Dictionary> p =
std::move(promise);
__block gin_helper::Promise<gin_helper::Dictionary> p = std::move(promise);
if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
settings.force_detached) {

View file

@ -80,19 +80,19 @@ bool CreateDialogThread(RunState* run_state) {
return true;
}
void OnDialogOpened(electron::util::Promise<gin_helper::Dictionary> promise,
void OnDialogOpened(gin_helper::Promise<gin_helper::Dictionary> promise,
bool canceled,
std::vector<base::FilePath> paths) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("canceled", canceled);
dict.Set("filePaths", paths);
promise.ResolveWithGin(dict);
promise.Resolve(dict);
}
void RunOpenDialogInNewThread(
const RunState& run_state,
const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
std::vector<base::FilePath> paths;
bool result = ShowOpenDialogSync(settings, &paths);
run_state.ui_task_runner->PostTask(
@ -101,19 +101,19 @@ void RunOpenDialogInNewThread(
run_state.ui_task_runner->DeleteSoon(FROM_HERE, run_state.dialog_thread);
}
void OnSaveDialogDone(electron::util::Promise<gin_helper::Dictionary> promise,
void OnSaveDialogDone(gin_helper::Promise<gin_helper::Dictionary> promise,
bool canceled,
const base::FilePath path) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("canceled", canceled);
dict.Set("filePath", path);
promise.ResolveWithGin(dict);
promise.Resolve(dict);
}
void RunSaveDialogInNewThread(
const RunState& run_state,
const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
base::FilePath path;
bool result = ShowSaveDialogSync(settings, &path);
run_state.ui_task_runner->PostTask(
@ -275,13 +275,13 @@ bool ShowOpenDialogSync(const DialogSettings& settings,
}
void ShowOpenDialog(const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
RunState run_state;
if (!CreateDialogThread(&run_state)) {
dict.Set("canceled", true);
dict.Set("filePaths", std::vector<base::FilePath>());
promise.ResolveWithGin(dict);
promise.Resolve(dict);
} else {
run_state.dialog_thread->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&RunOpenDialogInNewThread, run_state,
@ -325,14 +325,14 @@ bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) {
}
void ShowSaveDialog(const DialogSettings& settings,
electron::util::Promise<gin_helper::Dictionary> promise) {
gin_helper::Promise<gin_helper::Dictionary> promise) {
RunState run_state;
if (!CreateDialogThread(&run_state)) {
gin_helper::Dictionary dict =
gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("canceled", true);
dict.Set("filePath", base::FilePath());
promise.ResolveWithGin(dict);
promise.Resolve(dict);
} else {
run_state.dialog_thread->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&RunSaveDialogInNewThread, run_state,

View file

@ -58,7 +58,7 @@ class FileSelectHelper : public base::RefCounted<FileSelectHelper>,
void ShowOpenDialog(const file_dialog::DialogSettings& settings) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
electron::util::Promise<gin_helper::Dictionary> promise(isolate);
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
auto callback = base::BindOnce(&FileSelectHelper::OnOpenDialogDone, this);
ignore_result(promise.Then(std::move(callback)));
@ -68,7 +68,7 @@ class FileSelectHelper : public base::RefCounted<FileSelectHelper>,
void ShowSaveDialog(const file_dialog::DialogSettings& settings) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
electron::util::Promise<gin_helper::Dictionary> promise(isolate);
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
auto callback = base::BindOnce(&FileSelectHelper::OnSaveDialogDone, this);
ignore_result(promise.Then(std::move(callback)));

View file

@ -9,9 +9,9 @@
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/platform_util.h"
#include "shell/common/promise_util.h"
#if defined(OS_WIN)
#include "base/win/scoped_com_initializer.h"
@ -44,7 +44,7 @@ struct Converter<base::win::ShortcutOperation> {
namespace {
void OnOpenExternalFinished(electron::util::Promise<void*> promise,
void OnOpenExternalFinished(gin_helper::Promise<void> promise,
const std::string& error) {
if (error.empty())
promise.Resolve();
@ -53,7 +53,7 @@ void OnOpenExternalFinished(electron::util::Promise<void*> promise,
}
v8::Local<v8::Promise> OpenExternal(const GURL& url, gin::Arguments* args) {
electron::util::Promise<void*> promise(args->isolate());
gin_helper::Promise<void> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
platform_util::OpenExternalOptions options;

View file

@ -25,9 +25,9 @@
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/locker.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/heap_snapshot.h"
#include "shell/common/node_includes.h"
#include "shell/common/promise_util.h"
#include "third_party/blink/renderer/platform/heap/process_heap.h" // nogncheck
namespace electron {
@ -231,7 +231,7 @@ v8::Local<v8::Value> ElectronBindings::GetSystemMemoryInfo(
// static
v8::Local<v8::Promise> ElectronBindings::GetProcessMemoryInfo(
v8::Isolate* isolate) {
util::Promise<gin_helper::Dictionary> promise(isolate);
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (gin_helper::Locker::IsBrowserProcess() && !Browser::Get()->is_ready()) {
@ -265,7 +265,7 @@ v8::Local<v8::Value> ElectronBindings::GetBlinkMemoryInfo(
// static
void ElectronBindings::DidReceiveMemoryDump(
v8::Global<v8::Context> context,
util::Promise<gin_helper::Dictionary> promise,
gin_helper::Promise<gin_helper::Dictionary> promise,
bool success,
std::unique_ptr<memory_instrumentation::GlobalMemoryDump> global_dump) {
v8::Isolate* isolate = promise.isolate();
@ -292,7 +292,7 @@ void ElectronBindings::DidReceiveMemoryDump(
#endif
dict.Set("private", osdump.private_footprint_kb);
dict.Set("shared", osdump.shared_footprint_kb);
promise.ResolveWithGin(dict);
promise.Resolve(dict);
resolved = true;
break;
}

View file

@ -13,7 +13,7 @@
#include "base/memory/scoped_refptr.h"
#include "base/process/process_metrics.h"
#include "base/strings/string16.h"
#include "shell/common/promise_util.h"
#include "shell/common/gin_helper/promise.h"
#include "uv.h" // NOLINT(build/include)
namespace gin_helper {
@ -70,7 +70,7 @@ class ElectronBindings {
static void DidReceiveMemoryDump(
v8::Global<v8::Context> context,
util::Promise<gin_helper::Dictionary> promise,
gin_helper::Promise<gin_helper::Dictionary> promise,
bool success,
std::unique_ptr<memory_instrumentation::GlobalMemoryDump> dump);

View file

@ -0,0 +1,100 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/common/gin_helper/promise.h"
namespace gin_helper {
PromiseBase::PromiseBase(v8::Isolate* isolate)
: PromiseBase(isolate,
v8::Promise::Resolver::New(isolate->GetCurrentContext())
.ToLocalChecked()) {}
PromiseBase::PromiseBase(v8::Isolate* isolate,
v8::Local<v8::Promise::Resolver> handle)
: isolate_(isolate),
context_(isolate, isolate->GetCurrentContext()),
resolver_(isolate, handle) {}
PromiseBase::PromiseBase(PromiseBase&&) = default;
PromiseBase::~PromiseBase() = default;
PromiseBase& PromiseBase::operator=(PromiseBase&&) = default;
v8::Maybe<bool> PromiseBase::Reject() {
gin_helper::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(GetContext());
return GetInner()->Reject(GetContext(), v8::Undefined(isolate()));
}
v8::Maybe<bool> PromiseBase::Reject(v8::Local<v8::Value> except) {
gin_helper::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(GetContext());
return GetInner()->Reject(GetContext(), except);
}
v8::Maybe<bool> PromiseBase::RejectWithErrorMessage(base::StringPiece message) {
gin_helper::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(GetContext());
v8::Local<v8::Value> error =
v8::Exception::Error(gin::StringToV8(isolate(), message));
return GetInner()->Reject(GetContext(), (error));
}
v8::Local<v8::Context> PromiseBase::GetContext() const {
return v8::Local<v8::Context>::New(isolate_, context_);
}
v8::Local<v8::Promise> PromiseBase::GetHandle() const {
return GetInner()->GetPromise();
}
v8::Local<v8::Promise::Resolver> PromiseBase::GetInner() const {
return resolver_.Get(isolate());
}
// static
void Promise<void>::ResolvePromise(Promise<void> promise) {
if (gin_helper::Locker::IsBrowserProcess() &&
!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce([](Promise<void> promise) { promise.Resolve(); },
std::move(promise)));
} else {
promise.Resolve();
}
}
// static
v8::Local<v8::Promise> Promise<void>::ResolvedPromise(v8::Isolate* isolate) {
Promise<void> resolved(isolate);
resolved.Resolve();
return resolved.GetHandle();
}
v8::Maybe<bool> Promise<void>::Resolve() {
gin_helper::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(GetContext());
return GetInner()->Resolve(GetContext(), v8::Undefined(isolate()));
}
} // namespace gin_helper

View file

@ -0,0 +1,176 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_GIN_HELPER_PROMISE_H_
#define SHELL_COMMON_GIN_HELPER_PROMISE_H_
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include "base/strings/string_piece.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "shell/common/gin_converters/std_converter.h"
#include "shell/common/gin_helper/locker.h"
namespace gin_helper {
// A wrapper around the v8::Promise.
//
// This is the non-template base class to share code between templates
// instances.
//
// This is a move-only type that should always be `std::move`d when passed to
// callbacks, and it should be destroyed on the same thread of creation.
class PromiseBase {
public:
explicit PromiseBase(v8::Isolate* isolate);
PromiseBase(v8::Isolate* isolate, v8::Local<v8::Promise::Resolver> handle);
~PromiseBase();
// Support moving.
PromiseBase(PromiseBase&&);
PromiseBase& operator=(PromiseBase&&);
// Helper for rejecting promise with error message.
//
// Note: The parameter type is PromiseBase&& so it can take the instances of
// Promise<T> type.
static void RejectPromise(PromiseBase&& promise, base::StringPiece errmsg) {
if (gin_helper::Locker::IsBrowserProcess() &&
!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(
// Note that this callback can not take StringPiece,
// as StringPiece only references string internally and
// will blow when a temporary string is passed.
[](PromiseBase&& promise, std::string str) {
promise.RejectWithErrorMessage(str);
},
std::move(promise), std::string(errmsg.data(), errmsg.size())));
} else {
promise.RejectWithErrorMessage(errmsg);
}
}
v8::Maybe<bool> Reject();
v8::Maybe<bool> Reject(v8::Local<v8::Value> except);
v8::Maybe<bool> RejectWithErrorMessage(base::StringPiece message);
v8::Local<v8::Context> GetContext() const;
v8::Local<v8::Promise> GetHandle() const;
v8::Isolate* isolate() const { return isolate_; }
protected:
v8::Local<v8::Promise::Resolver> GetInner() const;
private:
v8::Isolate* isolate_;
v8::Global<v8::Context> context_;
v8::Global<v8::Promise::Resolver> resolver_;
DISALLOW_COPY_AND_ASSIGN(PromiseBase);
};
// Template implementation that returns values.
template <typename RT>
class Promise : public PromiseBase {
public:
using PromiseBase::PromiseBase;
// Helper for resolving the promise with |result|.
static void ResolvePromise(Promise<RT> promise, RT result) {
if (gin_helper::Locker::IsBrowserProcess() &&
!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
base::PostTask(FROM_HERE, {content::BrowserThread::UI},
base::BindOnce([](Promise<RT> promise,
RT result) { promise.Resolve(result); },
std::move(promise), std::move(result)));
} else {
promise.Resolve(result);
}
}
// Returns an already-resolved promise.
static v8::Local<v8::Promise> ResolvedPromise(v8::Isolate* isolate,
RT result) {
Promise<RT> resolved(isolate);
resolved.Resolve(result);
return resolved.GetHandle();
}
// Promise resolution is a microtask
// We use the MicrotasksRunner to trigger the running of pending microtasks
v8::Maybe<bool> Resolve(const RT& value) {
gin_helper::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(GetContext());
return GetInner()->Resolve(GetContext(),
gin::ConvertToV8(isolate(), value));
}
template <typename... ResolveType>
v8::MaybeLocal<v8::Promise> Then(
base::OnceCallback<void(ResolveType...)> cb) {
static_assert(sizeof...(ResolveType) <= 1,
"A promise's 'Then' callback should only receive at most one "
"parameter");
static_assert(
std::is_same<RT, std::tuple_element_t<0, std::tuple<ResolveType...>>>(),
"A promises's 'Then' callback must handle the same type as the "
"promises resolve type");
gin_helper::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::Context::Scope context_scope(GetContext());
v8::Local<v8::Value> value = gin::ConvertToV8(isolate(), std::move(cb));
v8::Local<v8::Function> handler = v8::Local<v8::Function>::Cast(value);
return GetHandle()->Then(GetContext(), handler);
}
};
// Template implementation that returns nothing.
template <>
class Promise<void> : public PromiseBase {
public:
using PromiseBase::PromiseBase;
// Helper for resolving the empty promise.
static void ResolvePromise(Promise<void> promise);
// Returns an already-resolved promise.
static v8::Local<v8::Promise> ResolvedPromise(v8::Isolate* isolate);
v8::Maybe<bool> Resolve();
};
} // namespace gin_helper
namespace gin {
template <typename T>
struct Converter<gin_helper::Promise<T>> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const gin_helper::Promise<T>& val) {
return val.GetHandle();
}
// TODO(MarshallOfSound): Implement FromV8 to allow promise chaining
// in native land
// static bool FromV8(v8::Isolate* isolate,
// v8::Local<v8::Value> val,
// Promise* out);
};
} // namespace gin
#endif // SHELL_COMMON_GIN_HELPER_PROMISE_H_

View file

@ -1,23 +0,0 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/common/promise_util.h"
namespace mate {
template <typename T>
v8::Local<v8::Value> mate::Converter<electron::util::Promise<T>>::ToV8(
v8::Isolate*,
const electron::util::Promise<T>& val) {
return val.GetHandle();
}
template <>
v8::Local<v8::Value> mate::Converter<electron::util::Promise<void*>>::ToV8(
v8::Isolate*,
const electron::util::Promise<void*>& val) {
return val.GetHandle();
}
} // namespace mate

View file

@ -1,243 +0,0 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef SHELL_COMMON_PROMISE_UTIL_H_
#define SHELL_COMMON_PROMISE_UTIL_H_
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include "base/strings/string_piece.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "native_mate/converter.h"
#include "shell/common/gin_converters/std_converter.h"
namespace electron {
namespace util {
// A wrapper around the v8::Promise.
//
// This is a move-only type that should always be `std::move`d when passed to
// callbacks, and it should be destroyed on the same thread of creation.
template <typename RT>
class Promise {
public:
// Create a new promise.
explicit Promise(v8::Isolate* isolate)
: Promise(isolate,
v8::Promise::Resolver::New(isolate->GetCurrentContext())
.ToLocalChecked()) {}
// Wrap an existing v8 promise.
Promise(v8::Isolate* isolate, v8::Local<v8::Promise::Resolver> handle)
: isolate_(isolate),
context_(isolate, isolate->GetCurrentContext()),
resolver_(isolate, handle) {}
~Promise() = default;
// Support moving.
Promise(Promise&&) = default;
Promise& operator=(Promise&&) = default;
v8::Isolate* isolate() const { return isolate_; }
v8::Local<v8::Context> GetContext() {
return v8::Local<v8::Context>::New(isolate_, context_);
}
// helpers for promise resolution and rejection
static void ResolvePromise(Promise<RT> promise, RT result) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce([](Promise<RT> promise,
RT result) { promise.ResolveWithGin(result); },
std::move(promise), std::move(result)));
} else {
promise.ResolveWithGin(result);
}
}
static void ResolveEmptyPromise(Promise<RT> promise) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
base::PostTask(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce([](Promise<RT> promise) { promise.Resolve(); },
std::move(promise)));
} else {
promise.Resolve();
}
}
static void RejectPromise(Promise<RT> promise, base::StringPiece errmsg) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
base::PostTask(FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(
[](Promise<RT> promise, base::StringPiece err) {
promise.RejectWithErrorMessage(err);
},
std::move(promise), std::move(errmsg)));
} else {
promise.RejectWithErrorMessage(errmsg);
}
}
// Returns an already-resolved promise.
static v8::Local<v8::Promise> ResolvedPromise(v8::Isolate* isolate,
RT result) {
Promise<RT> resolved(isolate);
resolved.Resolve(result);
return resolved.GetHandle();
}
static v8::Local<v8::Promise> ResolvedPromise(v8::Isolate* isolate) {
Promise<void*> resolved(isolate);
resolved.Resolve();
return resolved.GetHandle();
}
v8::Local<v8::Promise> GetHandle() const { return GetInner()->GetPromise(); }
v8::Maybe<bool> Resolve() {
static_assert(std::is_same<void*, RT>(),
"Can only resolve void* promises with no value");
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate(), GetContext()));
return GetInner()->Resolve(GetContext(), v8::Undefined(isolate()));
}
v8::Maybe<bool> Reject() {
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate(), GetContext()));
return GetInner()->Reject(GetContext(), v8::Undefined(isolate()));
}
v8::Maybe<bool> Reject(v8::Local<v8::Value> exception) {
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate(), GetContext()));
return GetInner()->Reject(GetContext(), exception);
}
template <typename... ResolveType>
v8::MaybeLocal<v8::Promise> Then(
base::OnceCallback<void(ResolveType...)> cb) {
static_assert(sizeof...(ResolveType) <= 1,
"A promise's 'Then' callback should only receive at most one "
"parameter");
static_assert(
std::is_same<RT, std::tuple_element_t<0, std::tuple<ResolveType...>>>(),
"A promises's 'Then' callback must handle the same type as the "
"promises resolve type");
v8::HandleScope handle_scope(isolate());
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate(), GetContext()));
v8::Local<v8::Value> value = gin::ConvertToV8(isolate(), std::move(cb));
v8::Local<v8::Function> handler = v8::Local<v8::Function>::Cast(value);
return GetHandle()->Then(GetContext(), handler);
}
// Promise resolution is a microtask
// We use the MicrotasksRunner to trigger the running of pending microtasks
v8::Maybe<bool> Resolve(const RT& value) {
static_assert(!std::is_same<void*, RT>(),
"void* promises can not be resolved with a value");
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate(), GetContext()));
return GetInner()->Resolve(GetContext(),
mate::ConvertToV8(isolate(), value));
}
v8::Maybe<bool> ResolveWithGin(const RT& value) {
static_assert(!std::is_same<void*, RT>(),
"void* promises can not be resolved with a value");
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate(), GetContext()));
return GetInner()->Resolve(GetContext(),
gin::ConvertToV8(isolate(), value));
}
v8::Maybe<bool> RejectWithErrorMessage(base::StringPiece string) {
v8::HandleScope handle_scope(isolate());
v8::MicrotasksScope script_scope(isolate(),
v8::MicrotasksScope::kRunMicrotasks);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate(), GetContext()));
v8::Local<v8::Value> error =
v8::Exception::Error(gin::StringToV8(isolate(), string));
return GetInner()->Reject(GetContext(), (error));
}
private:
v8::Local<v8::Promise::Resolver> GetInner() const {
return resolver_.Get(isolate());
}
v8::Isolate* isolate_;
v8::Global<v8::Context> context_;
v8::Global<v8::Promise::Resolver> resolver_;
DISALLOW_COPY_AND_ASSIGN(Promise);
};
} // namespace util
} // namespace electron
namespace mate {
template <typename T>
struct Converter<electron::util::Promise<T>> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const electron::util::Promise<T>& val);
// TODO(MarshallOfSound): Implement FromV8 to allow promise chaining
// in native land
// static bool FromV8(v8::Isolate* isolate,
// v8::Local<v8::Value> val,
// Promise* out);
};
} // namespace mate
namespace gin {
template <typename T>
struct Converter<electron::util::Promise<T>> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const electron::util::Promise<T>& val) {
return mate::ConvertToV8(isolate, val);
}
};
} // namespace gin
#endif // SHELL_COMMON_PROMISE_UTIL_H_

View file

@ -18,8 +18,8 @@
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/promise_util.h"
#include "shell/renderer/api/context_bridge/render_frame_context_bridge_store.h"
#include "shell/renderer/atom_render_frame_observer.h"
#include "third_party/blink/public/web/web_local_frame.h"
@ -153,10 +153,10 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
v8::Context::Scope source_scope(source_context);
{
source_context->GetIsolate()->ThrowException(v8::Exception::TypeError(
mate::StringToV8(source_context->GetIsolate(),
"Electron contextBridge recursion depth exceeded. "
"Nested objects "
"deeper than 1000 are not supported.")));
gin::StringToV8(source_context->GetIsolate(),
"Electron contextBridge recursion depth exceeded. "
"Nested objects "
"deeper than 1000 are not supported.")));
return v8::MaybeLocal<v8::Value>();
}
}
@ -195,13 +195,13 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
v8::Context::Scope destination_scope(destination_context);
{
auto source_promise = v8::Local<v8::Promise>::Cast(value);
auto* proxied_promise = new util::Promise<v8::Local<v8::Value>>(
auto* proxied_promise = new gin_helper::Promise<v8::Local<v8::Value>>(
destination_context->GetIsolate());
v8::Local<v8::Promise> proxied_promise_handle =
proxied_promise->GetHandle();
auto then_cb = base::BindOnce(
[](util::Promise<v8::Local<v8::Value>>* proxied_promise,
[](gin_helper::Promise<v8::Local<v8::Value>>* proxied_promise,
v8::Isolate* isolate,
v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
@ -220,7 +220,7 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
destination_context),
store);
auto catch_cb = base::BindOnce(
[](util::Promise<v8::Local<v8::Value>>* proxied_promise,
[](gin_helper::Promise<v8::Local<v8::Value>>* proxied_promise,
v8::Isolate* isolate,
v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,

View file

@ -15,9 +15,9 @@
#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#include "shell/common/promise_util.h"
#include "third_party/blink/public/web/web_local_frame.h"
using blink::WebLocalFrame;
@ -90,14 +90,14 @@ class IPCRenderer : public gin::Wrappable<IPCRenderer> {
if (!gin::ConvertFromV8(isolate, arguments, &message)) {
return v8::Local<v8::Promise>();
}
electron::util::Promise<blink::CloneableMessage> p(isolate);
gin_helper::Promise<blink::CloneableMessage> p(isolate);
auto handle = p.GetHandle();
electron_browser_ptr_->get()->Invoke(
internal, channel, std::move(message),
base::BindOnce(
[](electron::util::Promise<blink::CloneableMessage> p,
blink::CloneableMessage result) { p.ResolveWithGin(result); },
[](gin_helper::Promise<blink::CloneableMessage> p,
blink::CloneableMessage result) { p.Resolve(result); },
std::move(p)));
return handle;

View file

@ -16,8 +16,8 @@
#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/promise_util.h"
#include "shell/renderer/api/atom_api_spell_check_client.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/common/web_cache/web_cache_resource_type_stats.h"
@ -111,7 +111,7 @@ class RenderFrameStatus final : public content::RenderFrameObserver {
class ScriptExecutionCallback : public blink::WebScriptExecutionCallback {
public:
explicit ScriptExecutionCallback(
electron::util::Promise<v8::Local<v8::Value>> promise)
gin_helper::Promise<v8::Local<v8::Value>> promise)
: promise_(std::move(promise)) {}
~ScriptExecutionCallback() override = default;
@ -135,7 +135,7 @@ class ScriptExecutionCallback : public blink::WebScriptExecutionCallback {
}
private:
electron::util::Promise<v8::Local<v8::Value>> promise_;
gin_helper::Promise<v8::Local<v8::Value>> promise_;
DISALLOW_COPY_AND_ASSIGN(ScriptExecutionCallback);
};
@ -378,7 +378,7 @@ v8::Local<v8::Promise> ExecuteJavaScript(gin_helper::Arguments* args,
v8::Local<v8::Value> window,
const base::string16& code) {
v8::Isolate* isolate = args->isolate();
util::Promise<v8::Local<v8::Value>> promise(isolate);
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
bool has_user_gesture = false;
@ -397,7 +397,7 @@ v8::Local<v8::Promise> ExecuteJavaScriptInIsolatedWorld(
int world_id,
const std::vector<gin_helper::Dictionary>& scripts) {
v8::Isolate* isolate = args->isolate();
util::Promise<v8::Local<v8::Value>> promise(isolate);
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
std::vector<blink::WebScriptSource> sources;