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/message_loop/message_pump.h"
15 #include "base/message_loop/message_pump_dispatcher.h"
16 #include "base/observer_list.h"
17 #include "base/time/time.h"
18 #include "base/win/scoped_handle.h"
22 // MessagePumpWin serves as the base for specialized versions of the MessagePump
23 // for Windows. It provides basic functionality like handling of observers and
24 // controlling the lifetime of the message pump.
25 class BASE_EXPORT MessagePumpWin
: public MessagePump
{
27 MessagePumpWin() : have_work_(0), state_(NULL
) {}
29 // Like MessagePump::Run, but MSG objects are routed through dispatcher.
30 void RunWithDispatcher(Delegate
* delegate
, MessagePumpDispatcher
* dispatcher
);
32 // MessagePump methods:
33 void Run(Delegate
* delegate
) override
;
39 MessagePumpDispatcher
* dispatcher
;
41 // Used to flag that the current Run() invocation should return ASAP.
44 // Used to count how many Run() invocations are on the stack.
48 virtual void DoRunLoop() = 0;
49 int GetCurrentDelay() const;
51 // The time at which delayed work should run.
52 TimeTicks delayed_work_time_
;
54 // A boolean value used to indicate if there is a kMsgDoWork message pending
55 // in the Windows Message queue. There is at most one such message, and it
56 // can drive execution of tasks when a native message pump is running.
59 // State for the current invocation of Run.
63 //-----------------------------------------------------------------------------
64 // MessagePumpForUI extends MessagePumpWin with methods that are particular to a
65 // MessageLoop instantiated with TYPE_UI.
67 // MessagePumpForUI implements a "traditional" Windows message pump. It contains
68 // a nearly infinite loop that peeks out messages, and then dispatches them.
69 // Intermixed with those peeks are callouts to DoWork for pending tasks, and
70 // DoDelayedWork for pending timers. When there are no events to be serviced,
71 // this pump goes into a wait state. In most cases, this message pump handles
74 // However, when a task, or windows event, invokes on the stack a native dialog
75 // box or such, that window typically provides a bare bones (native?) message
76 // pump. That bare-bones message pump generally supports little more than a
77 // peek of the Windows message queue, followed by a dispatch of the peeked
78 // message. MessageLoop extends that bare-bones message pump to also service
79 // Tasks, at the cost of some complexity.
81 // The basic structure of the extension (refered to as a sub-pump) is that a
82 // special message, kMsgHaveWork, is repeatedly injected into the Windows
83 // Message queue. Each time the kMsgHaveWork message is peeked, checks are
84 // made for an extended set of events, including the availability of Tasks to
87 // After running a task, the special message kMsgHaveWork is again posted to
88 // the Windows Message queue, ensuring a future time slice for processing a
89 // future event. To prevent flooding the Windows Message queue, care is taken
90 // to be sure that at most one kMsgHaveWork message is EVER pending in the
91 // Window's Message queue.
93 // There are a few additional complexities in this system where, when there are
94 // no Tasks to run, this otherwise infinite stream of messages which drives the
95 // sub-pump is halted. The pump is automatically re-started when Tasks are
98 // A second complexity is that the presence of this stream of posted tasks may
99 // prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER.
100 // Such paint and timer events always give priority to a posted message, such as
101 // kMsgHaveWork messages. As a result, care is taken to do some peeking in
102 // between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork
103 // is peeked, and before a replacement kMsgHaveWork is posted).
105 // NOTE: Although it may seem odd that messages are used to start and stop this
106 // flow (as opposed to signaling objects, etc.), it should be understood that
107 // the native message pump will *only* respond to messages. As a result, it is
108 // an excellent choice. It is also helpful that the starter messages that are
109 // placed in the queue when new task arrive also awakens DoRunLoop.
111 class BASE_EXPORT MessagePumpForUI
: public MessagePumpWin
{
113 // The application-defined code passed to the hook procedure.
114 static const int kMessageFilterCode
= 0x5001;
117 ~MessagePumpForUI() override
;
119 // MessagePump methods:
120 void ScheduleWork() override
;
121 void ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) override
;
124 static LRESULT CALLBACK
WndProcThunk(HWND window_handle
,
128 void DoRunLoop() override
;
129 void InitMessageWnd();
131 void HandleWorkMessage();
132 void HandleTimerMessage();
133 bool ProcessNextWindowsMessage();
134 bool ProcessMessageHelper(const MSG
& msg
);
135 bool ProcessPumpReplacementMessage();
137 // Atom representing the registered window class.
140 // A hidden message-only window.
144 //-----------------------------------------------------------------------------
145 // MessagePumpForIO extends MessagePumpWin with methods that are particular to a
146 // MessageLoop instantiated with TYPE_IO. This version of MessagePump does not
147 // deal with Windows mesagges, and instead has a Run loop based on Completion
148 // Ports so it is better suited for IO operations.
150 class BASE_EXPORT MessagePumpForIO
: public MessagePumpWin
{
154 // Clients interested in receiving OS notifications when asynchronous IO
155 // operations complete should implement this interface and register themselves
156 // with the message pump.
159 // // Use only when there are no user's buffers involved on the actual IO,
160 // // so that all the cleanup can be done by the message pump.
161 // class MyFile : public IOHandler {
164 // context_ = new IOContext;
165 // context_->handler = this;
166 // message_pump->RegisterIOHandler(file_, this);
170 // // By setting the handler to NULL, we're asking for this context
171 // // to be deleted when received, without calling back to us.
172 // context_->handler = NULL;
177 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
183 // // The only buffer required for this operation is the overlapped
185 // ConnectNamedPipe(file_, &context_->overlapped);
189 // IOContext* context_;
194 // class MyFile : public IOHandler {
197 // message_pump->RegisterIOHandler(file_, this);
199 // // Plus some code to make sure that this destructor is not called
200 // // while there are pending IO operations.
203 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
210 // IOContext* context = new IOContext;
211 // // This is not used for anything. It just prevents the context from
212 // // being considered "abandoned".
213 // context->handler = this;
214 // ReadFile(file_, buffer, num_bytes, &read, &context->overlapped);
220 // Same as the previous example, except that in order to deal with the
221 // requirement stated for the destructor, the class calls WaitForIOCompletion
222 // from the destructor to block until all IO finishes.
225 // message_pump->WaitForIOCompletion(INFINITE, this);
230 virtual ~IOHandler() {}
231 // This will be called once the pending IO operation associated with
232 // |context| completes. |error| is the Win32 error code of the IO operation
233 // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero
235 virtual void OnIOCompleted(IOContext
* context
, DWORD bytes_transfered
,
239 // An IOObserver is an object that receives IO notifications from the
242 // NOTE: An IOObserver implementation should be extremely fast!
247 virtual void WillProcessIOEvent() = 0;
248 virtual void DidProcessIOEvent() = 0;
251 virtual ~IOObserver() {}
254 // The extended context that should be used as the base structure on every
255 // overlapped IO operation. |handler| must be set to the registered IOHandler
256 // for the given file when the operation is started, and it can be set to NULL
257 // before the operation completes to indicate that the handler should not be
258 // called anymore, and instead, the IOContext should be deleted when the OS
259 // notifies the completion of this operation. Please remember that any buffers
260 // involved with an IO operation should be around until the callback is
261 // received, so this technique can only be used for IO that do not involve
262 // additional buffers (other than the overlapped structure itself).
264 OVERLAPPED overlapped
;
269 ~MessagePumpForIO() override
;
271 // MessagePump methods:
272 void ScheduleWork() override
;
273 void ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) override
;
275 // Register the handler to be used when asynchronous IO for the given file
276 // completes. The registration persists as long as |file_handle| is valid, so
277 // |handler| must be valid as long as there is pending IO for the given file.
278 void RegisterIOHandler(HANDLE file_handle
, IOHandler
* handler
);
280 // Register the handler to be used to process job events. The registration
281 // persists as long as the job object is live, so |handler| must be valid
282 // until the job object is destroyed. Returns true if the registration
283 // succeeded, and false otherwise.
284 bool RegisterJobObject(HANDLE job_handle
, IOHandler
* handler
);
286 // Waits for the next IO completion that should be processed by |filter|, for
287 // up to |timeout| milliseconds. Return true if any IO operation completed,
288 // regardless of the involved handler, and false if the timeout expired. If
289 // the completion port received any message and the involved IO handler
290 // matches |filter|, the callback is called before returning from this code;
291 // if the handler is not the one that we are looking for, the callback will
292 // be postponed for another time, so reentrancy problems can be avoided.
293 // External use of this method should be reserved for the rare case when the
294 // caller is willing to allow pausing regular task dispatching on this thread.
295 bool WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
);
297 void AddIOObserver(IOObserver
* obs
);
298 void RemoveIOObserver(IOObserver
* obs
);
304 DWORD bytes_transfered
;
307 // In some cases |context| can be a non-pointer value casted to a pointer.
308 // |has_valid_io_context| is true if |context| is a valid IOContext
309 // pointer, and false otherwise.
310 bool has_valid_io_context
;
313 void DoRunLoop() override
;
315 bool MatchCompletedIOItem(IOHandler
* filter
, IOItem
* item
);
316 bool GetIOItem(DWORD timeout
, IOItem
* item
);
317 bool ProcessInternalIOItem(const IOItem
& item
);
318 void WillProcessIOEvent();
319 void DidProcessIOEvent();
321 // Converts an IOHandler pointer to a completion port key.
322 // |has_valid_io_context| specifies whether completion packets posted to
323 // |handler| will have valid OVERLAPPED pointers.
324 static ULONG_PTR
HandlerToKey(IOHandler
* handler
, bool has_valid_io_context
);
326 // Converts a completion port key to an IOHandler pointer.
327 static IOHandler
* KeyToHandler(ULONG_PTR key
, bool* has_valid_io_context
);
329 // The completion port associated with this thread.
330 win::ScopedHandle port_
;
331 // This list will be empty almost always. It stores IO completions that have
332 // not been delivered yet because somebody was doing cleanup.
333 std::list
<IOItem
> completed_io_
;
335 ObserverList
<IOObserver
> io_observers_
;
340 #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_