1 // Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011
2 // Google Inc. All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the name Chromium Embedded
15 // Framework nor the names of its contributors may be used to endorse
16 // or promote products derived from this software without specific prior
17 // written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 // -----------------------------------------------------------------------------
32 // Usage documentation
33 // -----------------------------------------------------------------------------
34 //
35 // Overview:
36 // base::BindOnce() and base::BindRepeating() are helpers for creating
37 // base::OnceCallback and base::RepeatingCallback objects respectively.
38 //
39 // For a runnable object of n-arity, the base::Bind*() family allows partial
40 // application of the first m arguments. The remaining n - m arguments must be
41 // passed when invoking the callback with Run().
42 //
43 // // The first argument is bound at callback creation; the remaining
44 // // two must be passed when calling Run() on the callback object.
45 // base::OnceCallback<long(int, long)> cb = base::BindOnce(
46 // [](short x, int y, long z) { return x * y * z; }, 42);
47 //
48 // When binding to a method, the receiver object must also be specified at
49 // callback creation time. When Run() is invoked, the method will be invoked on
50 // the specified receiver object.
51 //
52 // class C : public base::RefCounted<C> { void F(); };
53 // auto instance = base::MakeRefCounted<C>();
54 // auto cb = base::BindOnce(&C::F, instance);
55 // std::move(cb).Run(); // Identical to instance->F()
56 //
57 // See //docs/callback.md for the full documentation.
58 //
59 // -----------------------------------------------------------------------------
60 // Implementation notes
61 // -----------------------------------------------------------------------------
62 //
63 // If you're reading the implementation, before proceeding further, you should
64 // read the top comment of base/internal/cef_bind_internal.h for a definition of
65 // common terms and concepts.
66
67 #ifndef CEF_INCLUDE_BASE_CEF_BIND_H_
68 #define CEF_INCLUDE_BASE_CEF_BIND_H_
69 #pragma once
70
71 #if defined(USING_CHROMIUM_INCLUDES)
72 // When building CEF include the Chromium header directly.
73 #include "base/bind.h"
74 #else // !USING_CHROMIUM_INCLUDES
75 // The following is substantially similar to the Chromium implementation.
76 // If the Chromium implementation diverges the below implementation should be
77 // updated to match.
78
79 #include <functional>
80 #include <memory>
81 #include <type_traits>
82 #include <utility>
83
84 #include "include/base/cef_build.h"
85 #include "include/base/cef_compiler_specific.h"
86 #include "include/base/cef_template_util.h"
87 #include "include/base/internal/cef_bind_internal.h"
88
89 #if defined(OS_APPLE) && !HAS_FEATURE(objc_arc)
90 #include "include/base/internal/cef_scoped_block_mac.h"
91 #endif
92
93 namespace base {
94
95 // Bind as OnceCallback.
96 template <typename Functor, typename... Args>
BindOnce(Functor && functor,Args &&...args)97 inline OnceCallback<internal::MakeUnboundRunType<Functor, Args...>> BindOnce(
98 Functor&& functor,
99 Args&&... args) {
100 static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
101 (std::is_rvalue_reference<Functor&&>() &&
102 !std::is_const<std::remove_reference_t<Functor>>()),
103 "BindOnce requires non-const rvalue for OnceCallback binding."
104 " I.e.: base::BindOnce(std::move(callback)).");
105 static_assert(
106 conjunction<
107 internal::AssertBindArgIsNotBasePassed<std::decay_t<Args>>...>::value,
108 "Use std::move() instead of base::Passed() with base::BindOnce()");
109
110 return internal::BindImpl<OnceCallback>(std::forward<Functor>(functor),
111 std::forward<Args>(args)...);
112 }
113
114 // Bind as RepeatingCallback.
115 template <typename Functor, typename... Args>
116 inline RepeatingCallback<internal::MakeUnboundRunType<Functor, Args...>>
BindRepeating(Functor && functor,Args &&...args)117 BindRepeating(Functor&& functor, Args&&... args) {
118 static_assert(
119 !internal::IsOnceCallback<std::decay_t<Functor>>(),
120 "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
121
122 return internal::BindImpl<RepeatingCallback>(std::forward<Functor>(functor),
123 std::forward<Args>(args)...);
124 }
125
126 // Special cases for binding to a base::Callback without extra bound arguments.
127 // We CHECK() the validity of callback to guard against null pointers
128 // accidentally ending up in posted tasks, causing hard-to-debug crashes.
129 template <typename Signature>
BindOnce(OnceCallback<Signature> callback)130 OnceCallback<Signature> BindOnce(OnceCallback<Signature> callback) {
131 CHECK(callback);
132 return callback;
133 }
134
135 template <typename Signature>
BindOnce(RepeatingCallback<Signature> callback)136 OnceCallback<Signature> BindOnce(RepeatingCallback<Signature> callback) {
137 CHECK(callback);
138 return callback;
139 }
140
141 template <typename Signature>
BindRepeating(RepeatingCallback<Signature> callback)142 RepeatingCallback<Signature> BindRepeating(
143 RepeatingCallback<Signature> callback) {
144 CHECK(callback);
145 return callback;
146 }
147
148 // Unretained() allows binding a non-refcounted class, and to disable
149 // refcounting on arguments that are refcounted objects.
150 //
151 // EXAMPLE OF Unretained():
152 //
153 // class Foo {
154 // public:
155 // void func() { cout << "Foo:f" << endl; }
156 // };
157 //
158 // // In some function somewhere.
159 // Foo foo;
160 // OnceClosure foo_callback =
161 // BindOnce(&Foo::func, Unretained(&foo));
162 // std::move(foo_callback).Run(); // Prints "Foo:f".
163 //
164 // Without the Unretained() wrapper on |&foo|, the above call would fail
165 // to compile because Foo does not support the AddRef() and Release() methods.
166 template <typename T>
Unretained(T * o)167 inline internal::UnretainedWrapper<T> Unretained(T* o) {
168 return internal::UnretainedWrapper<T>(o);
169 }
170
171 // RetainedRef() accepts a ref counted object and retains a reference to it.
172 // When the callback is called, the object is passed as a raw pointer.
173 //
174 // EXAMPLE OF RetainedRef():
175 //
176 // void foo(RefCountedBytes* bytes) {}
177 //
178 // scoped_refptr<RefCountedBytes> bytes = ...;
179 // OnceClosure callback = BindOnce(&foo, base::RetainedRef(bytes));
180 // std::move(callback).Run();
181 //
182 // Without RetainedRef, the scoped_refptr would try to implicitly convert to
183 // a raw pointer and fail compilation:
184 //
185 // OnceClosure callback = BindOnce(&foo, bytes); // ERROR!
186 template <typename T>
RetainedRef(T * o)187 inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
188 return internal::RetainedRefWrapper<T>(o);
189 }
190 template <typename T>
RetainedRef(scoped_refptr<T> o)191 inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
192 return internal::RetainedRefWrapper<T>(std::move(o));
193 }
194
195 // Owned() transfers ownership of an object to the callback resulting from
196 // bind; the object will be deleted when the callback is deleted.
197 //
198 // EXAMPLE OF Owned():
199 //
200 // void foo(int* arg) { cout << *arg << endl }
201 //
202 // int* pn = new int(1);
203 // RepeatingClosure foo_callback = BindRepeating(&foo, Owned(pn));
204 //
205 // foo_callback.Run(); // Prints "1"
206 // foo_callback.Run(); // Prints "1"
207 // *pn = 2;
208 // foo_callback.Run(); // Prints "2"
209 //
210 // foo_callback.Reset(); // |pn| is deleted. Also will happen when
211 // // |foo_callback| goes out of scope.
212 //
213 // Without Owned(), someone would have to know to delete |pn| when the last
214 // reference to the callback is deleted.
215 template <typename T>
Owned(T * o)216 inline internal::OwnedWrapper<T> Owned(T* o) {
217 return internal::OwnedWrapper<T>(o);
218 }
219
220 template <typename T, typename Deleter>
Owned(std::unique_ptr<T,Deleter> && ptr)221 inline internal::OwnedWrapper<T, Deleter> Owned(
222 std::unique_ptr<T, Deleter>&& ptr) {
223 return internal::OwnedWrapper<T, Deleter>(std::move(ptr));
224 }
225
226 // OwnedRef() stores an object in the callback resulting from
227 // bind and passes a reference to the object to the bound function.
228 //
229 // EXAMPLE OF OwnedRef():
230 //
231 // void foo(int& arg) { cout << ++arg << endl }
232 //
233 // int counter = 0;
234 // RepeatingClosure foo_callback = BindRepeating(&foo, OwnedRef(counter));
235 //
236 // foo_callback.Run(); // Prints "1"
237 // foo_callback.Run(); // Prints "2"
238 // foo_callback.Run(); // Prints "3"
239 //
240 // cout << counter; // Prints "0", OwnedRef creates a copy of counter.
241 //
242 // Supports OnceCallbacks as well, useful to pass placeholder arguments:
243 //
244 // void bar(int& ignore, const std::string& s) { cout << s << endl }
245 //
246 // OnceClosure bar_callback = BindOnce(&bar, OwnedRef(0), "Hello");
247 //
248 // std::move(bar_callback).Run(); // Prints "Hello"
249 //
250 // Without OwnedRef() it would not be possible to pass a mutable reference to an
251 // object owned by the callback.
252 template <typename T>
OwnedRef(T && t)253 internal::OwnedRefWrapper<std::decay_t<T>> OwnedRef(T&& t) {
254 return internal::OwnedRefWrapper<std::decay_t<T>>(std::forward<T>(t));
255 }
256
257 // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
258 // through a RepeatingCallback. Logically, this signifies a destructive transfer
259 // of the state of the argument into the target function. Invoking
260 // RepeatingCallback::Run() twice on a callback that was created with a Passed()
261 // argument will CHECK() because the first invocation would have already
262 // transferred ownership to the target function.
263 //
264 // Note that Passed() is not necessary with BindOnce(), as std::move() does the
265 // same thing. Avoid Passed() in favor of std::move() with BindOnce().
266 //
267 // EXAMPLE OF Passed():
268 //
269 // void TakesOwnership(std::unique_ptr<Foo> arg) { }
270 // std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
271 // }
272 //
273 // auto f = std::make_unique<Foo>();
274 //
275 // // |cb| is given ownership of Foo(). |f| is now NULL.
276 // // You can use std::move(f) in place of &f, but it's more verbose.
277 // RepeatingClosure cb = BindRepeating(&TakesOwnership, Passed(&f));
278 //
279 // // Run was never called so |cb| still owns Foo() and deletes
280 // // it on Reset().
281 // cb.Reset();
282 //
283 // // |cb| is given a new Foo created by CreateFoo().
284 // cb = BindRepeating(&TakesOwnership, Passed(CreateFoo()));
285 //
286 // // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
287 // // no longer owns Foo() and, if reset, would not delete Foo().
288 // cb.Run(); // Foo() is now transferred to |arg| and deleted.
289 // cb.Run(); // This CHECK()s since Foo() already been used once.
290 //
291 // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and is
292 // best suited for use with the return value of a function or other temporary
293 // rvalues. The second takes a pointer to the scoper and is just syntactic sugar
294 // to avoid having to write Passed(std::move(scoper)).
295 //
296 // Both versions of Passed() prevent T from being an lvalue reference. The first
297 // via use of enable_if, and the second takes a T* which will not bind to T&.
298 template <typename T,
299 std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr>
Passed(T && scoper)300 inline internal::PassedWrapper<T> Passed(T&& scoper) {
301 return internal::PassedWrapper<T>(std::move(scoper));
302 }
303 template <typename T>
Passed(T * scoper)304 inline internal::PassedWrapper<T> Passed(T* scoper) {
305 return internal::PassedWrapper<T>(std::move(*scoper));
306 }
307
308 // IgnoreResult() is used to adapt a function or callback with a return type to
309 // one with a void return. This is most useful if you have a function with,
310 // say, a pesky ignorable bool return that you want to use with PostTask or
311 // something else that expect a callback with a void return.
312 //
313 // EXAMPLE OF IgnoreResult():
314 //
315 // int DoSomething(int arg) { cout << arg << endl; }
316 //
317 // // Assign to a callback with a void return type.
318 // OnceCallback<void(int)> cb = BindOnce(IgnoreResult(&DoSomething));
319 // std::move(cb).Run(1); // Prints "1".
320 //
321 // // Prints "2" on |ml|.
322 // ml->PostTask(FROM_HERE, BindOnce(IgnoreResult(&DoSomething), 2);
323 template <typename T>
IgnoreResult(T data)324 inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
325 return internal::IgnoreResultHelper<T>(std::move(data));
326 }
327
328 #if defined(OS_APPLE) && !HAS_FEATURE(objc_arc)
329
330 // RetainBlock() is used to adapt an Objective-C block when Automated Reference
331 // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
332 // BindOnce and BindRepeating already support blocks then.
333 //
334 // EXAMPLE OF RetainBlock():
335 //
336 // // Wrap the block and bind it to a callback.
337 // OnceCallback<void(int)> cb =
338 // BindOnce(RetainBlock(^(int n) { NSLog(@"%d", n); }));
339 // std::move(cb).Run(1); // Logs "1".
340 template <typename R, typename... Args>
341 base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
342 return base::mac::ScopedBlock<R (^)(Args...)>(block,
343 base::scoped_policy::RETAIN);
344 }
345
346 #endif // defined(OS_APPLE) && !HAS_FEATURE(objc_arc)
347
348 } // namespace base
349
350 #endif // !USING_CHROMIUM_INCLUDES
351
352 #endif // CEF_INCLUDE_BASE_CEF_BIND_H_
353