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