]> git.sesse.net Git - casparcg/blob - dependencies64/cef/include/base/cef_weak_ptr.h
* Merged html producer and updated to latest CEF version (does not have satisfactory...
[casparcg] / dependencies64 / cef / include / base / cef_weak_ptr.h
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 // Weak pointers are pointers to an object that do not affect its lifetime,
32 // and which may be invalidated (i.e. reset to NULL) by the object, or its
33 // owner, at any time, most commonly when the object is about to be deleted.
34
35 // Weak pointers are useful when an object needs to be accessed safely by one
36 // or more objects other than its owner, and those callers can cope with the
37 // object vanishing and e.g. tasks posted to it being silently dropped.
38 // Reference-counting such an object would complicate the ownership graph and
39 // make it harder to reason about the object's lifetime.
40
41 // EXAMPLE:
42 //
43 //  class Controller {
44 //   public:
45 //    void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
46 //    void WorkComplete(const Result& result) { ... }
47 //   private:
48 //    // Member variables should appear before the WeakPtrFactory, to ensure
49 //    // that any WeakPtrs to Controller are invalidated before its members
50 //    // variable's destructors are executed, rendering them invalid.
51 //    WeakPtrFactory<Controller> weak_factory_;
52 //  };
53 //
54 //  class Worker {
55 //   public:
56 //    static void StartNew(const WeakPtr<Controller>& controller) {
57 //      Worker* worker = new Worker(controller);
58 //      // Kick off asynchronous processing...
59 //    }
60 //   private:
61 //    Worker(const WeakPtr<Controller>& controller)
62 //        : controller_(controller) {}
63 //    void DidCompleteAsynchronousProcessing(const Result& result) {
64 //      if (controller_)
65 //        controller_->WorkComplete(result);
66 //    }
67 //    WeakPtr<Controller> controller_;
68 //  };
69 //
70 // With this implementation a caller may use SpawnWorker() to dispatch multiple
71 // Workers and subsequently delete the Controller, without waiting for all
72 // Workers to have completed.
73
74 // ------------------------- IMPORTANT: Thread-safety -------------------------
75
76 // Weak pointers may be passed safely between threads, but must always be
77 // dereferenced and invalidated on the same thread otherwise checking the
78 // pointer would be racey.
79 //
80 // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory
81 // is dereferenced, the factory and its WeakPtrs become bound to the calling
82 // thread, and cannot be dereferenced or invalidated on any other thread. Bound
83 // WeakPtrs can still be handed off to other threads, e.g. to use to post tasks
84 // back to object on the bound thread.
85 //
86 // Invalidating the factory's WeakPtrs un-binds it from the thread, allowing it
87 // to be passed for a different thread to use or delete it.
88
89 #ifndef CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_
90 #define CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_
91 #pragma once
92
93 #if defined(BASE_MEMORY_WEAK_PTR_H_)
94 // Do nothing if the Chromium header has already been included.
95 // This can happen in cases where Chromium code is used directly by the
96 // client application. When using Chromium code directly always include
97 // the Chromium header first to avoid type conflicts.
98 #elif defined(BUILDING_CEF_SHARED)
99 // When building CEF include the Chromium header directly.
100 #include "base/memory/weak_ptr.h"
101 #else  // !BUILDING_CEF_SHARED
102 // The following is substantially similar to the Chromium implementation.
103 // If the Chromium implementation diverges the below implementation should be
104 // updated to match.
105
106 #include "include/base/cef_basictypes.h"
107 #include "include/base/cef_logging.h"
108 #include "include/base/cef_ref_counted.h"
109 #include "include/base/cef_template_util.h"
110 #include "include/base/cef_thread_checker.h"
111
112 namespace base {
113
114 template <typename T> class SupportsWeakPtr;
115 template <typename T> class WeakPtr;
116
117 namespace cef_internal {
118 // These classes are part of the WeakPtr implementation.
119 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
120
121 class WeakReference {
122  public:
123   // Although Flag is bound to a specific thread, it may be deleted from another
124   // via base::WeakPtr::~WeakPtr().
125   class Flag : public RefCountedThreadSafe<Flag> {
126    public:
127     Flag();
128
129     void Invalidate();
130     bool IsValid() const;
131
132    private:
133     friend class base::RefCountedThreadSafe<Flag>;
134
135     ~Flag();
136
137     // The current Chromium implementation uses SequenceChecker instead of
138     // ThreadChecker to support SequencedWorkerPools. CEF does not yet expose
139     // the concept of SequencedWorkerPools.
140     ThreadChecker thread_checker_;
141     bool is_valid_;
142   };
143
144   WeakReference();
145   explicit WeakReference(const Flag* flag);
146   ~WeakReference();
147
148   bool is_valid() const;
149
150  private:
151   scoped_refptr<const Flag> flag_;
152 };
153
154 class WeakReferenceOwner {
155  public:
156   WeakReferenceOwner();
157   ~WeakReferenceOwner();
158
159   WeakReference GetRef() const;
160
161   bool HasRefs() const {
162     return flag_.get() && !flag_->HasOneRef();
163   }
164
165   void Invalidate();
166
167  private:
168   mutable scoped_refptr<WeakReference::Flag> flag_;
169 };
170
171 // This class simplifies the implementation of WeakPtr's type conversion
172 // constructor by avoiding the need for a public accessor for ref_.  A
173 // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
174 // base class gives us a way to access ref_ in a protected fashion.
175 class WeakPtrBase {
176  public:
177   WeakPtrBase();
178   ~WeakPtrBase();
179
180  protected:
181   explicit WeakPtrBase(const WeakReference& ref);
182
183   WeakReference ref_;
184 };
185
186 // This class provides a common implementation of common functions that would
187 // otherwise get instantiated separately for each distinct instantiation of
188 // SupportsWeakPtr<>.
189 class SupportsWeakPtrBase {
190  public:
191   // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
192   // conversion will only compile if there is exists a Base which inherits
193   // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
194   // function that makes calling this easier.
195   template<typename Derived>
196   static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
197     typedef
198         is_convertible<Derived, cef_internal::SupportsWeakPtrBase&> convertible;
199     COMPILE_ASSERT(convertible::value,
200                    AsWeakPtr_argument_inherits_from_SupportsWeakPtr);
201     return AsWeakPtrImpl<Derived>(t, *t);
202   }
203
204  private:
205   // This template function uses type inference to find a Base of Derived
206   // which is an instance of SupportsWeakPtr<Base>. We can then safely
207   // static_cast the Base* to a Derived*.
208   template <typename Derived, typename Base>
209   static WeakPtr<Derived> AsWeakPtrImpl(
210       Derived* t, const SupportsWeakPtr<Base>&) {
211     WeakPtr<Base> ptr = t->Base::AsWeakPtr();
212     return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
213   }
214 };
215
216 }  // namespace cef_internal
217
218 template <typename T> class WeakPtrFactory;
219
220 // The WeakPtr class holds a weak reference to |T*|.
221 //
222 // This class is designed to be used like a normal pointer.  You should always
223 // null-test an object of this class before using it or invoking a method that
224 // may result in the underlying object being destroyed.
225 //
226 // EXAMPLE:
227 //
228 //   class Foo { ... };
229 //   WeakPtr<Foo> foo;
230 //   if (foo)
231 //     foo->method();
232 //
233 template <typename T>
234 class WeakPtr : public cef_internal::WeakPtrBase {
235  public:
236   WeakPtr() : ptr_(NULL) {
237   }
238
239   // Allow conversion from U to T provided U "is a" T. Note that this
240   // is separate from the (implicit) copy constructor.
241   template <typename U>
242   WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) {
243   }
244
245   T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
246
247   T& operator*() const {
248     DCHECK(get() != NULL);
249     return *get();
250   }
251   T* operator->() const {
252     DCHECK(get() != NULL);
253     return get();
254   }
255
256   // Allow WeakPtr<element_type> to be used in boolean expressions, but not
257   // implicitly convertible to a real bool (which is dangerous).
258   //
259   // Note that this trick is only safe when the == and != operators
260   // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2"
261   // will compile but do the wrong thing (i.e., convert to Testable
262   // and then do the comparison).
263  private:
264   typedef T* WeakPtr::*Testable;
265
266  public:
267   operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; }
268
269   void reset() {
270     ref_ = cef_internal::WeakReference();
271     ptr_ = NULL;
272   }
273
274  private:
275   // Explicitly declare comparison operators as required by the bool
276   // trick, but keep them private.
277   template <class U> bool operator==(WeakPtr<U> const&) const;
278   template <class U> bool operator!=(WeakPtr<U> const&) const;
279
280   friend class cef_internal::SupportsWeakPtrBase;
281   template <typename U> friend class WeakPtr;
282   friend class SupportsWeakPtr<T>;
283   friend class WeakPtrFactory<T>;
284
285   WeakPtr(const cef_internal::WeakReference& ref, T* ptr)
286       : WeakPtrBase(ref),
287         ptr_(ptr) {
288   }
289
290   // This pointer is only valid when ref_.is_valid() is true.  Otherwise, its
291   // value is undefined (as opposed to NULL).
292   T* ptr_;
293 };
294
295 // A class may be composed of a WeakPtrFactory and thereby
296 // control how it exposes weak pointers to itself.  This is helpful if you only
297 // need weak pointers within the implementation of a class.  This class is also
298 // useful when working with primitive types.  For example, you could have a
299 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
300 template <class T>
301 class WeakPtrFactory {
302  public:
303   explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {
304   }
305
306   ~WeakPtrFactory() {
307     ptr_ = NULL;
308   }
309
310   WeakPtr<T> GetWeakPtr() {
311     DCHECK(ptr_);
312     return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
313   }
314
315   // Call this method to invalidate all existing weak pointers.
316   void InvalidateWeakPtrs() {
317     DCHECK(ptr_);
318     weak_reference_owner_.Invalidate();
319   }
320
321   // Call this method to determine if any weak pointers exist.
322   bool HasWeakPtrs() const {
323     DCHECK(ptr_);
324     return weak_reference_owner_.HasRefs();
325   }
326
327  private:
328   cef_internal::WeakReferenceOwner weak_reference_owner_;
329   T* ptr_;
330   DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
331 };
332
333 // A class may extend from SupportsWeakPtr to let others take weak pointers to
334 // it. This avoids the class itself implementing boilerplate to dispense weak
335 // pointers.  However, since SupportsWeakPtr's destructor won't invalidate
336 // weak pointers to the class until after the derived class' members have been
337 // destroyed, its use can lead to subtle use-after-destroy issues.
338 template <class T>
339 class SupportsWeakPtr : public cef_internal::SupportsWeakPtrBase {
340  public:
341   SupportsWeakPtr() {}
342
343   WeakPtr<T> AsWeakPtr() {
344     return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
345   }
346
347  protected:
348   ~SupportsWeakPtr() {}
349
350  private:
351   cef_internal::WeakReferenceOwner weak_reference_owner_;
352   DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
353 };
354
355 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
356 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
357 // extends a Base that extends SupportsWeakPtr<Base>.
358 //
359 // EXAMPLE:
360 //   class Base : public base::SupportsWeakPtr<Producer> {};
361 //   class Derived : public Base {};
362 //
363 //   Derived derived;
364 //   base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
365 //
366 // Note that the following doesn't work (invalid type conversion) since
367 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
368 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
369 // the caller.
370 //
371 //   base::WeakPtr<Derived> ptr = derived.AsWeakPtr();  // Fails.
372
373 template <typename Derived>
374 WeakPtr<Derived> AsWeakPtr(Derived* t) {
375   return cef_internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
376 }
377
378 }  // namespace base
379
380 #endif  // !BUILDING_CEF_SHARED
381
382 #endif  // CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_