diff --git a/filenames.gni b/filenames.gni index 11937539229..11e4ab83737 100644 --- a/filenames.gni +++ b/filenames.gni @@ -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", diff --git a/shell/browser/api/atom_api_app.cc b/shell/browser/api/atom_api_app.cc index 3f1d786bf71..0cc6cfcf232 100644 --- a/shell/browser/api/atom_api_app.cc +++ b/shell/browser/api/atom_api_app.cc @@ -532,9 +532,10 @@ int ImportIntoCertStore(CertificateManagerModel* model, } #endif -void OnIconDataAvailable(util::Promise promise, gfx::Image icon) { +void OnIconDataAvailable(gin_helper::Promise 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 val, v8::Local App::GetFileIcon(const base::FilePath& path, gin_helper::Arguments* args) { - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); base::FilePath normalized_path = path.NormalizePathSeparators(); @@ -1193,7 +1194,7 @@ v8::Local 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 App::GetGPUFeatureStatus(v8::Isolate* isolate) { v8::Local App::GetGPUInfo(v8::Isolate* isolate, const std::string& info_type) { auto* const gpu_data_manager = content::GpuDataManagerImpl::GetInstance(); - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); if (info_type != "basic" && info_type != "complete") { promise.RejectWithErrorMessage( diff --git a/shell/browser/api/atom_api_app.h b/shell/browser/api/atom_api_app.h index 43bfe219ba8..2c96ec70a86 100644 --- a/shell/browser/api/atom_api_app.h +++ b/shell/browser/api/atom_api_app.h @@ -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" diff --git a/shell/browser/api/atom_api_content_tracing.cc b/shell/browser/api/atom_api_content_tracing.cc index 838c8d934fc..b03a6592928 100644 --- a/shell/browser/api/atom_api_content_tracing.cc +++ b/shell/browser/api/atom_api_content_tracing.cc @@ -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 CreateTemporaryFileOnIO() { return base::make_optional(std::move(temp_file_path)); } -void StopTracing(electron::util::Promise promise, +void StopTracing(gin_helper::Promise promise, base::Optional file_path) { if (file_path) { auto endpoint = TracingController::CreateFileEndpoint( - *file_path, - base::AdaptCallbackForRepeating(base::BindOnce( - &electron::util::Promise::ResolvePromise, - std::move(promise), *file_path))); + *file_path, base::AdaptCallbackForRepeating(base::BindOnce( + &gin_helper::Promise::ResolvePromise, + std::move(promise), *file_path))); TracingController::GetInstance()->StopTracing(endpoint); } else { promise.RejectWithErrorMessage( @@ -79,7 +78,7 @@ void StopTracing(electron::util::Promise promise, } v8::Local StopRecording(gin_helper::Arguments* args) { - electron::util::Promise promise(args->isolate()); + gin_helper::Promise promise(args->isolate()); v8::Local handle = promise.GetHandle(); base::FilePath path; @@ -99,12 +98,12 @@ v8::Local StopRecording(gin_helper::Arguments* args) { } v8::Local GetCategories(v8::Isolate* isolate) { - electron::util::Promise&> promise(isolate); + gin_helper::Promise&> promise(isolate); v8::Local handle = promise.GetHandle(); // Note: This method always succeeds. TracingController::GetInstance()->GetCategories(base::BindOnce( - electron::util::Promise&>::ResolvePromise, + gin_helper::Promise&>::ResolvePromise, std::move(promise))); return handle; @@ -113,35 +112,35 @@ v8::Local GetCategories(v8::Isolate* isolate) { v8::Local StartTracing( v8::Isolate* isolate, const base::trace_event::TraceConfig& trace_config) { - electron::util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); if (!TracingController::GetInstance()->StartTracing( trace_config, - base::BindOnce(electron::util::Promise::ResolveEmptyPromise, + base::BindOnce(gin_helper::Promise::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::ResolvedPromise(isolate); + return gin_helper::Promise::ResolvedPromise(isolate); } return handle; } void OnTraceBufferUsageAvailable( - electron::util::Promise promise, + gin_helper::Promise 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 GetTraceBufferUsage(v8::Isolate* isolate) { - electron::util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); // Note: This method always succeeds. diff --git a/shell/browser/api/atom_api_cookies.cc b/shell/browser/api/atom_api_cookies.cc index 491a1bf5e06..94897a707ea 100644 --- a/shell/browser/api/atom_api_cookies.cc +++ b/shell/browser/api/atom_api_cookies.cc @@ -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 promise, + gin_helper::Promise 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 promise, + gin_helper::Promise 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 Cookies::Get(const gin_helper::Dictionary& filter) { - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); auto* storage_partition = content::BrowserContext::GetDefaultStoragePartition( @@ -208,7 +208,7 @@ v8::Local Cookies::Get(const gin_helper::Dictionary& filter) { v8::Local Cookies::Remove(const GURL& url, const std::string& name) { - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); auto cookie_deletion_filter = network::mojom::CookieDeletionFilter::New(); @@ -222,8 +222,8 @@ v8::Local Cookies::Remove(const GURL& url, manager->DeleteCookies( std::move(cookie_deletion_filter), base::BindOnce( - [](util::Promise promise, uint32_t num_deleted) { - util::Promise::ResolveEmptyPromise(std::move(promise)); + [](gin_helper::Promise promise, uint32_t num_deleted) { + gin_helper::Promise::ResolvePromise(std::move(promise)); }, std::move(promise))); @@ -231,7 +231,7 @@ v8::Local Cookies::Remove(const GURL& url, } v8::Local Cookies::Set(base::DictionaryValue details) { - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); const std::string* url_string = details.FindStringKey("url"); @@ -296,7 +296,7 @@ v8::Local Cookies::Set(base::DictionaryValue details) { manager->SetCanonicalCookie( *canonical_cookie, url.scheme(), options, base::BindOnce( - [](util::Promise promise, + [](gin_helper::Promise promise, net::CanonicalCookie::CookieInclusionStatus status) { if (status.IsInclude()) { promise.Resolve(); @@ -310,7 +310,7 @@ v8::Local Cookies::Set(base::DictionaryValue details) { } v8::Local Cookies::FlushStore() { - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); auto* storage_partition = content::BrowserContext::GetDefaultStoragePartition( @@ -318,7 +318,7 @@ v8::Local Cookies::FlushStore() { auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); manager->FlushCookieStore(base::BindOnce( - util::Promise::ResolveEmptyPromise, std::move(promise))); + gin_helper::Promise::ResolvePromise, std::move(promise))); return handle; } diff --git a/shell/browser/api/atom_api_cookies.h b/shell/browser/api/atom_api_cookies.h index 7e508b602f2..9455d42ebfc 100644 --- a/shell/browser/api/atom_api_cookies.h +++ b/shell/browser/api/atom_api_cookies.h @@ -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; diff --git a/shell/browser/api/atom_api_data_pipe_holder.cc b/shell/browser/api/atom_api_data_pipe_holder.cc index b26783a7a0b..bcca4cf2130 100644 --- a/shell/browser/api/atom_api_data_pipe_holder.cc +++ b/shell/browser/api/atom_api_data_pipe_holder.cc @@ -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 g_weak_map; // Utility class to read from data pipe. class DataPipeReader { public: - DataPipeReader(util::Promise> promise, + DataPipeReader(gin_helper::Promise> promise, mojo::Remote data_pipe_getter) : promise_(std::move(promise)), data_pipe_getter_(std::move(data_pipe_getter)), @@ -116,7 +116,7 @@ class DataPipeReader { delete static_cast(self); } - util::Promise> promise_; + gin_helper::Promise> promise_; mojo::Remote data_pipe_getter_; mojo::ScopedDataPipeConsumerHandle data_pipe_; @@ -148,7 +148,7 @@ DataPipeHolder::DataPipeHolder(const network::DataElement& element) DataPipeHolder::~DataPipeHolder() = default; v8::Local DataPipeHolder::ReadAll(v8::Isolate* isolate) { - util::Promise> promise(isolate); + gin_helper::Promise> promise(isolate); v8::Local handle = promise.GetHandle(); if (!data_pipe_) { promise.RejectWithErrorMessage("Could not get blob data"); diff --git a/shell/browser/api/atom_api_debugger.cc b/shell/browser/api/atom_api_debugger.cc index bf0ffd4a627..755df614cb1 100644 --- a/shell/browser/api/atom_api_debugger.cc +++ b/shell/browser/api/atom_api_debugger.cc @@ -65,8 +65,7 @@ void Debugger::DispatchProtocolMessage(DevToolsAgentHost* agent_host, if (it == pending_requests_.end()) return; - electron::util::Promise promise = - std::move(it->second); + gin_helper::Promise 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 Debugger::SendCommand(gin_helper::Arguments* args) { - electron::util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); if (!agent_host_) { diff --git a/shell/browser/api/atom_api_debugger.h b/shell/browser/api/atom_api_debugger.h index 83f23388cad..3d41de3a640 100644 --- a/shell/browser/api/atom_api_debugger.h +++ b/shell/browser/api/atom_api_debugger.h @@ -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, private: using PendingRequestMap = - std::map>; + std::map>; void Attach(gin_helper::Arguments* args); bool IsAttached(); diff --git a/shell/browser/api/atom_api_dialog.cc b/shell/browser/api/atom_api_dialog.cc index 003cd1a7747..dcc7b7b9c50 100644 --- a/shell/browser/api/atom_api_dialog.cc +++ b/shell/browser/api/atom_api_dialog.cc @@ -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 promise, - int result, - bool checkbox_checked) { +void ResolvePromiseObject(gin_helper::Promise 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 ShowMessageBox( const electron::MessageBoxSettings& settings, gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); - electron::util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); electron::ShowMessageBox( @@ -61,7 +60,7 @@ void ShowOpenDialogSync(const file_dialog::DialogSettings& settings, v8::Local ShowOpenDialog( const file_dialog::DialogSettings& settings, gin::Arguments* args) { - electron::util::Promise promise(args->isolate()); + gin_helper::Promise promise(args->isolate()); v8::Local 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 ShowSaveDialog( const file_dialog::DialogSettings& settings, gin::Arguments* args) { - electron::util::Promise promise(args->isolate()); + gin_helper::Promise promise(args->isolate()); v8::Local handle = promise.GetHandle(); file_dialog::ShowSaveDialog(settings, std::move(promise)); diff --git a/shell/browser/api/atom_api_in_app_purchase.cc b/shell/browser/api/atom_api_in_app_purchase.cc index ccd5e5e3979..293eb549f0f 100644 --- a/shell/browser/api/atom_api_in_app_purchase.cc +++ b/shell/browser/api/atom_api_in_app_purchase.cc @@ -104,7 +104,7 @@ v8::Local InAppPurchase::PurchaseProduct( const std::string& product_id, gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); - electron::util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); int quantity = 1; @@ -112,7 +112,8 @@ v8::Local InAppPurchase::PurchaseProduct( in_app_purchase::PurchaseProduct( product_id, quantity, - base::BindOnce(util::Promise::ResolvePromise, std::move(promise))); + base::BindOnce(gin_helper::Promise::ResolvePromise, + std::move(promise))); return handle; } @@ -121,15 +122,14 @@ v8::Local InAppPurchase::GetProducts( const std::vector& productIDs, gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); - electron::util::Promise> promise( - isolate); + gin_helper::Promise> promise(isolate); v8::Local handle = promise.GetHandle(); in_app_purchase::GetProducts( productIDs, - base::BindOnce( - util::Promise>::ResolvePromise, - std::move(promise))); + base::BindOnce(gin_helper::Promise< + std::vector>::ResolvePromise, + std::move(promise))); return handle; } diff --git a/shell/browser/api/atom_api_in_app_purchase.h b/shell/browser/api/atom_api_in_app_purchase.h index dec89ebad3a..72f109e1341 100644 --- a/shell/browser/api/atom_api_in_app_purchase.h +++ b/shell/browser/api/atom_api_in_app_purchase.h @@ -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 { diff --git a/shell/browser/api/atom_api_net_log.cc b/shell/browser/api/atom_api_net_log.cc index fde65f90224..f073dcedf94 100644 --- a/shell/browser/api/atom_api_net_log.cc +++ b/shell/browser/api/atom_api_net_log.cc @@ -62,7 +62,8 @@ base::File OpenFileForWriting(base::FilePath path) { base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); } -void ResolvePromiseWithNetError(util::Promise promise, int32_t error) { +void ResolvePromiseWithNetError(gin_helper::Promise promise, + int32_t error) { if (error == net::OK) { promise.Resolve(); } else { @@ -117,7 +118,8 @@ v8::Local NetLog::StartLogging(base::FilePath log_path, return v8::Local(); } - pending_start_promise_ = base::make_optional>(isolate()); + pending_start_promise_ = + base::make_optional>(isolate()); v8::Local handle = pending_start_promise_->GetHandle(); auto command_line_string = @@ -187,7 +189,7 @@ bool NetLog::IsCurrentlyLogging() const { } v8::Local NetLog::StopLogging(gin_helper::Arguments* args) { - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); if (net_log_exporter_) { @@ -197,8 +199,8 @@ v8::Local NetLog::StopLogging(gin_helper::Arguments* args) { net_log_exporter_->Stop( base::Value(base::Value::Type::DICTIONARY), base::BindOnce( - [](network::mojom::NetLogExporterPtr, util::Promise promise, - int32_t error) { + [](network::mojom::NetLogExporterPtr, + gin_helper::Promise promise, int32_t error) { ResolvePromiseWithNetError(std::move(promise), error); }, std::move(net_log_exporter_), std::move(promise))); diff --git a/shell/browser/api/atom_api_net_log.h b/shell/browser/api/atom_api_net_log.h index aac501b708d..b70db5cc887 100644 --- a/shell/browser/api/atom_api_net_log.h +++ b/shell/browser/api/atom_api_net_log.h @@ -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 { network::mojom::NetLogExporterPtr net_log_exporter_; - base::Optional> pending_start_promise_; + base::Optional> pending_start_promise_; scoped_refptr file_task_runner_; diff --git a/shell/browser/api/atom_api_protocol.cc b/shell/browser/api/atom_api_protocol.cc index 18473ee93ed..83e807919ce 100644 --- a/shell/browser/api/atom_api_protocol.cc +++ b/shell/browser/api/atom_api_protocol.cc @@ -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 Protocol::IsProtocolHandled(const std::string& scheme, "protocol.isProtocolRegistered or protocol.isProtocolIntercepted " "instead.", "ProtocolDeprecateIsProtocolHandled"); - return util::Promise::ResolvedPromise( + return gin_helper::Promise::ResolvedPromise( isolate(), IsProtocolRegistered(scheme) || IsProtocolIntercepted(scheme) || // The |isProtocolHandled| should return true for builtin diff --git a/shell/browser/api/atom_api_session.cc b/shell/browser/api/atom_api_session.cc index 9300c6b9d1b..0a0c3388f3f 100644 --- a/shell/browser/api/atom_api_session.cc +++ b/shell/browser/api/atom_api_session.cc @@ -246,14 +246,14 @@ void Session::OnDownloadCreated(content::DownloadManager* manager, v8::Local Session::ResolveProxy(gin_helper::Arguments* args) { v8::Isolate* isolate = args->isolate(); - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); GURL url; args->GetNext(&url); browser_context_->GetResolveProxyHelper()->ResolveProxy( - url, base::BindOnce(util::Promise::ResolvePromise, + url, base::BindOnce(gin_helper::Promise::ResolvePromise, std::move(promise))); return handle; @@ -261,7 +261,7 @@ v8::Local Session::ResolveProxy(gin_helper::Arguments* args) { v8::Local Session::GetCacheSize() { auto* isolate = v8::Isolate::GetCurrent(); - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); auto handle = promise.GetHandle(); content::BrowserContext::GetDefaultStoragePartition(browser_context_.get()) @@ -269,7 +269,7 @@ v8::Local Session::GetCacheSize() { ->ComputeHttpCacheSize( base::Time(), base::Time::Max(), base::BindOnce( - [](util::Promise promise, bool is_upper_bound, + [](gin_helper::Promise promise, bool is_upper_bound, int64_t size_or_error) { if (size_or_error < 0) { promise.RejectWithErrorMessage( @@ -285,13 +285,13 @@ v8::Local Session::GetCacheSize() { v8::Local Session::ClearCache() { auto* isolate = v8::Isolate::GetCurrent(); - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); auto handle = promise.GetHandle(); content::BrowserContext::GetDefaultStoragePartition(browser_context_.get()) ->GetNetworkContext() ->ClearHttpCache(base::Time(), base::Time::Max(), nullptr, - base::BindOnce(util::Promise::ResolveEmptyPromise, + base::BindOnce(gin_helper::Promise::ResolvePromise, std::move(promise))); return handle; @@ -299,7 +299,7 @@ v8::Local Session::ClearCache() { v8::Local Session::ClearStorageData(gin_helper::Arguments* args) { v8::Isolate* isolate = args->isolate(); - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); ClearStorageDataOptions options; @@ -316,7 +316,7 @@ v8::Local 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::ResolveEmptyPromise, + base::BindOnce(gin_helper::Promise::ResolvePromise, std::move(promise))); return handle; } @@ -329,7 +329,7 @@ void Session::FlushStorageData() { v8::Local Session::SetProxy(gin_helper::Arguments* args) { v8::Isolate* isolate = args->isolate(); - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); gin_helper::Dictionary options; @@ -362,7 +362,7 @@ v8::Local Session::SetProxy(gin_helper::Arguments* args) { } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(util::Promise::ResolveEmptyPromise, + FROM_HERE, base::BindOnce(gin_helper::Promise::ResolvePromise, std::move(promise))); return handle; @@ -464,13 +464,13 @@ void Session::SetPermissionCheckHandler(v8::Local val, v8::Local Session::ClearHostResolverCache( gin_helper::Arguments* args) { v8::Isolate* isolate = args->isolate(); - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); content::BrowserContext::GetDefaultStoragePartition(browser_context_.get()) ->GetNetworkContext() ->ClearHostCache(nullptr, - base::BindOnce(util::Promise::ResolveEmptyPromise, + base::BindOnce(gin_helper::Promise::ResolvePromise, std::move(promise))); return handle; @@ -478,14 +478,14 @@ v8::Local Session::ClearHostResolverCache( v8::Local Session::ClearAuthCache() { auto* isolate = v8::Isolate::GetCurrent(); - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); content::BrowserContext::GetDefaultStoragePartition(browser_context_.get()) ->GetNetworkContext() ->ClearHttpAuthCache( base::Time(), - base::BindOnce(util::Promise::ResolveEmptyPromise, + base::BindOnce(gin_helper::Promise::ResolvePromise, std::move(promise))); return handle; @@ -515,7 +515,7 @@ v8::Local Session::GetBlobData(v8::Isolate* isolate, const std::string& uuid) { gin::Handle holder = DataPipeHolder::From(isolate, uuid); if (holder.IsEmpty()) { - util::Promise> promise(isolate); + gin_helper::Promise> promise(isolate); promise.RejectWithErrorMessage("Could not get blob data handle"); return promise.GetHandle(); } diff --git a/shell/browser/api/atom_api_session.h b/shell/browser/api/atom_api_session.h index 5ac404af3e6..a7e63e4757c 100644 --- a/shell/browser/api/atom_api_session.h +++ b/shell/browser/api/atom_api_session.h @@ -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; diff --git a/shell/browser/api/atom_api_system_preferences.h b/shell/browser/api/atom_api_system_preferences.h index f37601c26af..5b24ba7d64c 100644 --- a/shell/browser/api/atom_api_system_preferences.h +++ b/shell/browser/api/atom_api_system_preferences.h @@ -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" diff --git a/shell/browser/api/atom_api_system_preferences_mac.mm b/shell/browser/api/atom_api_system_preferences_mac.mm index 981ee4464ab..b1681a871f5 100644 --- a/shell/browser/api/atom_api_system_preferences_mac.mm +++ b/shell/browser/api/atom_api_system_preferences_mac.mm @@ -444,7 +444,7 @@ bool SystemPreferences::CanPromptTouchID() { v8::Local SystemPreferences::PromptTouchID( v8::Isolate* isolate, const std::string& reason) { - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); if (@available(macOS 10.12.2, *)) { @@ -461,7 +461,7 @@ v8::Local SystemPreferences::PromptTouchID( scoped_refptr runner = base::SequencedTaskRunnerHandle::Get(); - __block util::Promise p = std::move(promise); + __block gin_helper::Promise p = std::move(promise); [context evaluateAccessControl:access_control operation:LAAccessControlOperationUseKeySign @@ -473,13 +473,13 @@ v8::Local SystemPreferences::PromptTouchID( runner->PostTask( FROM_HERE, base::BindOnce( - util::Promise::RejectPromise, + gin_helper::Promise::RejectPromise, std::move(p), std::move(err_msg))); } else { runner->PostTask( FROM_HERE, base::BindOnce( - util::Promise::ResolveEmptyPromise, + gin_helper::Promise::ResolvePromise, std::move(p))); } }]; @@ -606,12 +606,12 @@ std::string SystemPreferences::GetMediaAccessStatus( v8::Local SystemPreferences::AskForMediaAccess( v8::Isolate* isolate, const std::string& media_type) { - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); if (auto type = ParseMediaType(media_type)) { if (@available(macOS 10.14, *)) { - __block util::Promise p = std::move(promise); + __block gin_helper::Promise p = std::move(promise); [AVCaptureDevice requestAccessForMediaType:type completionHandler:^(BOOL granted) { dispatch_async(dispatch_get_main_queue(), ^{ diff --git a/shell/browser/api/atom_api_web_contents.cc b/shell/browser/api/atom_api_web_contents.cc index 2bf6b11934a..b4240e2f88c 100644 --- a/shell/browser/api/atom_api_web_contents.cc +++ b/shell/browser/api/atom_api_web_contents.cc @@ -320,10 +320,10 @@ namespace api { namespace { // Called when CapturePage is done. -void OnCapturePageDone(util::Promise promise, +void OnCapturePageDone(gin_helper::Promise 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 GetCursorBlinkInterval() { @@ -1494,7 +1494,7 @@ std::string WebContents::GetUserAgent() { v8::Local WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); auto* handler = new SavePageHandler(web_contents(), std::move(promise)); @@ -1864,7 +1864,7 @@ std::vector WebContents::GetPrinterList() { } v8::Local WebContents::PrintToPDF(base::DictionaryValue settings) { - util::Promise> promise(isolate()); + gin_helper::Promise> promise(isolate()); v8::Local 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 WebContents::CapturePage(gin_helper::Arguments* args) { gfx::Rect rect; - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); // get rect arguments if they exist @@ -2175,7 +2175,7 @@ v8::Local 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 WebContents::TakeHeapSnapshot( const base::FilePath& file_path) { - util::Promise promise(isolate()); + gin_helper::Promise promise(isolate()); v8::Local handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; @@ -2462,7 +2462,7 @@ v8::Local WebContents::TakeHeapSnapshot( mojo::WrapPlatformFile(file.TakePlatformFile()), base::BindOnce( [](mojo::AssociatedRemote* ep, - util::Promise promise, bool success) { + gin_helper::Promise promise, bool success) { if (success) { promise.Resolve(); } else { diff --git a/shell/browser/api/gpuinfo_manager.cc b/shell/browser/api/gpuinfo_manager.cc index 177275943d7..94222d41571 100644 --- a/shell/browser/api/gpuinfo_manager.cc +++ b/shell/browser/api/gpuinfo_manager.cc @@ -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 promise) { + gin_helper::Promise promise) { complete_info_promise_set_.emplace_back(std::move(promise)); if (NeedsCompleteGpuInfoCollection()) { @@ -75,7 +75,7 @@ void GPUInfoManager::CompleteInfoFetcher( } void GPUInfoManager::FetchCompleteInfo( - util::Promise promise) { + gin_helper::Promise 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 promise) { + gin_helper::Promise promise) { gpu::GPUInfo gpu_info; CollectBasicGraphicsInfo(&gpu_info); - promise.ResolveWithGin(*EnumerateGPUInfo(gpu_info)); + promise.Resolve(*EnumerateGPUInfo(gpu_info)); } std::unique_ptr GPUInfoManager::EnumerateGPUInfo( diff --git a/shell/browser/api/gpuinfo_manager.h b/shell/browser/api/gpuinfo_manager.h index f013b19df68..21b4ce6972a 100644 --- a/shell/browser/api/gpuinfo_manager.h +++ b/shell/browser/api/gpuinfo_manager.h @@ -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 promise); - void FetchBasicInfo(util::Promise promise); + void FetchCompleteInfo(gin_helper::Promise promise); + void FetchBasicInfo(gin_helper::Promise 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 promise); + void CompleteInfoFetcher(gin_helper::Promise promise); void ProcessCompleteInfo(); // This set maintains all the promises that should be fulfilled // once we have the complete information data - std::vector> complete_info_promise_set_; + std::vector> + complete_info_promise_set_; content::GpuDataManager* gpu_data_manager_; DISALLOW_COPY_AND_ASSIGN(GPUInfoManager); diff --git a/shell/browser/api/save_page_handler.cc b/shell/browser/api/save_page_handler.cc index 72239f5fee6..b41e8cc6a5f 100644 --- a/shell/browser/api/save_page_handler.cc +++ b/shell/browser/api/save_page_handler.cc @@ -17,7 +17,7 @@ namespace electron { namespace api { SavePageHandler::SavePageHandler(content::WebContents* web_contents, - util::Promise promise) + gin_helper::Promise promise) : web_contents_(web_contents), promise_(std::move(promise)) {} SavePageHandler::~SavePageHandler() = default; diff --git a/shell/browser/api/save_page_handler.h b/shell/browser/api/save_page_handler.h index f0e685f7718..f556d74e8ea 100644 --- a/shell/browser/api/save_page_handler.h +++ b/shell/browser/api/save_page_handler.h @@ -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 promise); + gin_helper::Promise 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 promise_; + gin_helper::Promise promise_; }; } // namespace api diff --git a/shell/browser/atom_download_manager_delegate.cc b/shell/browser/atom_download_manager_delegate.cc index 1ca768e03a2..9f853f9bb51 100644 --- a/shell/browser/atom_download_manager_delegate.cc +++ b/shell/browser/atom_download_manager_delegate.cc @@ -124,7 +124,7 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated( settings.force_detached = offscreen; v8::Isolate* isolate = v8::Isolate::GetCurrent(); - electron::util::Promise dialog_promise(isolate); + gin_helper::Promise dialog_promise(isolate); auto dialog_callback = base::BindOnce(&AtomDownloadManagerDelegate::OnDownloadSaveDialogDone, base::Unretained(this), download_id, callback); diff --git a/shell/browser/browser.cc b/shell/browser/browser.cc index ea2297a2002..e3b02587d45 100644 --- a/shell/browser/browser.cc +++ b/shell/browser/browser.cc @@ -168,7 +168,7 @@ void Browser::DidFinishLaunching(base::DictionaryValue launch_info) { v8::Local Browser::WhenReady(v8::Isolate* isolate) { if (!ready_promise_) { - ready_promise_ = std::make_unique>(isolate); + ready_promise_ = std::make_unique>(isolate); if (is_ready()) { ready_promise_->Resolve(); } diff --git a/shell/browser/browser.h b/shell/browser/browser.h index 3403d016096..665505942a5 100644 --- a/shell/browser/browser.h +++ b/shell/browser/browser.h @@ -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 @@ -304,7 +304,7 @@ class Browser : public WindowListObserver { int badge_count_ = 0; - std::unique_ptr> ready_promise_; + std::unique_ptr> ready_promise_; #if defined(OS_LINUX) || defined(OS_WIN) base::Value about_panel_options_; diff --git a/shell/browser/browser_mac.mm b/shell/browser/browser_mac.mm index 67370aa107d..29727e94f07 100644 --- a/shell/browser/browser_mac.mm +++ b/shell/browser/browser_mac.mm @@ -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 Browser::DockShow(v8::Isolate* isolate) { - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); BOOL active = [[NSRunningApplication currentApplication] isActive]; @@ -328,7 +328,7 @@ v8::Local Browser::DockShow(v8::Isolate* isolate) { [app activateWithOptions:NSApplicationActivateIgnoringOtherApps]; break; } - __block util::Promise p = std::move(promise); + __block gin_helper::Promise 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); diff --git a/shell/browser/printing/print_preview_message_handler.cc b/shell/browser/printing/print_preview_message_handler.cc index fa3c0e34d5d..1b285a4e93b 100644 --- a/shell/browser/printing/print_preview_message_handler.cc +++ b/shell/browser/printing/print_preview_message_handler.cc @@ -144,7 +144,7 @@ void PrintPreviewMessageHandler::OnPrintPreviewCancelled( void PrintPreviewMessageHandler::PrintToPDF( base::DictionaryValue options, - electron::util::Promise> promise) { + gin_helper::Promise> 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> PrintPreviewMessageHandler::GetPromise( - int request_id) { +gin_helper::Promise> +PrintPreviewMessageHandler::GetPromise(int request_id) { auto it = promise_map_.find(request_id); DCHECK(it != promise_map_.end()); - util::Promise> promise = std::move(it->second); + gin_helper::Promise> promise = std::move(it->second); promise_map_.erase(it); return promise; @@ -172,7 +172,7 @@ void PrintPreviewMessageHandler::ResolvePromise( scoped_refptr data_bytes) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - util::Promise> promise = GetPromise(request_id); + gin_helper::Promise> 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> promise = GetPromise(request_id); + gin_helper::Promise> promise = GetPromise(request_id); promise.RejectWithErrorMessage("Failed to generate PDF"); } diff --git a/shell/browser/printing/print_preview_message_handler.h b/shell/browser/printing/print_preview_message_handler.h index cf5281d8322..e5c156b79dc 100644 --- a/shell/browser/printing/print_preview_message_handler.h +++ b/shell/browser/printing/print_preview_message_handler.h @@ -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> promise); + gin_helper::Promise> promise); protected: // content::WebContentsObserver implementation. @@ -56,14 +56,13 @@ class PrintPreviewMessageHandler void OnPrintPreviewCancelled(int document_cookie, const PrintHostMsg_PreviewIds& ids); - util::Promise> GetPromise(int request_id); + gin_helper::Promise> GetPromise(int request_id); void ResolvePromise(int request_id, scoped_refptr data_bytes); void RejectPromise(int request_id); - using PromiseMap = - std::map>>; + using PromiseMap = std::map>>; PromiseMap promise_map_; base::WeakPtrFactory weak_ptr_factory_; diff --git a/shell/browser/ui/certificate_trust.h b/shell/browser/ui/certificate_trust.h index e032638ab56..cda586908d2 100644 --- a/shell/browser/ui/certificate_trust.h +++ b/shell/browser/ui/certificate_trust.h @@ -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; diff --git a/shell/browser/ui/certificate_trust_mac.mm b/shell/browser/ui/certificate_trust_mac.mm index 890a2d410de..038c9e750af 100644 --- a/shell/browser/ui/certificate_trust_mac.mm +++ b/shell/browser/ui/certificate_trust_mac.mm @@ -19,7 +19,7 @@ @interface TrustDelegate : NSObject { @private - std::unique_ptr> promise_; + std::unique_ptr> promise_; SFCertificateTrustPanel* panel_; scoped_refptr cert_; SecTrustRef trust_; @@ -27,7 +27,7 @@ SecPolicyRef sec_policy_; } -- (id)initWithPromise:(electron::util::Promise)promise +- (id)initWithPromise:(gin_helper::Promise)promise panel:(SFCertificateTrustPanel*)panel cert:(const scoped_refptr&)cert trust:(SecTrustRef)trust @@ -51,14 +51,14 @@ [super dealloc]; } -- (id)initWithPromise:(electron::util::Promise)promise +- (id)initWithPromise:(gin_helper::Promise)promise panel:(SFCertificateTrustPanel*)panel cert:(const scoped_refptr&)cert trust:(SecTrustRef)trust certChain:(CFArrayRef)certChain secPolicy:(SecPolicyRef)secPolicy { if ((self = [super init])) { - promise_.reset(new electron::util::Promise(std::move(promise))); + promise_.reset(new gin_helper::Promise(std::move(promise))); panel_ = panel; cert_ = cert; trust_ = trust; @@ -90,7 +90,7 @@ v8::Local ShowCertificateTrust( const scoped_refptr& cert, const std::string& message) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); - electron::util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); auto* sec_policy = SecPolicyCreateBasicX509(); diff --git a/shell/browser/ui/certificate_trust_win.cc b/shell/browser/ui/certificate_trust_win.cc index acd110b87c1..d6ba23fc159 100644 --- a/shell/browser/ui/certificate_trust_win.cc +++ b/shell/browser/ui/certificate_trust_win.cc @@ -61,7 +61,7 @@ v8::Local ShowCertificateTrust( const scoped_refptr& cert, const std::string& message) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); - electron::util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); PCCERT_CHAIN_CONTEXT chain_context; diff --git a/shell/browser/ui/file_dialog.h b/shell/browser/ui/file_dialog.h index ab9c44e8800..239fcbc1242 100644 --- a/shell/browser/ui/file_dialog.h +++ b/shell/browser/ui/file_dialog.h @@ -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* paths); void ShowOpenDialog(const DialogSettings& settings, - electron::util::Promise promise); + gin_helper::Promise promise); bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path); void ShowSaveDialog(const DialogSettings& settings, - electron::util::Promise promise); + gin_helper::Promise promise); } // namespace file_dialog diff --git a/shell/browser/ui/file_dialog_gtk.cc b/shell/browser/ui/file_dialog_gtk.cc index d7991a2a80d..fb7ef215f82 100644 --- a/shell/browser/ui/file_dialog_gtk.cc +++ b/shell/browser/ui/file_dialog_gtk.cc @@ -141,17 +141,17 @@ class FileChooserDialog { } void RunSaveAsynchronous( - electron::util::Promise promise) { + gin_helper::Promise promise) { save_promise_ = - std::make_unique>( + std::make_unique>( std::move(promise)); RunAsynchronous(); } void RunOpenAsynchronous( - electron::util::Promise promise) { + gin_helper::Promise promise) { open_promise_ = - std::make_unique>( + std::make_unique>( std::move(promise)); RunAsynchronous(); } @@ -193,10 +193,8 @@ class FileChooserDialog { GtkWidget* preview_; Filters filters_; - std::unique_ptr> - save_promise_; - std::unique_ptr> - open_promise_; + std::unique_ptr> save_promise_; + std::unique_ptr> 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()); } - 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 promise) { + gin_helper::Promise 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 promise) { + gin_helper::Promise promise) { FileChooserDialog* save_dialog = new FileChooserDialog(GTK_FILE_CHOOSER_ACTION_SAVE, settings); save_dialog->RunSaveAsynchronous(std::move(promise)); diff --git a/shell/browser/ui/file_dialog_mac.mm b/shell/browser/ui/file_dialog_mac.mm index f2ac88038bf..664bb220439 100644 --- a/shell/browser/ui/file_dialog_mac.mm +++ b/shell/browser/ui/file_dialog_mac.mm @@ -298,11 +298,10 @@ bool ShowOpenDialogSync(const DialogSettings& settings, return true; } -void OpenDialogCompletion( - int chosen, - NSOpenPanel* dialog, - bool security_scoped_bookmarks, - electron::util::Promise promise) { +void OpenDialogCompletion(int chosen, + NSOpenPanel* dialog, + bool security_scoped_bookmarks, + gin_helper::Promise 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()); #endif - promise.ResolveWithGin(dict); + promise.Resolve(dict); } else { std::vector 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 promise) { + gin_helper::Promise 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 p = - std::move(promise); + __block gin_helper::Promise 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 promise) { +void SaveDialogCompletion(int chosen, + NSSavePanel* dialog, + bool security_scoped_bookmarks, + gin_helper::Promise 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 promise) { + gin_helper::Promise 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 p = - std::move(promise); + __block gin_helper::Promise p = std::move(promise); if (!settings.parent_window || !settings.parent_window->GetNativeWindow() || settings.force_detached) { diff --git a/shell/browser/ui/file_dialog_win.cc b/shell/browser/ui/file_dialog_win.cc index 36428c97ba4..9fcda1a0072 100644 --- a/shell/browser/ui/file_dialog_win.cc +++ b/shell/browser/ui/file_dialog_win.cc @@ -80,19 +80,19 @@ bool CreateDialogThread(RunState* run_state) { return true; } -void OnDialogOpened(electron::util::Promise promise, +void OnDialogOpened(gin_helper::Promise promise, bool canceled, std::vector 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 promise) { + gin_helper::Promise promise) { std::vector 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 promise, +void OnSaveDialogDone(gin_helper::Promise 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 promise) { + gin_helper::Promise 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 promise) { + gin_helper::Promise 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()); - 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 promise) { + gin_helper::Promise 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, diff --git a/shell/browser/web_dialog_helper.cc b/shell/browser/web_dialog_helper.cc index 8129016b89f..cd06e0712d0 100644 --- a/shell/browser/web_dialog_helper.cc +++ b/shell/browser/web_dialog_helper.cc @@ -58,7 +58,7 @@ class FileSelectHelper : public base::RefCounted, void ShowOpenDialog(const file_dialog::DialogSettings& settings) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); - electron::util::Promise promise(isolate); + gin_helper::Promise 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, void ShowSaveDialog(const file_dialog::DialogSettings& settings) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); - electron::util::Promise promise(isolate); + gin_helper::Promise promise(isolate); auto callback = base::BindOnce(&FileSelectHelper::OnSaveDialogDone, this); ignore_result(promise.Then(std::move(callback))); diff --git a/shell/common/api/atom_api_shell.cc b/shell/common/api/atom_api_shell.cc index dd07ede80ac..2ce7d370e72 100644 --- a/shell/common/api/atom_api_shell.cc +++ b/shell/common/api/atom_api_shell.cc @@ -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 { namespace { -void OnOpenExternalFinished(electron::util::Promise promise, +void OnOpenExternalFinished(gin_helper::Promise promise, const std::string& error) { if (error.empty()) promise.Resolve(); @@ -53,7 +53,7 @@ void OnOpenExternalFinished(electron::util::Promise promise, } v8::Local OpenExternal(const GURL& url, gin::Arguments* args) { - electron::util::Promise promise(args->isolate()); + gin_helper::Promise promise(args->isolate()); v8::Local handle = promise.GetHandle(); platform_util::OpenExternalOptions options; diff --git a/shell/common/api/electron_bindings.cc b/shell/common/api/electron_bindings.cc index ba278eaa889..0b23950f915 100644 --- a/shell/common/api/electron_bindings.cc +++ b/shell/common/api/electron_bindings.cc @@ -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 ElectronBindings::GetSystemMemoryInfo( // static v8::Local ElectronBindings::GetProcessMemoryInfo( v8::Isolate* isolate) { - util::Promise promise(isolate); + gin_helper::Promise promise(isolate); v8::Local handle = promise.GetHandle(); if (gin_helper::Locker::IsBrowserProcess() && !Browser::Get()->is_ready()) { @@ -265,7 +265,7 @@ v8::Local ElectronBindings::GetBlinkMemoryInfo( // static void ElectronBindings::DidReceiveMemoryDump( v8::Global context, - util::Promise promise, + gin_helper::Promise promise, bool success, std::unique_ptr 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; } diff --git a/shell/common/api/electron_bindings.h b/shell/common/api/electron_bindings.h index 4547ef14b7d..51ff4da195e 100644 --- a/shell/common/api/electron_bindings.h +++ b/shell/common/api/electron_bindings.h @@ -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 context, - util::Promise promise, + gin_helper::Promise promise, bool success, std::unique_ptr dump); diff --git a/shell/common/gin_helper/promise.cc b/shell/common/gin_helper/promise.cc new file mode 100644 index 00000000000..32737c18ab2 --- /dev/null +++ b/shell/common/gin_helper/promise.cc @@ -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 handle) + : isolate_(isolate), + context_(isolate, isolate->GetCurrentContext()), + resolver_(isolate, handle) {} + +PromiseBase::PromiseBase(PromiseBase&&) = default; + +PromiseBase::~PromiseBase() = default; + +PromiseBase& PromiseBase::operator=(PromiseBase&&) = default; + +v8::Maybe 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 PromiseBase::Reject(v8::Local 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 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 error = + v8::Exception::Error(gin::StringToV8(isolate(), message)); + return GetInner()->Reject(GetContext(), (error)); +} + +v8::Local PromiseBase::GetContext() const { + return v8::Local::New(isolate_, context_); +} + +v8::Local PromiseBase::GetHandle() const { + return GetInner()->GetPromise(); +} + +v8::Local PromiseBase::GetInner() const { + return resolver_.Get(isolate()); +} + +// static +void Promise::ResolvePromise(Promise promise) { + if (gin_helper::Locker::IsBrowserProcess() && + !content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { + base::PostTask( + FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce([](Promise promise) { promise.Resolve(); }, + std::move(promise))); + } else { + promise.Resolve(); + } +} + +// static +v8::Local Promise::ResolvedPromise(v8::Isolate* isolate) { + Promise resolved(isolate); + resolved.Resolve(); + return resolved.GetHandle(); +} + +v8::Maybe Promise::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 diff --git a/shell/common/gin_helper/promise.h b/shell/common/gin_helper/promise.h new file mode 100644 index 00000000000..813eef4665b --- /dev/null +++ b/shell/common/gin_helper/promise.h @@ -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 +#include +#include +#include + +#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 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 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 Reject(); + v8::Maybe Reject(v8::Local except); + v8::Maybe RejectWithErrorMessage(base::StringPiece message); + + v8::Local GetContext() const; + v8::Local GetHandle() const; + + v8::Isolate* isolate() const { return isolate_; } + + protected: + v8::Local GetInner() const; + + private: + v8::Isolate* isolate_; + v8::Global context_; + v8::Global resolver_; + + DISALLOW_COPY_AND_ASSIGN(PromiseBase); +}; + +// Template implementation that returns values. +template +class Promise : public PromiseBase { + public: + using PromiseBase::PromiseBase; + + // Helper for resolving the promise with |result|. + static void ResolvePromise(Promise promise, RT result) { + if (gin_helper::Locker::IsBrowserProcess() && + !content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce([](Promise promise, + RT result) { promise.Resolve(result); }, + std::move(promise), std::move(result))); + } else { + promise.Resolve(result); + } + } + + // Returns an already-resolved promise. + static v8::Local ResolvedPromise(v8::Isolate* isolate, + RT result) { + Promise 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 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 + v8::MaybeLocal Then( + base::OnceCallback cb) { + static_assert(sizeof...(ResolveType) <= 1, + "A promise's 'Then' callback should only receive at most one " + "parameter"); + static_assert( + std::is_same>>(), + "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 value = gin::ConvertToV8(isolate(), std::move(cb)); + v8::Local handler = v8::Local::Cast(value); + + return GetHandle()->Then(GetContext(), handler); + } +}; + +// Template implementation that returns nothing. +template <> +class Promise : public PromiseBase { + public: + using PromiseBase::PromiseBase; + + // Helper for resolving the empty promise. + static void ResolvePromise(Promise promise); + + // Returns an already-resolved promise. + static v8::Local ResolvedPromise(v8::Isolate* isolate); + + v8::Maybe Resolve(); +}; + +} // namespace gin_helper + +namespace gin { + +template +struct Converter> { + static v8::Local ToV8(v8::Isolate* isolate, + const gin_helper::Promise& val) { + return val.GetHandle(); + } + // TODO(MarshallOfSound): Implement FromV8 to allow promise chaining + // in native land + // static bool FromV8(v8::Isolate* isolate, + // v8::Local val, + // Promise* out); +}; + +} // namespace gin + +#endif // SHELL_COMMON_GIN_HELPER_PROMISE_H_ diff --git a/shell/common/promise_util.cc b/shell/common/promise_util.cc deleted file mode 100644 index 38d32c48853..00000000000 --- a/shell/common/promise_util.cc +++ /dev/null @@ -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 -v8::Local mate::Converter>::ToV8( - v8::Isolate*, - const electron::util::Promise& val) { - return val.GetHandle(); -} - -template <> -v8::Local mate::Converter>::ToV8( - v8::Isolate*, - const electron::util::Promise& val) { - return val.GetHandle(); -} - -} // namespace mate diff --git a/shell/common/promise_util.h b/shell/common/promise_util.h deleted file mode 100644 index 769b292f758..00000000000 --- a/shell/common/promise_util.h +++ /dev/null @@ -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 -#include -#include -#include - -#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 -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 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 GetContext() { - return v8::Local::New(isolate_, context_); - } - - // helpers for promise resolution and rejection - - static void ResolvePromise(Promise promise, RT result) { - if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTask( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce([](Promise promise, - RT result) { promise.ResolveWithGin(result); }, - std::move(promise), std::move(result))); - } else { - promise.ResolveWithGin(result); - } - } - - static void ResolveEmptyPromise(Promise promise) { - if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTask( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce([](Promise promise) { promise.Resolve(); }, - std::move(promise))); - } else { - promise.Resolve(); - } - } - - static void RejectPromise(Promise promise, base::StringPiece errmsg) { - if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTask(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce( - [](Promise 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 ResolvedPromise(v8::Isolate* isolate, - RT result) { - Promise resolved(isolate); - resolved.Resolve(result); - return resolved.GetHandle(); - } - - static v8::Local ResolvedPromise(v8::Isolate* isolate) { - Promise resolved(isolate); - resolved.Resolve(); - return resolved.GetHandle(); - } - - v8::Local GetHandle() const { return GetInner()->GetPromise(); } - - v8::Maybe Resolve() { - static_assert(std::is_same(), - "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::New(isolate(), GetContext())); - - return GetInner()->Resolve(GetContext(), v8::Undefined(isolate())); - } - - v8::Maybe Reject() { - v8::HandleScope handle_scope(isolate()); - v8::MicrotasksScope script_scope(isolate(), - v8::MicrotasksScope::kRunMicrotasks); - v8::Context::Scope context_scope( - v8::Local::New(isolate(), GetContext())); - - return GetInner()->Reject(GetContext(), v8::Undefined(isolate())); - } - - v8::Maybe Reject(v8::Local exception) { - v8::HandleScope handle_scope(isolate()); - v8::MicrotasksScope script_scope(isolate(), - v8::MicrotasksScope::kRunMicrotasks); - v8::Context::Scope context_scope( - v8::Local::New(isolate(), GetContext())); - - return GetInner()->Reject(GetContext(), exception); - } - - template - v8::MaybeLocal Then( - base::OnceCallback cb) { - static_assert(sizeof...(ResolveType) <= 1, - "A promise's 'Then' callback should only receive at most one " - "parameter"); - static_assert( - std::is_same>>(), - "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::New(isolate(), GetContext())); - - v8::Local value = gin::ConvertToV8(isolate(), std::move(cb)); - v8::Local handler = v8::Local::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 Resolve(const RT& value) { - static_assert(!std::is_same(), - "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::New(isolate(), GetContext())); - - return GetInner()->Resolve(GetContext(), - mate::ConvertToV8(isolate(), value)); - } - - v8::Maybe ResolveWithGin(const RT& value) { - static_assert(!std::is_same(), - "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::New(isolate(), GetContext())); - - return GetInner()->Resolve(GetContext(), - gin::ConvertToV8(isolate(), value)); - } - - v8::Maybe RejectWithErrorMessage(base::StringPiece string) { - v8::HandleScope handle_scope(isolate()); - v8::MicrotasksScope script_scope(isolate(), - v8::MicrotasksScope::kRunMicrotasks); - v8::Context::Scope context_scope( - v8::Local::New(isolate(), GetContext())); - - v8::Local error = - v8::Exception::Error(gin::StringToV8(isolate(), string)); - return GetInner()->Reject(GetContext(), (error)); - } - - private: - v8::Local GetInner() const { - return resolver_.Get(isolate()); - } - - v8::Isolate* isolate_; - v8::Global context_; - v8::Global resolver_; - - DISALLOW_COPY_AND_ASSIGN(Promise); -}; - -} // namespace util - -} // namespace electron - -namespace mate { - -template -struct Converter> { - static v8::Local ToV8(v8::Isolate* isolate, - const electron::util::Promise& val); - // TODO(MarshallOfSound): Implement FromV8 to allow promise chaining - // in native land - // static bool FromV8(v8::Isolate* isolate, - // v8::Local val, - // Promise* out); -}; - -} // namespace mate - -namespace gin { - -template -struct Converter> { - static v8::Local ToV8(v8::Isolate* isolate, - const electron::util::Promise& val) { - return mate::ConvertToV8(isolate, val); - } -}; - -} // namespace gin - -#endif // SHELL_COMMON_PROMISE_UTIL_H_ diff --git a/shell/renderer/api/atom_api_context_bridge.cc b/shell/renderer/api/atom_api_context_bridge.cc index e3ca10dd0a0..3a99aa4936b 100644 --- a/shell/renderer/api/atom_api_context_bridge.cc +++ b/shell/renderer/api/atom_api_context_bridge.cc @@ -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 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(); } } @@ -195,13 +195,13 @@ v8::MaybeLocal PassValueToOtherContext( v8::Context::Scope destination_scope(destination_context); { auto source_promise = v8::Local::Cast(value); - auto* proxied_promise = new util::Promise>( + auto* proxied_promise = new gin_helper::Promise>( destination_context->GetIsolate()); v8::Local proxied_promise_handle = proxied_promise->GetHandle(); auto then_cb = base::BindOnce( - [](util::Promise>* proxied_promise, + [](gin_helper::Promise>* proxied_promise, v8::Isolate* isolate, v8::Global global_source_context, v8::Global global_destination_context, @@ -220,7 +220,7 @@ v8::MaybeLocal PassValueToOtherContext( destination_context), store); auto catch_cb = base::BindOnce( - [](util::Promise>* proxied_promise, + [](gin_helper::Promise>* proxied_promise, v8::Isolate* isolate, v8::Global global_source_context, v8::Global global_destination_context, diff --git a/shell/renderer/api/atom_api_renderer_ipc.cc b/shell/renderer/api/atom_api_renderer_ipc.cc index b253a0cbabc..1241d6f65d7 100644 --- a/shell/renderer/api/atom_api_renderer_ipc.cc +++ b/shell/renderer/api/atom_api_renderer_ipc.cc @@ -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 { if (!gin::ConvertFromV8(isolate, arguments, &message)) { return v8::Local(); } - electron::util::Promise p(isolate); + gin_helper::Promise p(isolate); auto handle = p.GetHandle(); electron_browser_ptr_->get()->Invoke( internal, channel, std::move(message), base::BindOnce( - [](electron::util::Promise p, - blink::CloneableMessage result) { p.ResolveWithGin(result); }, + [](gin_helper::Promise p, + blink::CloneableMessage result) { p.Resolve(result); }, std::move(p))); return handle; diff --git a/shell/renderer/api/atom_api_web_frame.cc b/shell/renderer/api/atom_api_web_frame.cc index 85538961950..c6f20d38c96 100644 --- a/shell/renderer/api/atom_api_web_frame.cc +++ b/shell/renderer/api/atom_api_web_frame.cc @@ -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> promise) + gin_helper::Promise> promise) : promise_(std::move(promise)) {} ~ScriptExecutionCallback() override = default; @@ -135,7 +135,7 @@ class ScriptExecutionCallback : public blink::WebScriptExecutionCallback { } private: - electron::util::Promise> promise_; + gin_helper::Promise> promise_; DISALLOW_COPY_AND_ASSIGN(ScriptExecutionCallback); }; @@ -378,7 +378,7 @@ v8::Local ExecuteJavaScript(gin_helper::Arguments* args, v8::Local window, const base::string16& code) { v8::Isolate* isolate = args->isolate(); - util::Promise> promise(isolate); + gin_helper::Promise> promise(isolate); v8::Local handle = promise.GetHandle(); bool has_user_gesture = false; @@ -397,7 +397,7 @@ v8::Local ExecuteJavaScriptInIsolatedWorld( int world_id, const std::vector& scripts) { v8::Isolate* isolate = args->isolate(); - util::Promise> promise(isolate); + gin_helper::Promise> promise(isolate); v8::Local handle = promise.GetHandle(); std::vector sources;