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.
5 #ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_
6 #define BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_
12 #include "base/base_export.h"
13 #include "base/basictypes.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/message_loop/message_pump.h"
16 #include "base/message_loop/message_pump_dispatcher.h"
17 #include "base/observer_list.h"
18 #include "base/time/time.h"
19 #include "base/win/scoped_handle.h"
25 // MessagePumpWin serves as the base for specialized versions of the MessagePump
26 // for Windows. It provides basic functionality like handling of observers and
27 // controlling the lifetime of the message pump.
28 class BASE_EXPORT MessagePumpWin
: public MessagePump
{
30 MessagePumpWin() : have_work_(0), state_(NULL
) {}
32 // Like MessagePump::Run, but MSG objects are routed through dispatcher.
33 void RunWithDispatcher(Delegate
* delegate
, MessagePumpDispatcher
* dispatcher
);
35 // MessagePump methods:
36 void Run(Delegate
* delegate
) override
;
42 MessagePumpDispatcher
* dispatcher
;
44 // Used to flag that the current Run() invocation should return ASAP.
47 // Used to count how many Run() invocations are on the stack.
51 virtual void DoRunLoop() = 0;
52 int GetCurrentDelay() const;
54 // The time at which delayed work should run.
55 TimeTicks delayed_work_time_
;
57 // A boolean value used to indicate if there is a kMsgDoWork message pending
58 // in the Windows Message queue. There is at most one such message, and it
59 // can drive execution of tasks when a native message pump is running.
62 // State for the current invocation of Run.
66 //-----------------------------------------------------------------------------
67 // MessagePumpForUI extends MessagePumpWin with methods that are particular to a
68 // MessageLoop instantiated with TYPE_UI.
70 // MessagePumpForUI implements a "traditional" Windows message pump. It contains
71 // a nearly infinite loop that peeks out messages, and then dispatches them.
72 // Intermixed with those peeks are callouts to DoWork for pending tasks, and
73 // DoDelayedWork for pending timers. When there are no events to be serviced,
74 // this pump goes into a wait state. In most cases, this message pump handles
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.
84 // The basic structure of the extension (refered 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
87 // made for an extended set of events, including the availability of Tasks to
90 // After running a task, the special message kMsgHaveWork is again posted to
91 // the Windows Message queue, ensuring a future time slice for processing a
92 // future event. To prevent flooding the Windows Message queue, care is taken
93 // to be sure that at most one kMsgHaveWork message is EVER pending in the
94 // Window's Message queue.
96 // There are a few additional complexities in this system where, when there are
97 // no Tasks to run, this otherwise infinite stream of messages which drives the
98 // sub-pump is halted. The pump is automatically re-started when Tasks are
101 // A second complexity is that the presence of this stream of posted tasks may
102 // prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER.
103 // Such paint and timer events always give priority to a posted message, such as
104 // kMsgHaveWork messages. As a result, care is taken to do some peeking in
105 // between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork
106 // is peeked, and before a replacement kMsgHaveWork is posted).
108 // NOTE: Although it may seem odd that messages are used to start and stop this
109 // flow (as opposed to signaling objects, etc.), it should be understood that
110 // the native message pump will *only* respond to messages. As a result, it is
111 // an excellent choice. It is also helpful that the starter messages that are
112 // placed in the queue when new task arrive also awakens DoRunLoop.
114 class BASE_EXPORT MessagePumpForUI
: public MessagePumpWin
{
116 // The application-defined code passed to the hook procedure.
117 static const int kMessageFilterCode
= 0x5001;
120 ~MessagePumpForUI() override
;
122 // MessagePump methods:
123 void ScheduleWork() override
;
124 void ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) override
;
127 static LRESULT CALLBACK
WndProcThunk(HWND window_handle
,
131 void DoRunLoop() override
;
132 void InitMessageWnd();
134 void HandleWorkMessage();
135 void HandleTimerMessage();
136 void RescheduleTimer();
137 bool ProcessNextWindowsMessage();
138 bool ProcessMessageHelper(const MSG
& msg
);
139 bool ProcessPumpReplacementMessage();
141 // We spawn a worker thread to periodically post (3 ms) the kMsgHaveWork
142 // message to the UI message pump. This is to ensure that the main thread
143 // gets to process tasks and delayed tasks when there is no activity in the
144 // Windows message pump or when there is a nested modal loop (sizing/moving/
145 // drag drop/message boxes) etc.
146 void DoWorkerThreadRunLoop();
148 // This function is posted as part of a user mode APC to shutdown the worker
149 // thread when the main message pump is shutting down.
150 static void CALLBACK
ShutdownWorkerThread(ULONG_PTR param
);
152 // Helper function for posting the kMsgHaveWork message to wake up the pump
153 // for processing tasks.
154 void PostWorkMessage();
156 // Helper function to set the waitable timer used to wake up the UI worker
157 // thread for processing delayed tasks.
158 // |delay_ms| : The delay in milliseconds.
159 void SetWakeupTimer(int64 delay_ms
);
161 // Helper function to ensure that the message pump processes tasks and
163 void ScheduleWorkHelper();
165 // Atom representing the registered window class.
168 // A hidden message-only window.
171 // This thread is used to periodically wake up the main thread to process
173 scoped_ptr
<base::Thread
> ui_worker_thread_
;
175 // The UI worker thread waits on this timer indefinitely. When the main
176 // thread has tasks ready to be processed it sets the timer.
177 base::win::ScopedHandle ui_worker_thread_timer_
;
179 // This flag controls whether the UI worker thread sets the waitable timer
180 // to ensure that tasks missed in one timer iteration get picked in the
182 long force_fallback_timer_for_tasks_
;
185 //-----------------------------------------------------------------------------
186 // MessagePumpForIO extends MessagePumpWin with methods that are particular to a
187 // MessageLoop instantiated with TYPE_IO. This version of MessagePump does not
188 // deal with Windows mesagges, and instead has a Run loop based on Completion
189 // Ports so it is better suited for IO operations.
191 class BASE_EXPORT MessagePumpForIO
: public MessagePumpWin
{
195 // Clients interested in receiving OS notifications when asynchronous IO
196 // operations complete should implement this interface and register themselves
197 // with the message pump.
200 // // Use only when there are no user's buffers involved on the actual IO,
201 // // so that all the cleanup can be done by the message pump.
202 // class MyFile : public IOHandler {
205 // context_ = new IOContext;
206 // context_->handler = this;
207 // message_pump->RegisterIOHandler(file_, this);
211 // // By setting the handler to NULL, we're asking for this context
212 // // to be deleted when received, without calling back to us.
213 // context_->handler = NULL;
218 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
224 // // The only buffer required for this operation is the overlapped
226 // ConnectNamedPipe(file_, &context_->overlapped);
230 // IOContext* context_;
235 // class MyFile : public IOHandler {
238 // message_pump->RegisterIOHandler(file_, this);
240 // // Plus some code to make sure that this destructor is not called
241 // // while there are pending IO operations.
244 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
251 // IOContext* context = new IOContext;
252 // // This is not used for anything. It just prevents the context from
253 // // being considered "abandoned".
254 // context->handler = this;
255 // ReadFile(file_, buffer, num_bytes, &read, &context->overlapped);
261 // Same as the previous example, except that in order to deal with the
262 // requirement stated for the destructor, the class calls WaitForIOCompletion
263 // from the destructor to block until all IO finishes.
266 // message_pump->WaitForIOCompletion(INFINITE, this);
271 virtual ~IOHandler() {}
272 // This will be called once the pending IO operation associated with
273 // |context| completes. |error| is the Win32 error code of the IO operation
274 // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero
276 virtual void OnIOCompleted(IOContext
* context
, DWORD bytes_transfered
,
280 // An IOObserver is an object that receives IO notifications from the
283 // NOTE: An IOObserver implementation should be extremely fast!
288 virtual void WillProcessIOEvent() = 0;
289 virtual void DidProcessIOEvent() = 0;
292 virtual ~IOObserver() {}
295 // The extended context that should be used as the base structure on every
296 // overlapped IO operation. |handler| must be set to the registered IOHandler
297 // for the given file when the operation is started, and it can be set to NULL
298 // before the operation completes to indicate that the handler should not be
299 // called anymore, and instead, the IOContext should be deleted when the OS
300 // notifies the completion of this operation. Please remember that any buffers
301 // involved with an IO operation should be around until the callback is
302 // received, so this technique can only be used for IO that do not involve
303 // additional buffers (other than the overlapped structure itself).
305 OVERLAPPED overlapped
;
310 ~MessagePumpForIO() override
;
312 // MessagePump methods:
313 void ScheduleWork() override
;
314 void ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) override
;
316 // Register the handler to be used when asynchronous IO for the given file
317 // completes. The registration persists as long as |file_handle| is valid, so
318 // |handler| must be valid as long as there is pending IO for the given file.
319 void RegisterIOHandler(HANDLE file_handle
, IOHandler
* handler
);
321 // Register the handler to be used to process job events. The registration
322 // persists as long as the job object is live, so |handler| must be valid
323 // until the job object is destroyed. Returns true if the registration
324 // succeeded, and false otherwise.
325 bool RegisterJobObject(HANDLE job_handle
, IOHandler
* handler
);
327 // Waits for the next IO completion that should be processed by |filter|, for
328 // up to |timeout| milliseconds. Return true if any IO operation completed,
329 // regardless of the involved handler, and false if the timeout expired. If
330 // the completion port received any message and the involved IO handler
331 // matches |filter|, the callback is called before returning from this code;
332 // if the handler is not the one that we are looking for, the callback will
333 // be postponed for another time, so reentrancy problems can be avoided.
334 // External use of this method should be reserved for the rare case when the
335 // caller is willing to allow pausing regular task dispatching on this thread.
336 bool WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
);
338 void AddIOObserver(IOObserver
* obs
);
339 void RemoveIOObserver(IOObserver
* obs
);
345 DWORD bytes_transfered
;
348 // In some cases |context| can be a non-pointer value casted to a pointer.
349 // |has_valid_io_context| is true if |context| is a valid IOContext
350 // pointer, and false otherwise.
351 bool has_valid_io_context
;
354 void DoRunLoop() override
;
356 bool MatchCompletedIOItem(IOHandler
* filter
, IOItem
* item
);
357 bool GetIOItem(DWORD timeout
, IOItem
* item
);
358 bool ProcessInternalIOItem(const IOItem
& item
);
359 void WillProcessIOEvent();
360 void DidProcessIOEvent();
362 // Converts an IOHandler pointer to a completion port key.
363 // |has_valid_io_context| specifies whether completion packets posted to
364 // |handler| will have valid OVERLAPPED pointers.
365 static ULONG_PTR
HandlerToKey(IOHandler
* handler
, bool has_valid_io_context
);
367 // Converts a completion port key to an IOHandler pointer.
368 static IOHandler
* KeyToHandler(ULONG_PTR key
, bool* has_valid_io_context
);
370 // The completion port associated with this thread.
371 win::ScopedHandle port_
;
372 // This list will be empty almost always. It stores IO completions that have
373 // not been delivered yet because somebody was doing cleanup.
374 std::list
<IOItem
> completed_io_
;
376 ObserverList
<IOObserver
> io_observers_
;
381 #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_