message_pump.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. #ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMP_H_
  5. #define BASE_MESSAGE_LOOP_MESSAGE_PUMP_H_
  6. #include "base/base_export.h"
  7. #include "base/check_op.h"
  8. #include "base/message_loop/message_pump_type.h"
  9. #include "base/message_loop/timer_slack.h"
  10. #include "base/sequence_checker.h"
  11. #include "base/time/time.h"
  12. #include "build/build_config.h"
  13. namespace base {
  14. class TimeTicks;
  15. class BASE_EXPORT MessagePump {
  16. public:
  17. using MessagePumpFactory = std::unique_ptr<MessagePump>();
  18. // Uses the given base::MessagePumpFactory to override the default MessagePump
  19. // implementation for 'MessagePumpType::UI'. May only be called once.
  20. static void OverrideMessagePumpForUIFactory(MessagePumpFactory* factory);
  21. // Returns true if the MessagePumpForUI has been overidden.
  22. static bool IsMessagePumpForUIFactoryOveridden();
  23. // Creates the default MessagePump based on |type|. Caller owns return value.
  24. static std::unique_ptr<MessagePump> Create(MessagePumpType type);
  25. // Please see the comments above the Run method for an illustration of how
  26. // these delegate methods are used.
  27. class BASE_EXPORT Delegate {
  28. public:
  29. virtual ~Delegate() = default;
  30. // Called before a unit of work internal to the message pump is executed.
  31. // This allows reports about individual units of work to be produced. The
  32. // unit of work ends when BeforeDoInternalWork() is called again, or when
  33. // BeforeWait(), DoWork(), or DoIdleWork() is called.
  34. // TODO(crbug.com/851163): Place calls for all platforms.
  35. virtual void BeforeDoInternalWork() = 0;
  36. // Called before the message pump starts waiting for work.
  37. // This indicates the end of the current unit of work, which is required
  38. // to produce reports about individual units of work.
  39. virtual void BeforeWait() = 0;
  40. struct NextWorkInfo {
  41. // Helper to extract a TimeDelta for pumps that need a
  42. // timeout-till-next-task.
  43. TimeDelta remaining_delay() const {
  44. DCHECK(!delayed_run_time.is_null() && !delayed_run_time.is_max());
  45. DCHECK_GE(TimeTicks::Now(), recent_now);
  46. return delayed_run_time - recent_now;
  47. }
  48. // Helper to verify if the next task is ready right away.
  49. bool is_immediate() const { return delayed_run_time.is_null(); }
  50. // The next PendingTask's |delayed_run_time|. is_null() if there's extra
  51. // work to run immediately. is_max() if there are no more immediate nor
  52. // delayed tasks.
  53. TimeTicks delayed_run_time;
  54. // A recent view of TimeTicks::Now(). Only valid if |next_task_run_time|
  55. // isn't null nor max. MessagePump impls should use remaining_delay()
  56. // instead of resampling Now() if they wish to sleep for a TimeDelta.
  57. TimeTicks recent_now;
  58. };
  59. // Executes an immediate task or a ripe delayed task. Returns information
  60. // about when DoWork() should be called again. If the returned NextWorkInfo
  61. // is_immediate(), DoWork() must be invoked again shortly. Else, DoWork()
  62. // must be invoked at |NextWorkInfo::delayed_run_time| or when
  63. // ScheduleWork() is invoked, whichever comes first. Redundant/spurious
  64. // invocations of DoWork() outside of those requirements are tolerated.
  65. // DoIdleWork() will not be called so long as this returns a NextWorkInfo
  66. // which is_immediate().
  67. virtual NextWorkInfo DoWork() = 0;
  68. // Called from within Run just before the message pump goes to sleep.
  69. // Returns true to indicate that idle work was done. Returning false means
  70. // the pump will now wait.
  71. virtual bool DoIdleWork() = 0;
  72. };
  73. MessagePump();
  74. virtual ~MessagePump();
  75. // The Run method is called to enter the message pump's run loop.
  76. //
  77. // Within the method, the message pump is responsible for processing native
  78. // messages as well as for giving cycles to the delegate periodically. The
  79. // message pump should take care to mix delegate callbacks with native message
  80. // processing so neither type of event starves the other of cycles. Each call
  81. // to a delegate function or DoInternalWork() is considered the beginning of a
  82. // new "unit of work".
  83. //
  84. // The anatomy of a typical run loop:
  85. //
  86. // for (;;) {
  87. // bool did_internal_work = DoInternalWork();
  88. // if (should_quit_)
  89. // break;
  90. //
  91. // Delegate::NextWorkInfo next_work_info = delegate->DoWork();
  92. // if (should_quit_)
  93. // break;
  94. //
  95. // if (did_internal_work || next_work_info.is_immediate())
  96. // continue;
  97. //
  98. // bool did_idle_work = delegate_->DoIdleWork();
  99. // if (should_quit_)
  100. // break;
  101. //
  102. // if (did_idle_work)
  103. // continue;
  104. //
  105. // WaitForWork();
  106. // }
  107. //
  108. // Here, DoInternalWork is some private method of the message pump that is
  109. // responsible for dispatching the next UI message or notifying the next IO
  110. // completion (for example). WaitForWork is a private method that simply
  111. // blocks until there is more work of any type to do.
  112. //
  113. // Notice that the run loop cycles between calling DoInternalWork and DoWork
  114. // methods. This helps ensure that none of these work queues starve the
  115. // others. This is important for message pumps that are used to drive
  116. // animations, for example.
  117. //
  118. // Notice also that after each callout to foreign code, the run loop checks to
  119. // see if it should quit. The Quit method is responsible for setting this
  120. // flag. No further work is done once the quit flag is set.
  121. //
  122. // NOTE 1: Run may be called reentrantly from any of the callouts to foreign
  123. // code (internal work, DoWork, DoIdleWork). As a result, DoWork and
  124. // DoIdleWork must be reentrant.
  125. //
  126. // NOTE 2: Run implementations must arrange for DoWork to be invoked as
  127. // expected if a callout to foreign code enters a message pump outside their
  128. // control. For example, the MessageBox API on Windows pumps UI messages. If
  129. // the MessageBox API is called (indirectly) from within Run, it is expected
  130. // that DoWork will be invoked from within that call in response to
  131. // ScheduleWork or as requested by the last NextWorkInfo returned by DoWork.
  132. // The MessagePump::Delegate may then elect to do nested work or not depending
  133. // on its policy in that context. Regardless of that decision (and return
  134. // value of the nested DoWork() call), DoWork() will be invoked again when the
  135. // nested loop unwinds.
  136. virtual void Run(Delegate* delegate) = 0;
  137. // Quit immediately from the most recently entered run loop. This method may
  138. // only be used on the thread that called Run.
  139. virtual void Quit() = 0;
  140. // Schedule a DoWork callback to happen reasonably soon. Does nothing if a
  141. // DoWork callback is already scheduled. Once this call is made, DoWork is
  142. // guaranteed to be called repeatedly at least until it returns a
  143. // non-immediate NextWorkInfo. This call can be expensive and callers should
  144. // attempt not to invoke it again before a non-immediate NextWorkInfo was
  145. // returned from DoWork(). Thread-safe (and callers should avoid holding a
  146. // Lock at all cost while making this call as some platforms' priority
  147. // boosting features have been observed to cause the caller to get descheduled
  148. // : https://crbug.com/890978).
  149. virtual void ScheduleWork() = 0;
  150. // Schedule a DoWork callback to happen at the specified time, cancelling any
  151. // pending callback scheduled by this method. This method may only be used on
  152. // the thread that called Run.
  153. //
  154. // It isn't necessary to call this during normal execution, as the pump wakes
  155. // up as requested by the return value of DoWork().
  156. // TODO(crbug.com/885371): Determine if this must be called to ensure that
  157. // delayed tasks run when a message pump outside the control of Run is
  158. // entered.
  159. virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time) = 0;
  160. // Sets the timer slack to the specified value.
  161. virtual void SetTimerSlack(TimerSlack timer_slack);
  162. };
  163. } // namespace base
  164. #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_H_