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