• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012
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 // A callback is similar in concept to a function pointer: it wraps a runnable
37 // object such as a function, method, lambda, or even another callback, allowing
38 // the runnable object to be invoked later via the callback object.
39 //
40 // Unlike function pointers, callbacks are created with base::BindOnce() or
41 // base::BindRepeating() and support partial function application.
42 //
43 // A base::OnceCallback may be Run() at most once; a base::RepeatingCallback may
44 // be Run() any number of times. |is_null()| is guaranteed to return true for a
45 // moved-from callback.
46 //
47 //   // The lambda takes two arguments, but the first argument |x| is bound at
48 //   // callback creation.
49 //   base::OnceCallback<int(int)> cb = base::BindOnce([] (int x, int y) {
50 //     return x + y;
51 //   }, 1);
52 //   // Run() only needs the remaining unbound argument |y|.
53 //   printf("1 + 2 = %d\n", std::move(cb).Run(2));  // Prints 3
54 //   printf("cb is null? %s\n",
55 //          cb.is_null() ? "true" : "false");  // Prints true
56 //   std::move(cb).Run(2);  // Crashes since |cb| has already run.
57 //
58 // Callbacks also support cancellation. A common use is binding the receiver
59 // object as a WeakPtr<T>. If that weak pointer is invalidated, calling Run()
60 // will be a no-op. Note that |IsCancelled()| and |is_null()| are distinct:
61 // simply cancelling a callback will not also make it null.
62 //
63 // See https://chromium.googlesource.com/chromium/src/+/HEAD/docs/callback.md
64 // for the full documentation.
65 
66 #ifndef CEF_INCLUDE_BASE_CEF_CALLBACK_H_
67 #define CEF_INCLUDE_BASE_CEF_CALLBACK_H_
68 #pragma once
69 
70 #if defined(USING_CHROMIUM_INCLUDES)
71 // When building CEF include the Chromium header directly.
72 #include "base/callback.h"
73 #else  // !USING_CHROMIUM_INCLUDES
74 // The following is substantially similar to the Chromium implementation.
75 // If the Chromium implementation diverges the below implementation should be
76 // updated to match.
77 
78 #include <stddef.h>
79 
80 #include "include/base/cef_bind.h"
81 #include "include/base/cef_callback_forward.h"
82 #include "include/base/cef_logging.h"
83 #include "include/base/internal/cef_callback_internal.h"
84 
85 namespace base {
86 
87 template <typename R, typename... Args>
88 class OnceCallback<R(Args...)> : public internal::CallbackBase {
89  public:
90   using ResultType = R;
91   using RunType = R(Args...);
92   using PolymorphicInvoke = R (*)(internal::BindStateBase*,
93                                   internal::PassingType<Args>...);
94 
95   constexpr OnceCallback() = default;
96   OnceCallback(std::nullptr_t) = delete;
97 
OnceCallback(internal::BindStateBase * bind_state)98   explicit OnceCallback(internal::BindStateBase* bind_state)
99       : internal::CallbackBase(bind_state) {}
100 
101   OnceCallback(const OnceCallback&) = delete;
102   OnceCallback& operator=(const OnceCallback&) = delete;
103 
104   OnceCallback(OnceCallback&&) noexcept = default;
105   OnceCallback& operator=(OnceCallback&&) noexcept = default;
106 
OnceCallback(RepeatingCallback<RunType> other)107   OnceCallback(RepeatingCallback<RunType> other)
108       : internal::CallbackBase(std::move(other)) {}
109 
110   OnceCallback& operator=(RepeatingCallback<RunType> other) {
111     static_cast<internal::CallbackBase&>(*this) = std::move(other);
112     return *this;
113   }
114 
Run(Args...args)115   R Run(Args... args) const& {
116     static_assert(!sizeof(*this),
117                   "OnceCallback::Run() may only be invoked on a non-const "
118                   "rvalue, i.e. std::move(callback).Run().");
119     NOTREACHED();
120   }
121 
Run(Args...args)122   R Run(Args... args) && {
123     // Move the callback instance into a local variable before the invocation,
124     // that ensures the internal state is cleared after the invocation.
125     // It's not safe to touch |this| after the invocation, since running the
126     // bound function may destroy |this|.
127     OnceCallback cb = std::move(*this);
128     PolymorphicInvoke f =
129         reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
130     return f(cb.bind_state_.get(), std::forward<Args>(args)...);
131   }
132 
133   // Then() returns a new OnceCallback that receives the same arguments as
134   // |this|, and with the return type of |then|. The returned callback will:
135   // 1) Run the functor currently bound to |this| callback.
136   // 2) Run the |then| callback with the result from step 1 as its single
137   //    argument.
138   // 3) Return the value from running the |then| callback.
139   //
140   // Since this method generates a callback that is a replacement for `this`,
141   // `this` will be consumed and reset to a null callback to ensure the
142   // originally-bound functor can be run at most once.
143   template <typename ThenR, typename... ThenArgs>
Then(OnceCallback<ThenR (ThenArgs...)> then)144   OnceCallback<ThenR(Args...)> Then(OnceCallback<ThenR(ThenArgs...)> then) && {
145     CHECK(then);
146     return BindOnce(
147         internal::ThenHelper<
148             OnceCallback, OnceCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
149         std::move(*this), std::move(then));
150   }
151 
152   // This overload is required; even though RepeatingCallback is implicitly
153   // convertible to OnceCallback, that conversion will not used when matching
154   // for template argument deduction.
155   template <typename ThenR, typename... ThenArgs>
Then(RepeatingCallback<ThenR (ThenArgs...)> then)156   OnceCallback<ThenR(Args...)> Then(
157       RepeatingCallback<ThenR(ThenArgs...)> then) && {
158     CHECK(then);
159     return BindOnce(
160         internal::ThenHelper<
161             OnceCallback,
162             RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
163         std::move(*this), std::move(then));
164   }
165 };
166 
167 template <typename R, typename... Args>
168 class RepeatingCallback<R(Args...)> : public internal::CallbackBaseCopyable {
169  public:
170   using ResultType = R;
171   using RunType = R(Args...);
172   using PolymorphicInvoke = R (*)(internal::BindStateBase*,
173                                   internal::PassingType<Args>...);
174 
175   constexpr RepeatingCallback() = default;
176   RepeatingCallback(std::nullptr_t) = delete;
177 
RepeatingCallback(internal::BindStateBase * bind_state)178   explicit RepeatingCallback(internal::BindStateBase* bind_state)
179       : internal::CallbackBaseCopyable(bind_state) {}
180 
181   // Copyable and movable.
182   RepeatingCallback(const RepeatingCallback&) = default;
183   RepeatingCallback& operator=(const RepeatingCallback&) = default;
184   RepeatingCallback(RepeatingCallback&&) noexcept = default;
185   RepeatingCallback& operator=(RepeatingCallback&&) noexcept = default;
186 
187   bool operator==(const RepeatingCallback& other) const {
188     return EqualsInternal(other);
189   }
190 
191   bool operator!=(const RepeatingCallback& other) const {
192     return !operator==(other);
193   }
194 
Run(Args...args)195   R Run(Args... args) const& {
196     PolymorphicInvoke f =
197         reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke());
198     return f(this->bind_state_.get(), std::forward<Args>(args)...);
199   }
200 
Run(Args...args)201   R Run(Args... args) && {
202     // Move the callback instance into a local variable before the invocation,
203     // that ensures the internal state is cleared after the invocation.
204     // It's not safe to touch |this| after the invocation, since running the
205     // bound function may destroy |this|.
206     RepeatingCallback cb = std::move(*this);
207     PolymorphicInvoke f =
208         reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
209     return f(std::move(cb).bind_state_.get(), std::forward<Args>(args)...);
210   }
211 
212   // Then() returns a new RepeatingCallback that receives the same arguments as
213   // |this|, and with the return type of |then|. The
214   // returned callback will:
215   // 1) Run the functor currently bound to |this| callback.
216   // 2) Run the |then| callback with the result from step 1 as its single
217   //    argument.
218   // 3) Return the value from running the |then| callback.
219   //
220   // If called on an rvalue (e.g. std::move(cb).Then(...)), this method
221   // generates a callback that is a replacement for `this`. Therefore, `this`
222   // will be consumed and reset to a null callback to ensure the
223   // originally-bound functor will be run at most once.
224   template <typename ThenR, typename... ThenArgs>
Then(RepeatingCallback<ThenR (ThenArgs...)> then)225   RepeatingCallback<ThenR(Args...)> Then(
226       RepeatingCallback<ThenR(ThenArgs...)> then) const& {
227     CHECK(then);
228     return BindRepeating(
229         internal::ThenHelper<
230             RepeatingCallback,
231             RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
232         *this, std::move(then));
233   }
234 
235   template <typename ThenR, typename... ThenArgs>
Then(RepeatingCallback<ThenR (ThenArgs...)> then)236   RepeatingCallback<ThenR(Args...)> Then(
237       RepeatingCallback<ThenR(ThenArgs...)> then) && {
238     CHECK(then);
239     return BindRepeating(
240         internal::ThenHelper<
241             RepeatingCallback,
242             RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
243         std::move(*this), std::move(then));
244   }
245 };
246 
247 }  // namespace base
248 
249 #endif  // !USING_CHROMIUM_INCLUDES
250 
251 #endif  // CEF_INCLUDE_BASE_CEF_CALLBACK_H_
252