// Copyright (c) 2015 GitHub, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ATOM_COMMON_NATIVE_MATE_CONVERTERS_CALLBACK_H_ #define ATOM_COMMON_NATIVE_MATE_CONVERTERS_CALLBACK_H_ #include #include "atom/common/api/locker.h" #include "base/bind.h" #include "base/callback.h" #include "native_mate/function_template.h" #include "native_mate/scoped_persistent.h" #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h" namespace mate { namespace internal { typedef scoped_refptr > SafeV8Function; template struct V8FunctionInvoker {}; template struct V8FunctionInvoker(ArgTypes...)> { static v8::Local Go(v8::Isolate* isolate, SafeV8Function function, ArgTypes... raw) { Locker locker(isolate); v8::EscapableHandleScope handle_scope(isolate); scoped_ptr script_scope( Locker::IsBrowserProcess() ? nullptr : new blink::WebScopedRunV8Script(isolate)); v8::Local holder = function->NewHandle(); v8::Local context = holder->CreationContext(); v8::Context::Scope context_scope(context); std::vector> args = { ConvertToV8(isolate, raw)... }; v8::Local ret(holder->Call(holder, args.size(), &args.front())); return handle_scope.Escape(ret); } }; template struct V8FunctionInvoker { static void Go(v8::Isolate* isolate, SafeV8Function function, ArgTypes... raw) { Locker locker(isolate); v8::HandleScope handle_scope(isolate); scoped_ptr script_scope( Locker::IsBrowserProcess() ? nullptr : new blink::WebScopedRunV8Script(isolate)); v8::Local holder = function->NewHandle(); v8::Local context = holder->CreationContext(); v8::Context::Scope context_scope(context); std::vector> args = { ConvertToV8(isolate, raw)... }; holder->Call(holder, args.size(), &args.front()); } }; template struct V8FunctionInvoker { static ReturnType Go(v8::Isolate* isolate, SafeV8Function function, ArgTypes... raw) { Locker locker(isolate); v8::HandleScope handle_scope(isolate); scoped_ptr script_scope( Locker::IsBrowserProcess() ? nullptr : new blink::WebScopedRunV8Script(isolate)); v8::Local holder = function->NewHandle(); v8::Local context = holder->CreationContext(); v8::Context::Scope context_scope(context); ReturnType ret; std::vector> args = { ConvertToV8(isolate, raw)... }; v8::Local val(holder->Call(holder, args.size(), &args.front())); Converter::FromV8(isolate, val, &ret); return ret; } }; } // namespace internal template struct Converter > { static v8::Local ToV8(v8::Isolate* isolate, const base::Callback& val) { return CreateFunctionTemplate(isolate, val)->GetFunction(); } static bool FromV8(v8::Isolate* isolate, v8::Local val, base::Callback* out) { if (!val->IsFunction()) return false; internal::SafeV8Function function( new RefCountedPersistent(isolate, val)); *out = base::Bind(&internal::V8FunctionInvoker::Go, isolate, function); return true; } }; } // namespace mate #endif // ATOM_COMMON_NATIVE_MATE_CONVERTERS_CALLBACK_H_