Blink roll 25b6bd3a7a131ffe68d809546ad1a20707915cdc:3a503f41ae42e5b79cfcd2ff10e65afde...
[chromium-blink-merge.git] / base / message_loop / message_pump_win.h
blobb25731742285a1ccc2381cd563942c845e844b80
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_
8 #include <windows.h>
10 #include <list>
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"
20 namespace base {
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 {
26 public:
27 MessagePumpWin() : have_work_(0), state_(NULL) {}
28 virtual ~MessagePumpWin() {}
30 // Like MessagePump::Run, but MSG objects are routed through dispatcher.
31 void RunWithDispatcher(Delegate* delegate, MessagePumpDispatcher* dispatcher);
33 // MessagePump methods:
34 virtual void Run(Delegate* delegate) { RunWithDispatcher(delegate, NULL); }
35 virtual void Quit();
37 protected:
38 struct RunState {
39 Delegate* delegate;
40 MessagePumpDispatcher* dispatcher;
42 // Used to flag that the current Run() invocation should return ASAP.
43 bool should_quit;
45 // Used to count how many Run() invocations are on the stack.
46 int run_depth;
49 virtual void DoRunLoop() = 0;
50 int GetCurrentDelay() const;
52 // The time at which delayed work should run.
53 TimeTicks delayed_work_time_;
55 // A boolean value used to indicate if there is a kMsgDoWork message pending
56 // in the Windows Message queue. There is at most one such message, and it
57 // can drive execution of tasks when a native message pump is running.
58 LONG have_work_;
60 // State for the current invocation of Run.
61 RunState* state_;
64 //-----------------------------------------------------------------------------
65 // MessagePumpForUI extends MessagePumpWin with methods that are particular to a
66 // MessageLoop instantiated with TYPE_UI.
68 // MessagePumpForUI implements a "traditional" Windows message pump. It contains
69 // a nearly infinite loop that peeks out messages, and then dispatches them.
70 // Intermixed with those peeks are callouts to DoWork for pending tasks, and
71 // DoDelayedWork for pending timers. When there are no events to be serviced,
72 // this pump goes into a wait state. In most cases, this message pump handles
73 // all processing.
75 // However, when a task, or windows event, invokes on the stack a native dialog
76 // box or such, that window typically provides a bare bones (native?) message
77 // pump. That bare-bones message pump generally supports little more than a
78 // peek of the Windows message queue, followed by a dispatch of the peeked
79 // message. MessageLoop extends that bare-bones message pump to also service
80 // Tasks, at the cost of some complexity.
82 // The basic structure of the extension (refered to as a sub-pump) is that a
83 // special message, kMsgHaveWork, is repeatedly injected into the Windows
84 // Message queue. Each time the kMsgHaveWork message is peeked, checks are
85 // made for an extended set of events, including the availability of Tasks to
86 // run.
88 // After running a task, the special message kMsgHaveWork is again posted to
89 // the Windows Message queue, ensuring a future time slice for processing a
90 // future event. To prevent flooding the Windows Message queue, care is taken
91 // to be sure that at most one kMsgHaveWork message is EVER pending in the
92 // Window's Message queue.
94 // There are a few additional complexities in this system where, when there are
95 // no Tasks to run, this otherwise infinite stream of messages which drives the
96 // sub-pump is halted. The pump is automatically re-started when Tasks are
97 // queued.
99 // A second complexity is that the presence of this stream of posted tasks may
100 // prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER.
101 // Such paint and timer events always give priority to a posted message, such as
102 // kMsgHaveWork messages. As a result, care is taken to do some peeking in
103 // between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork
104 // is peeked, and before a replacement kMsgHaveWork is posted).
106 // NOTE: Although it may seem odd that messages are used to start and stop this
107 // flow (as opposed to signaling objects, etc.), it should be understood that
108 // the native message pump will *only* respond to messages. As a result, it is
109 // an excellent choice. It is also helpful that the starter messages that are
110 // placed in the queue when new task arrive also awakens DoRunLoop.
112 class BASE_EXPORT MessagePumpForUI : public MessagePumpWin {
113 public:
114 // The application-defined code passed to the hook procedure.
115 static const int kMessageFilterCode = 0x5001;
117 MessagePumpForUI();
118 virtual ~MessagePumpForUI();
120 // MessagePump methods:
121 virtual void ScheduleWork();
122 virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time);
124 private:
125 static LRESULT CALLBACK WndProcThunk(HWND window_handle,
126 UINT message,
127 WPARAM wparam,
128 LPARAM lparam);
129 virtual void DoRunLoop();
130 void InitMessageWnd();
131 void WaitForWork();
132 void HandleWorkMessage();
133 void HandleTimerMessage();
134 bool ProcessNextWindowsMessage();
135 bool ProcessMessageHelper(const MSG& msg);
136 bool ProcessPumpReplacementMessage();
138 // Atom representing the registered window class.
139 ATOM atom_;
141 // A hidden message-only window.
142 HWND message_hwnd_;
145 //-----------------------------------------------------------------------------
146 // MessagePumpForIO extends MessagePumpWin with methods that are particular to a
147 // MessageLoop instantiated with TYPE_IO. This version of MessagePump does not
148 // deal with Windows mesagges, and instead has a Run loop based on Completion
149 // Ports so it is better suited for IO operations.
151 class BASE_EXPORT MessagePumpForIO : public MessagePumpWin {
152 public:
153 struct IOContext;
155 // Clients interested in receiving OS notifications when asynchronous IO
156 // operations complete should implement this interface and register themselves
157 // with the message pump.
159 // Typical use #1:
160 // // Use only when there are no user's buffers involved on the actual IO,
161 // // so that all the cleanup can be done by the message pump.
162 // class MyFile : public IOHandler {
163 // MyFile() {
164 // ...
165 // context_ = new IOContext;
166 // context_->handler = this;
167 // message_pump->RegisterIOHandler(file_, this);
168 // }
169 // ~MyFile() {
170 // if (pending_) {
171 // // By setting the handler to NULL, we're asking for this context
172 // // to be deleted when received, without calling back to us.
173 // context_->handler = NULL;
174 // } else {
175 // delete context_;
176 // }
177 // }
178 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
179 // DWORD error) {
180 // pending_ = false;
181 // }
182 // void DoSomeIo() {
183 // ...
184 // // The only buffer required for this operation is the overlapped
185 // // structure.
186 // ConnectNamedPipe(file_, &context_->overlapped);
187 // pending_ = true;
188 // }
189 // bool pending_;
190 // IOContext* context_;
191 // HANDLE file_;
192 // };
194 // Typical use #2:
195 // class MyFile : public IOHandler {
196 // MyFile() {
197 // ...
198 // message_pump->RegisterIOHandler(file_, this);
199 // }
200 // // Plus some code to make sure that this destructor is not called
201 // // while there are pending IO operations.
202 // ~MyFile() {
203 // }
204 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
205 // DWORD error) {
206 // ...
207 // delete context;
208 // }
209 // void DoSomeIo() {
210 // ...
211 // IOContext* context = new IOContext;
212 // // This is not used for anything. It just prevents the context from
213 // // being considered "abandoned".
214 // context->handler = this;
215 // ReadFile(file_, buffer, num_bytes, &read, &context->overlapped);
216 // }
217 // HANDLE file_;
218 // };
220 // Typical use #3:
221 // Same as the previous example, except that in order to deal with the
222 // requirement stated for the destructor, the class calls WaitForIOCompletion
223 // from the destructor to block until all IO finishes.
224 // ~MyFile() {
225 // while(pending_)
226 // message_pump->WaitForIOCompletion(INFINITE, this);
227 // }
229 class IOHandler {
230 public:
231 virtual ~IOHandler() {}
232 // This will be called once the pending IO operation associated with
233 // |context| completes. |error| is the Win32 error code of the IO operation
234 // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero
235 // on error.
236 virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
237 DWORD error) = 0;
240 // An IOObserver is an object that receives IO notifications from the
241 // MessagePump.
243 // NOTE: An IOObserver implementation should be extremely fast!
244 class IOObserver {
245 public:
246 IOObserver() {}
248 virtual void WillProcessIOEvent() = 0;
249 virtual void DidProcessIOEvent() = 0;
251 protected:
252 virtual ~IOObserver() {}
255 // The extended context that should be used as the base structure on every
256 // overlapped IO operation. |handler| must be set to the registered IOHandler
257 // for the given file when the operation is started, and it can be set to NULL
258 // before the operation completes to indicate that the handler should not be
259 // called anymore, and instead, the IOContext should be deleted when the OS
260 // notifies the completion of this operation. Please remember that any buffers
261 // involved with an IO operation should be around until the callback is
262 // received, so this technique can only be used for IO that do not involve
263 // additional buffers (other than the overlapped structure itself).
264 struct IOContext {
265 OVERLAPPED overlapped;
266 IOHandler* handler;
269 MessagePumpForIO();
270 virtual ~MessagePumpForIO() {}
272 // MessagePump methods:
273 virtual void ScheduleWork();
274 virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time);
276 // Register the handler to be used when asynchronous IO for the given file
277 // completes. The registration persists as long as |file_handle| is valid, so
278 // |handler| must be valid as long as there is pending IO for the given file.
279 void RegisterIOHandler(HANDLE file_handle, IOHandler* handler);
281 // Register the handler to be used to process job events. The registration
282 // persists as long as the job object is live, so |handler| must be valid
283 // until the job object is destroyed. Returns true if the registration
284 // succeeded, and false otherwise.
285 bool RegisterJobObject(HANDLE job_handle, IOHandler* handler);
287 // Waits for the next IO completion that should be processed by |filter|, for
288 // up to |timeout| milliseconds. Return true if any IO operation completed,
289 // regardless of the involved handler, and false if the timeout expired. If
290 // the completion port received any message and the involved IO handler
291 // matches |filter|, the callback is called before returning from this code;
292 // if the handler is not the one that we are looking for, the callback will
293 // be postponed for another time, so reentrancy problems can be avoided.
294 // External use of this method should be reserved for the rare case when the
295 // caller is willing to allow pausing regular task dispatching on this thread.
296 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
298 void AddIOObserver(IOObserver* obs);
299 void RemoveIOObserver(IOObserver* obs);
301 private:
302 struct IOItem {
303 IOHandler* handler;
304 IOContext* context;
305 DWORD bytes_transfered;
306 DWORD error;
308 // In some cases |context| can be a non-pointer value casted to a pointer.
309 // |has_valid_io_context| is true if |context| is a valid IOContext
310 // pointer, and false otherwise.
311 bool has_valid_io_context;
314 virtual void DoRunLoop();
315 void WaitForWork();
316 bool MatchCompletedIOItem(IOHandler* filter, IOItem* item);
317 bool GetIOItem(DWORD timeout, IOItem* item);
318 bool ProcessInternalIOItem(const IOItem& item);
319 void WillProcessIOEvent();
320 void DidProcessIOEvent();
322 // Converts an IOHandler pointer to a completion port key.
323 // |has_valid_io_context| specifies whether completion packets posted to
324 // |handler| will have valid OVERLAPPED pointers.
325 static ULONG_PTR HandlerToKey(IOHandler* handler, bool has_valid_io_context);
327 // Converts a completion port key to an IOHandler pointer.
328 static IOHandler* KeyToHandler(ULONG_PTR key, bool* has_valid_io_context);
330 // The completion port associated with this thread.
331 win::ScopedHandle port_;
332 // This list will be empty almost always. It stores IO completions that have
333 // not been delivered yet because somebody was doing cleanup.
334 std::list<IOItem> completed_io_;
336 ObserverList<IOObserver> io_observers_;
339 } // namespace base
341 #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_