Upload upstream chromium 69.0.3497
[platform/framework/web/chromium-efl.git] / base / run_loop.h
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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 BASE_RUN_LOOP_H_
6 #define BASE_RUN_LOOP_H_
7
8 #include <utility>
9 #include <vector>
10
11 #include "base/base_export.h"
12 #include "base/callback.h"
13 #include "base/containers/stack.h"
14 #include "base/macros.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/observer_list.h"
18 #include "base/sequence_checker.h"
19 #include "base/threading/thread_checker.h"
20 #include "build/build_config.h"
21
22 namespace base {
23 #if defined(OS_ANDROID)
24 class MessagePumpForUI;
25 #endif
26
27 #if defined(USE_EFL)
28 class MessagePumpForUIEfl;
29 #endif
30
31 #if defined(OS_IOS)
32 class MessagePumpUIApplication;
33 #endif
34
35 class SingleThreadTaskRunner;
36
37 // Helper class to run the RunLoop::Delegate associated with the current thread.
38 // A RunLoop::Delegate must have been bound to this thread (ref.
39 // RunLoop::RegisterDelegateForCurrentThread()) prior to using any of RunLoop's
40 // member and static methods unless explicitly indicated otherwise (e.g.
41 // IsRunning/IsNestedOnCurrentThread()). RunLoop::Run can only be called once
42 // per RunLoop lifetime. Create a RunLoop on the stack and call Run/Quit to run
43 // a nested RunLoop but please do not use nested loops in production code!
44 class BASE_EXPORT RunLoop {
45  public:
46   // The type of RunLoop: a kDefault RunLoop at the top-level (non-nested) will
47   // process system and application tasks assigned to its Delegate. When nested
48   // however a kDefault RunLoop will only process system tasks while a
49   // kNestableTasksAllowed RunLoop will continue to process application tasks
50   // even if nested.
51   //
52   // This is relevant in the case of recursive RunLoops. Some unwanted run loops
53   // may occur when using common controls or printer functions. By default,
54   // recursive task processing is disabled.
55   //
56   // In general, nestable RunLoops are to be avoided. They are dangerous and
57   // difficult to get right, so please use with extreme caution.
58   //
59   // A specific example where this makes a difference is:
60   // - The thread is running a RunLoop.
61   // - It receives a task #1 and executes it.
62   // - The task #1 implicitly starts a RunLoop, like a MessageBox in the unit
63   //   test. This can also be StartDoc or GetSaveFileName.
64   // - The thread receives a task #2 before or while in this second RunLoop.
65   // - With a kNestableTasksAllowed RunLoop, the task #2 will run right away.
66   //   Otherwise, it will get executed right after task #1 completes in the main
67   //   RunLoop.
68   enum class Type {
69     kDefault,
70     kNestableTasksAllowed,
71   };
72
73   RunLoop(Type type = Type::kDefault);
74   ~RunLoop();
75
76   // Run the current RunLoop::Delegate. This blocks until Quit is called. Before
77   // calling Run, be sure to grab the QuitClosure in order to stop the
78   // RunLoop::Delegate asynchronously.
79   void Run();
80
81   // Run the current RunLoop::Delegate until it doesn't find any tasks or
82   // messages in its queue (it goes idle). WARNING: This may never return! Only
83   // use this when repeating tasks such as animated web pages have been shut
84   // down.
85   void RunUntilIdle();
86
87   bool running() const {
88     DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
89     return running_;
90   }
91
92   // Quit() quits an earlier call to Run() immediately. QuitWhenIdle() quits an
93   // earlier call to Run() when there aren't any tasks or messages in the queue.
94   //
95   // These methods are thread-safe but note that Quit() is best-effort when
96   // called from another thread (will quit soon but tasks that were already
97   // queued on this RunLoop will get to run first).
98   //
99   // There can be other nested RunLoops servicing the same task queue. Quitting
100   // one RunLoop has no bearing on the others. Quit() and QuitWhenIdle() can be
101   // called before, during or after Run(). If called before Run(), Run() will
102   // return immediately when called. Calling Quit() or QuitWhenIdle() after the
103   // RunLoop has already finished running has no effect.
104   //
105   // WARNING: You must NEVER assume that a call to Quit() or QuitWhenIdle() will
106   // terminate the targetted message loop. If a nested RunLoop continues
107   // running, the target may NEVER terminate. It is very easy to livelock (run
108   // forever) in such a case.
109   void Quit();
110   void QuitWhenIdle();
111
112   // Convenience methods to get a closure that safely calls Quit() or
113   // QuitWhenIdle() (has no effect if the RunLoop instance is gone).
114   //
115   // The resulting Closure is thread-safe (note however that invoking the
116   // QuitClosure() from another thread than this RunLoop's will result in an
117   // asynchronous rather than immediate Quit()).
118   //
119   // Example:
120   //   RunLoop run_loop;
121   //   PostTask(run_loop.QuitClosure());
122   //   run_loop.Run();
123   base::Closure QuitClosure();
124   base::Closure QuitWhenIdleClosure();
125
126   // Returns true if there is an active RunLoop on this thread.
127   // Safe to call before RegisterDelegateForCurrentThread().
128   static bool IsRunningOnCurrentThread();
129
130   // Returns true if there is an active RunLoop on this thread and it's nested
131   // within another active RunLoop.
132   // Safe to call before RegisterDelegateForCurrentThread().
133   static bool IsNestedOnCurrentThread();
134
135   // A NestingObserver is notified when a nested RunLoop begins and ends.
136   class BASE_EXPORT NestingObserver {
137    public:
138     // Notified before a nested loop starts running work on the current thread.
139     virtual void OnBeginNestedRunLoop() = 0;
140     // Notified after a nested loop is done running work on the current thread.
141     virtual void OnExitNestedRunLoop() {}
142
143    protected:
144     virtual ~NestingObserver() = default;
145   };
146
147   static void AddNestingObserverOnCurrentThread(NestingObserver* observer);
148   static void RemoveNestingObserverOnCurrentThread(NestingObserver* observer);
149
150   // A RunLoop::Delegate is a generic interface that allows RunLoop to be
151   // separate from the underlying implementation of the message loop for this
152   // thread. It holds private state used by RunLoops on its associated thread.
153   // One and only one RunLoop::Delegate must be registered on a given thread
154   // via RunLoop::RegisterDelegateForCurrentThread() before RunLoop instances
155   // and RunLoop static methods can be used on it.
156   class BASE_EXPORT Delegate {
157    public:
158     Delegate();
159     virtual ~Delegate();
160
161     // Used by RunLoop to inform its Delegate to Run/Quit. Implementations are
162     // expected to keep on running synchronously from the Run() call until the
163     // eventual matching Quit() call. Upon receiving a Quit() call it should
164     // return from the Run() call as soon as possible without executing
165     // remaining tasks/messages. Run() calls can nest in which case each Quit()
166     // call should result in the topmost active Run() call returning. The only
167     // other trigger for Run() to return is the
168     // |should_quit_when_idle_callback_| which the Delegate should probe before
169     // sleeping when it becomes idle. |application_tasks_allowed| is true if
170     // this is the first Run() call on the stack or it was made from a nested
171     // RunLoop of Type::kNestableTasksAllowed (otherwise this Run() level should
172     // only process system tasks).
173     virtual void Run(bool application_tasks_allowed) = 0;
174     virtual void Quit() = 0;
175
176     // Invoked right before a RunLoop enters a nested Run() call on this
177     // Delegate iff this RunLoop is of type kNestableTasksAllowed. The Delegate
178     // should ensure that the upcoming Run() call will result in processing
179     // application tasks queued ahead of it without further probing. e.g.
180     // message pumps on some platforms, like Mac, need an explicit request to
181     // process application tasks when nested, otherwise they'll only wait for
182     // system messages.
183     virtual void EnsureWorkScheduled() = 0;
184
185    protected:
186     // Returns the result of this Delegate's |should_quit_when_idle_callback_|.
187     // "protected" so it can be invoked only by the Delegate itself.
188     bool ShouldQuitWhenIdle();
189
190    private:
191     // While the state is owned by the Delegate subclass, only RunLoop can use
192     // it.
193     friend class RunLoop;
194
195     // A vector-based stack is more memory efficient than the default
196     // deque-based stack as the active RunLoop stack isn't expected to ever
197     // have more than a few entries.
198     using RunLoopStack = base::stack<RunLoop*, std::vector<RunLoop*>>;
199
200     RunLoopStack active_run_loops_;
201     ObserverList<RunLoop::NestingObserver> nesting_observers_;
202
203 #if DCHECK_IS_ON()
204     bool allow_running_for_testing_ = true;
205 #endif
206
207     // True once this Delegate is bound to a thread via
208     // RegisterDelegateForCurrentThread().
209     bool bound_ = false;
210
211     // Thread-affine per its use of TLS.
212     THREAD_CHECKER(bound_thread_checker_);
213
214     DISALLOW_COPY_AND_ASSIGN(Delegate);
215   };
216
217   // Registers |delegate| on the current thread. Must be called once and only
218   // once per thread before using RunLoop methods on it. |delegate| is from then
219   // on forever bound to that thread (including its destruction).
220   static void RegisterDelegateForCurrentThread(Delegate* delegate);
221
222   // Quits the active RunLoop (when idle) -- there must be one. These were
223   // introduced as prefered temporary replacements to the long deprecated
224   // MessageLoop::Quit(WhenIdle)(Closure) methods. Callers should properly plumb
225   // a reference to the appropriate RunLoop instance (or its QuitClosure)
226   // instead of using these in order to link Run()/Quit() to a single RunLoop
227   // instance and increase readability.
228   static void QuitCurrentDeprecated();
229   static void QuitCurrentWhenIdleDeprecated();
230   static Closure QuitCurrentWhenIdleClosureDeprecated();
231
232   // Run() will DCHECK if called while there's a ScopedDisallowRunningForTesting
233   // in scope on its thread. This is useful to add safety to some test
234   // constructs which allow multiple task runners to share the main thread in
235   // unit tests. While the main thread can be shared by multiple runners to
236   // deterministically fake multi threading, there can still only be a single
237   // RunLoop::Delegate per thread and RunLoop::Run() should only be invoked from
238   // it (or it would result in incorrectly driving TaskRunner A while in
239   // TaskRunner B's context).
240   class BASE_EXPORT ScopedDisallowRunningForTesting {
241    public:
242     ScopedDisallowRunningForTesting();
243     ~ScopedDisallowRunningForTesting();
244
245    private:
246 #if DCHECK_IS_ON()
247     Delegate* current_delegate_;
248     const bool previous_run_allowance_;
249 #endif  // DCHECK_IS_ON()
250
251     DISALLOW_COPY_AND_ASSIGN(ScopedDisallowRunningForTesting);
252   };
253
254  private:
255   FRIEND_TEST_ALL_PREFIXES(MessageLoopTypedTest, RunLoopQuitOrderAfter);
256
257 #if defined(OS_ANDROID)
258   // Android doesn't support the blocking RunLoop::Run, so it calls
259   // BeforeRun and AfterRun directly.
260   friend class base::MessagePumpForUI;
261 #endif
262
263 #if defined(USE_EFL)
264   // EFL doesn't support the blocking RunLoop::Run, so it calls
265   // BeforeRun directly.
266   friend class base::MessagePumpForUIEfl;
267 #endif
268
269 #if defined(OS_IOS)
270   // iOS doesn't support the blocking RunLoop::Run, so it calls
271   // BeforeRun directly.
272   friend class base::MessagePumpUIApplication;
273 #endif
274
275   // Return false to abort the Run.
276   bool BeforeRun();
277   void AfterRun();
278
279   // A copy of RunLoop::Delegate for the thread driven by tis RunLoop for quick
280   // access without using TLS (also allows access to state from another sequence
281   // during Run(), ref. |sequence_checker_| below).
282   Delegate* delegate_;
283
284   const Type type_;
285
286 #if DCHECK_IS_ON()
287   bool run_called_ = false;
288 #endif
289
290   bool quit_called_ = false;
291   bool running_ = false;
292   // Used to record that QuitWhenIdle() was called on this RunLoop, meaning that
293   // the Delegate should quit Run() once it becomes idle (it's responsible for
294   // probing this state via ShouldQuitWhenIdle()). This state is stored here
295   // rather than pushed to Delegate to support nested RunLoops.
296   bool quit_when_idle_received_ = false;
297
298   // True if use of QuitCurrent*Deprecated() is allowed. Taking a Quit*Closure()
299   // from a RunLoop implicitly sets this to false, so QuitCurrent*Deprecated()
300   // cannot be used while that RunLoop is being Run().
301   bool allow_quit_current_deprecated_ = true;
302
303   // RunLoop is not thread-safe. Its state/methods, unless marked as such, may
304   // not be accessed from any other sequence than the thread it was constructed
305   // on. Exception: RunLoop can be safely accessed from one other sequence (or
306   // single parallel task) during Run() -- e.g. to Quit() without having to
307   // plumb ThreatTaskRunnerHandle::Get() throughout a test to repost QuitClosure
308   // to origin thread.
309   SEQUENCE_CHECKER(sequence_checker_);
310
311   const scoped_refptr<SingleThreadTaskRunner> origin_task_runner_;
312
313   // WeakPtrFactory for QuitClosure safety.
314   base::WeakPtrFactory<RunLoop> weak_factory_;
315
316   DISALLOW_COPY_AND_ASSIGN(RunLoop);
317 };
318
319 }  // namespace base
320
321 #endif  // BASE_RUN_LOOP_H_