Fix FullScreen crash in Webapp
[platform/framework/web/chromium-efl.git] / gin / function_template.h
1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef GIN_FUNCTION_TEMPLATE_H_
6 #define GIN_FUNCTION_TEMPLATE_H_
7
8 #include <stddef.h>
9 #include <type_traits>
10 #include <utility>
11
12 #include "base/check.h"
13 #include "base/functional/callback.h"
14 #include "base/memory/raw_ptr.h"
15 #include "base/strings/strcat.h"
16 #include "gin/arguments.h"
17 #include "gin/converter.h"
18 #include "gin/gin_export.h"
19 #include "v8/include/v8-external.h"
20 #include "v8/include/v8-forward.h"
21 #include "v8/include/v8-persistent-handle.h"
22 #include "v8/include/v8-template.h"
23
24 namespace gin {
25
26 struct InvokerOptions {
27   bool holder_is_first_argument = false;
28   const char* holder_type = nullptr;  // Null if unknown or not applicable.
29 };
30
31 namespace internal {
32
33 template<typename T>
34 struct CallbackParamTraits {
35   typedef T LocalType;
36 };
37 template<typename T>
38 struct CallbackParamTraits<const T&> {
39   typedef T LocalType;
40 };
41 template<typename T>
42 struct CallbackParamTraits<const T*> {
43   typedef T* LocalType;
44 };
45
46 // CallbackHolder and CallbackHolderBase are used to pass a
47 // base::RepeatingCallback from CreateFunctionTemplate through v8 (via
48 // v8::FunctionTemplate) to DispatchToCallback, where it is invoked.
49
50 // This simple base class is used so that we can share a single object template
51 // among every CallbackHolder instance.
52 class GIN_EXPORT CallbackHolderBase {
53  public:
54   CallbackHolderBase(const CallbackHolderBase&) = delete;
55   CallbackHolderBase& operator=(const CallbackHolderBase&) = delete;
56
57   v8::Local<v8::External> GetHandle(v8::Isolate* isolate);
58
59  protected:
60   explicit CallbackHolderBase(v8::Isolate* isolate);
61   virtual ~CallbackHolderBase();
62
63  private:
64   static void FirstWeakCallback(
65       const v8::WeakCallbackInfo<CallbackHolderBase>& data);
66   static void SecondWeakCallback(
67       const v8::WeakCallbackInfo<CallbackHolderBase>& data);
68
69   v8::Global<v8::External> v8_ref_;
70 };
71
72 template<typename Sig>
73 class CallbackHolder : public CallbackHolderBase {
74  public:
75   CallbackHolder(v8::Isolate* isolate,
76                  base::RepeatingCallback<Sig> callback,
77                  InvokerOptions invoker_options)
78       : CallbackHolderBase(isolate),
79         callback(std::move(callback)),
80         invoker_options(std::move(invoker_options)) {}
81   CallbackHolder(const CallbackHolder&) = delete;
82   CallbackHolder& operator=(const CallbackHolder&) = delete;
83
84   base::RepeatingCallback<Sig> callback;
85   InvokerOptions invoker_options;
86
87  private:
88   ~CallbackHolder() override = default;
89 };
90
91 template <typename T>
92 bool GetNextArgument(Arguments* args,
93                      const InvokerOptions& invoker_options,
94                      bool is_first,
95                      T* result) {
96   if (is_first && invoker_options.holder_is_first_argument) {
97     return args->GetHolder(result);
98   } else {
99     return args->GetNext(result);
100   }
101 }
102
103 // For advanced use cases, we allow callers to request the unparsed Arguments
104 // object and poke around in it directly.
105 inline bool GetNextArgument(Arguments* args,
106                             const InvokerOptions& invoker_options,
107                             bool is_first,
108                             Arguments* result) {
109   *result = *args;
110   return true;
111 }
112 inline bool GetNextArgument(Arguments* args,
113                             const InvokerOptions& invoker_options,
114                             bool is_first,
115                             Arguments** result) {
116   *result = args;
117   return true;
118 }
119
120 // It's common for clients to just need the isolate, so we make that easy.
121 inline bool GetNextArgument(Arguments* args,
122                             const InvokerOptions& invoker_options,
123                             bool is_first,
124                             v8::Isolate** result) {
125   *result = args->isolate();
126   return true;
127 }
128
129 // Throws an error indicating conversion failure.
130 GIN_EXPORT void ThrowConversionError(Arguments* args,
131                                      const InvokerOptions& invoker_options,
132                                      size_t index);
133
134 // Class template for extracting and storing single argument for callback
135 // at position |index|.
136 template <size_t index, typename ArgType, typename = void>
137 struct ArgumentHolder {
138   using ArgLocalType = typename CallbackParamTraits<ArgType>::LocalType;
139
140   ArgLocalType value;
141   bool ok;
142
143   ArgumentHolder(Arguments* args, const InvokerOptions& invoker_options)
144       : ok(GetNextArgument(args, invoker_options, index == 0, &value)) {
145     if (!ok)
146       ThrowConversionError(args, invoker_options, index);
147   }
148 };
149
150 // This is required for types such as v8::LocalVector<T>, which don't have
151 // a default constructor. To create an element of such a type, the isolate
152 // has to be provided.
153 template <size_t index, typename ArgType>
154 struct ArgumentHolder<
155     index,
156     ArgType,
157     std::enable_if_t<!std::is_default_constructible_v<
158                          typename CallbackParamTraits<ArgType>::LocalType> &&
159                      std::is_constructible_v<
160                          typename CallbackParamTraits<ArgType>::LocalType,
161                          v8::Isolate*>>> {
162   using ArgLocalType = typename CallbackParamTraits<ArgType>::LocalType;
163
164   ArgLocalType value;
165   bool ok;
166
167   ArgumentHolder(Arguments* args, const InvokerOptions& invoker_options)
168       : value(args->isolate()),
169         ok(GetNextArgument(args, invoker_options, index == 0, &value)) {
170     if (!ok) {
171       ThrowConversionError(args, invoker_options, index);
172     }
173   }
174 };
175
176 // Class template for converting arguments from JavaScript to C++ and running
177 // the callback with them.
178 template <typename IndicesType, typename... ArgTypes>
179 class Invoker;
180
181 template <size_t... indices, typename... ArgTypes>
182 class Invoker<std::index_sequence<indices...>, ArgTypes...>
183     : public ArgumentHolder<indices, ArgTypes>... {
184  public:
185   // Invoker<> inherits from ArgumentHolder<> for each argument.
186   // C++ has always been strict about the class initialization order,
187   // so it is guaranteed ArgumentHolders will be initialized (and thus, will
188   // extract arguments from Arguments) in the right order.
189   Invoker(Arguments* args, const InvokerOptions& invoker_options)
190       : ArgumentHolder<indices, ArgTypes>(args, invoker_options)...,
191         args_(args) {}
192
193   bool IsOK() {
194     return And(ArgumentHolder<indices, ArgTypes>::ok...);
195   }
196
197   template <typename ReturnType>
198   void DispatchToCallback(
199       base::RepeatingCallback<ReturnType(ArgTypes...)> callback) {
200     args_->Return(
201         callback.Run(std::move(ArgumentHolder<indices, ArgTypes>::value)...));
202   }
203
204   // In C++, you can declare the function foo(void), but you can't pass a void
205   // expression to foo. As a result, we must specialize the case of Callbacks
206   // that have the void return type.
207   void DispatchToCallback(base::RepeatingCallback<void(ArgTypes...)> callback) {
208     callback.Run(std::move(ArgumentHolder<indices, ArgTypes>::value)...);
209   }
210
211  private:
212   static bool And() { return true; }
213   template <typename... T>
214   static bool And(bool arg1, T... args) {
215     return arg1 && And(args...);
216   }
217
218   raw_ptr<Arguments> args_;
219 };
220
221 // DispatchToCallback converts all the JavaScript arguments to C++ types and
222 // invokes the base::RepeatingCallback.
223 template <typename Sig>
224 struct Dispatcher {};
225
226 template <typename ReturnType, typename... ArgTypes>
227 struct Dispatcher<ReturnType(ArgTypes...)> {
228   static void DispatchToCallbackImpl(Arguments* args) {
229     v8::Local<v8::External> v8_holder;
230     CHECK(args->GetData(&v8_holder));
231     CallbackHolderBase* holder_base = reinterpret_cast<CallbackHolderBase*>(
232         v8_holder->Value());
233
234     typedef CallbackHolder<ReturnType(ArgTypes...)> HolderT;
235     HolderT* holder = static_cast<HolderT*>(holder_base);
236
237     using Indices = std::index_sequence_for<ArgTypes...>;
238     Invoker<Indices, ArgTypes...> invoker(args, holder->invoker_options);
239     if (invoker.IsOK())
240       invoker.DispatchToCallback(holder->callback);
241   }
242
243   static void DispatchToCallback(
244       const v8::FunctionCallbackInfo<v8::Value>& info) {
245     Arguments args(info);
246     DispatchToCallbackImpl(&args);
247   }
248
249   static void DispatchToCallbackForProperty(
250       v8::Local<v8::Name>,
251       const v8::PropertyCallbackInfo<v8::Value>& info) {
252     Arguments args(info);
253     DispatchToCallbackImpl(&args);
254   }
255 };
256
257 }  // namespace internal
258
259 // CreateFunctionTemplate creates a v8::FunctionTemplate that will create
260 // JavaScript functions that execute a provided C++ function or
261 // base::RepeatingCallback. JavaScript arguments are automatically converted via
262 // gin::Converter, as is the return value of the C++ function, if any.
263 // |invoker_options| contains additional parameters. If it contains a
264 // holder_type, it will be used to provide a useful conversion error if the
265 // holder is the first argument. If not provided, a generic invocation error
266 // will be used.
267 //
268 // NOTE: V8 caches FunctionTemplates for a lifetime of a web page for its own
269 // internal reasons, thus it is generally a good idea to cache the template
270 // returned by this function.  Otherwise, repeated method invocations from JS
271 // will create substantial memory leaks. See http://crbug.com/463487.
272 template <typename Sig>
273 v8::Local<v8::FunctionTemplate> CreateFunctionTemplate(
274     v8::Isolate* isolate,
275     base::RepeatingCallback<Sig> callback,
276     InvokerOptions invoker_options = {}) {
277   typedef internal::CallbackHolder<Sig> HolderT;
278   HolderT* holder =
279       new HolderT(isolate, std::move(callback), std::move(invoker_options));
280
281   v8::Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New(
282       isolate, &internal::Dispatcher<Sig>::DispatchToCallback,
283       ConvertToV8<v8::Local<v8::External>>(isolate, holder->GetHandle(isolate)),
284       v8::Local<v8::Signature>(), 0, v8::ConstructorBehavior::kThrow);
285   return tmpl;
286 }
287
288 // CreateDataPropertyCallback creates a v8::AccessorNameGetterCallback and
289 // corresponding data value that will hold and execute the provided
290 // base::RepeatingCallback, using automatic conversions similar to
291 // |CreateFunctionTemplate|.
292 //
293 // It is expected that these will be passed to v8::Template::SetLazyDataProperty
294 // or another similar function.
295 template <typename Sig>
296 std::pair<v8::AccessorNameGetterCallback, v8::Local<v8::Value>>
297 CreateDataPropertyCallback(v8::Isolate* isolate,
298                            base::RepeatingCallback<Sig> callback,
299                            InvokerOptions invoker_options = {}) {
300   typedef internal::CallbackHolder<Sig> HolderT;
301   HolderT* holder =
302       new HolderT(isolate, std::move(callback), std::move(invoker_options));
303   return {&internal::Dispatcher<Sig>::DispatchToCallbackForProperty,
304           ConvertToV8<v8::Local<v8::External>>(isolate,
305                                                holder->GetHandle(isolate))};
306 }
307
308 }  // namespace gin
309
310 #endif  // GIN_FUNCTION_TEMPLATE_H_