message_pump_win.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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_WIN_H_
  5. #define BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_
  6. #include <windows.h>
  7. #include <atomic>
  8. #include <memory>
  9. #include "base/base_export.h"
  10. #include "base/compiler_specific.h"
  11. #include "base/location.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/message_loop/message_pump.h"
  14. #include "base/observer_list.h"
  15. #include "base/threading/thread_checker.h"
  16. #include "base/time/time.h"
  17. #include "base/win/message_window.h"
  18. #include "base/win/scoped_handle.h"
  19. #include "third_party/abseil-cpp/absl/types/optional.h"
  20. namespace base {
  21. // MessagePumpWin serves as the base for specialized versions of the MessagePump
  22. // for Windows. It provides basic functionality like handling of observers and
  23. // controlling the lifetime of the message pump.
  24. class BASE_EXPORT MessagePumpWin : public MessagePump {
  25. public:
  26. MessagePumpWin();
  27. ~MessagePumpWin() override;
  28. // MessagePump methods:
  29. void Run(Delegate* delegate) override;
  30. void Quit() override;
  31. protected:
  32. struct RunState {
  33. explicit RunState(Delegate* delegate_in) : delegate(delegate_in) {}
  34. const raw_ptr<Delegate> delegate;
  35. // Used to flag that the current Run() invocation should return ASAP.
  36. bool should_quit = false;
  37. // Set to true if this Run() is nested within another Run().
  38. bool is_nested = false;
  39. };
  40. virtual void DoRunLoop() = 0;
  41. // True iff:
  42. // * MessagePumpForUI: there's a kMsgDoWork message pending in the Windows
  43. // Message queue. i.e. when:
  44. // a. The pump is about to wakeup from idle.
  45. // b. The pump is about to enter a nested native loop and a
  46. // ScopedNestableTaskAllower was instantiated to allow application
  47. // tasks to execute in that nested loop (ScopedNestableTaskAllower
  48. // invokes ScheduleWork()).
  49. // c. While in a native (nested) loop : HandleWorkMessage() =>
  50. // ProcessPumpReplacementMessage() invokes ScheduleWork() before
  51. // processing a native message to guarantee this pump will get another
  52. // time slice if it goes into native Windows code and enters a native
  53. // nested loop. This is different from (b.) because we're not yet
  54. // processing an application task at the current run level and
  55. // therefore are expected to keep pumping application tasks without
  56. // necessitating a ScopedNestableTaskAllower.
  57. //
  58. // * MessagePumpforIO: there's a dummy IO completion item with |this| as an
  59. // lpCompletionKey in the queue which is about to wakeup
  60. // WaitForIOCompletion(). MessagePumpForIO doesn't support nesting so
  61. // this is simpler than MessagePumpForUI.
  62. std::atomic_bool work_scheduled_{false};
  63. // State for the current invocation of Run(). null if not running.
  64. RunState* run_state_ = nullptr;
  65. THREAD_CHECKER(bound_thread_);
  66. };
  67. //-----------------------------------------------------------------------------
  68. // MessagePumpForUI extends MessagePumpWin with methods that are particular to a
  69. // MessageLoop instantiated with TYPE_UI.
  70. //
  71. // MessagePumpForUI implements a "traditional" Windows message pump. It contains
  72. // a nearly infinite loop that peeks out messages, and then dispatches them.
  73. // Intermixed with those peeks are callouts to DoWork. When there are no
  74. // events to be serviced, this pump goes into a wait state. In most cases, this
  75. // message pump handles all processing.
  76. //
  77. // However, when a task, or windows event, invokes on the stack a native dialog
  78. // box or such, that window typically provides a bare bones (native?) message
  79. // pump. That bare-bones message pump generally supports little more than a
  80. // peek of the Windows message queue, followed by a dispatch of the peeked
  81. // message. MessageLoop extends that bare-bones message pump to also service
  82. // Tasks, at the cost of some complexity.
  83. //
  84. // The basic structure of the extension (referred to as a sub-pump) is that a
  85. // special message, kMsgHaveWork, is repeatedly injected into the Windows
  86. // Message queue. Each time the kMsgHaveWork message is peeked, checks are made
  87. // for an extended set of events, including the availability of Tasks to run.
  88. //
  89. // After running a task, the special message kMsgHaveWork is again posted to the
  90. // Windows Message queue, ensuring a future time slice for processing a future
  91. // event. To prevent flooding the Windows Message queue, care is taken to be
  92. // sure that at most one kMsgHaveWork message is EVER pending in the Window's
  93. // Message queue.
  94. //
  95. // There are a few additional complexities in this system where, when there are
  96. // no Tasks to run, this otherwise infinite stream of messages which drives the
  97. // sub-pump is halted. The pump is automatically re-started when Tasks are
  98. // queued.
  99. //
  100. // A second complexity is that the presence of this stream of posted tasks may
  101. // prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER.
  102. // Such paint and timer events always give priority to a posted message, such as
  103. // kMsgHaveWork messages. As a result, care is taken to do some peeking in
  104. // between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork is
  105. // peeked, and before a replacement kMsgHaveWork is posted).
  106. //
  107. // NOTE: Although it may seem odd that messages are used to start and stop this
  108. // flow (as opposed to signaling objects, etc.), it should be understood that
  109. // the native message pump will *only* respond to messages. As a result, it is
  110. // an excellent choice. It is also helpful that the starter messages that are
  111. // placed in the queue when new task arrive also awakens DoRunLoop.
  112. //
  113. class BASE_EXPORT MessagePumpForUI : public MessagePumpWin {
  114. public:
  115. MessagePumpForUI();
  116. ~MessagePumpForUI() override;
  117. // MessagePump methods:
  118. void ScheduleWork() override;
  119. void ScheduleDelayedWork(
  120. const Delegate::NextWorkInfo& next_work_info) override;
  121. // An observer interface to give the scheduler an opportunity to log
  122. // information about MSGs before and after they are dispatched.
  123. class BASE_EXPORT Observer {
  124. public:
  125. virtual void WillDispatchMSG(const MSG& msg) = 0;
  126. virtual void DidDispatchMSG(const MSG& msg) = 0;
  127. };
  128. void AddObserver(Observer* observer);
  129. void RemoveObserver(Observer* obseerver);
  130. private:
  131. bool MessageCallback(UINT message,
  132. WPARAM wparam,
  133. LPARAM lparam,
  134. LRESULT* result);
  135. void DoRunLoop() override;
  136. NOINLINE void NOT_TAIL_CALLED
  137. WaitForWork(Delegate::NextWorkInfo next_work_info);
  138. void HandleWorkMessage();
  139. void HandleTimerMessage();
  140. void ScheduleNativeTimer(Delegate::NextWorkInfo next_work_info);
  141. void KillNativeTimer();
  142. bool ProcessNextWindowsMessage();
  143. bool ProcessMessageHelper(const MSG& msg);
  144. bool ProcessPumpReplacementMessage();
  145. base::win::MessageWindow message_window_;
  146. // Non-nullopt if there's currently a native timer installed. If so, it
  147. // indicates when the timer is set to fire and can be used to avoid setting
  148. // redundant timers.
  149. absl::optional<TimeTicks> installed_native_timer_;
  150. // This will become true when a native loop takes our kMsgHaveWork out of the
  151. // system queue. It will be reset to false whenever DoRunLoop regains control.
  152. // Used to decide whether ScheduleDelayedWork() should start a native timer.
  153. bool in_native_loop_ = false;
  154. ObserverList<Observer>::Unchecked observers_;
  155. };
  156. //-----------------------------------------------------------------------------
  157. // MessagePumpForIO extends MessagePumpWin with methods that are particular to a
  158. // MessageLoop instantiated with TYPE_IO. This version of MessagePump does not
  159. // deal with Windows mesagges, and instead has a Run loop based on Completion
  160. // Ports so it is better suited for IO operations.
  161. //
  162. class BASE_EXPORT MessagePumpForIO : public MessagePumpWin {
  163. public:
  164. struct BASE_EXPORT IOContext {
  165. IOContext();
  166. OVERLAPPED overlapped;
  167. };
  168. // Clients interested in receiving OS notifications when asynchronous IO
  169. // operations complete should implement this interface and register themselves
  170. // with the message pump.
  171. //
  172. // Typical use #1:
  173. // class MyFile : public IOHandler {
  174. // MyFile() : IOHandler(FROM_HERE) {
  175. // ...
  176. // message_pump->RegisterIOHandler(file_, this);
  177. // }
  178. // // Plus some code to make sure that this destructor is not called
  179. // // while there are pending IO operations.
  180. // ~MyFile() {
  181. // }
  182. // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
  183. // DWORD error) {
  184. // ...
  185. // delete context;
  186. // }
  187. // void DoSomeIo() {
  188. // ...
  189. // IOContext* context = new IOContext;
  190. // ReadFile(file_, buffer, num_bytes, &read, &context);
  191. // }
  192. // HANDLE file_;
  193. // };
  194. //
  195. // Typical use #2:
  196. // Same as the previous example, except that in order to deal with the
  197. // requirement stated for the destructor, the class calls WaitForIOCompletion
  198. // from the destructor to block until all IO finishes.
  199. // ~MyFile() {
  200. // while(pending_)
  201. // message_pump->WaitForIOCompletion(INFINITE, this);
  202. // }
  203. //
  204. class BASE_EXPORT IOHandler {
  205. public:
  206. explicit IOHandler(const Location& from_here);
  207. virtual ~IOHandler();
  208. IOHandler(const IOHandler&) = delete;
  209. IOHandler& operator=(const IOHandler&) = delete;
  210. // This will be called once the pending IO operation associated with
  211. // |context| completes. |error| is the Win32 error code of the IO operation
  212. // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero
  213. // on error.
  214. virtual void OnIOCompleted(IOContext* context,
  215. DWORD bytes_transfered,
  216. DWORD error) = 0;
  217. const Location& io_handler_location() { return io_handler_location_; }
  218. private:
  219. const Location io_handler_location_;
  220. };
  221. MessagePumpForIO();
  222. ~MessagePumpForIO() override;
  223. // MessagePump methods:
  224. void ScheduleWork() override;
  225. void ScheduleDelayedWork(
  226. const Delegate::NextWorkInfo& next_work_info) override;
  227. // Register the handler to be used when asynchronous IO for the given file
  228. // completes. The registration persists as long as |file_handle| is valid, so
  229. // |handler| must be valid as long as there is pending IO for the given file.
  230. HRESULT RegisterIOHandler(HANDLE file_handle, IOHandler* handler);
  231. // Register the handler to be used to process job events. The registration
  232. // persists as long as the job object is live, so |handler| must be valid
  233. // until the job object is destroyed. Returns true if the registration
  234. // succeeded, and false otherwise.
  235. bool RegisterJobObject(HANDLE job_handle, IOHandler* handler);
  236. private:
  237. struct IOItem {
  238. raw_ptr<IOHandler> handler;
  239. raw_ptr<IOContext> context;
  240. DWORD bytes_transfered;
  241. DWORD error;
  242. };
  243. void DoRunLoop() override;
  244. NOINLINE void NOT_TAIL_CALLED
  245. WaitForWork(Delegate::NextWorkInfo next_work_info);
  246. bool GetIOItem(DWORD timeout, IOItem* item);
  247. bool ProcessInternalIOItem(const IOItem& item);
  248. // Waits for the next IO completion for up to |timeout| milliseconds.
  249. // Return true if any IO operation completed, and false if the timeout
  250. // expired. If the completion port received any messages, the associated
  251. // handlers will have been invoked before returning from this code.
  252. bool WaitForIOCompletion(DWORD timeout);
  253. // The completion port associated with this thread.
  254. win::ScopedHandle port_;
  255. };
  256. } // namespace base
  257. #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_