Reland "Encapsulate CSS selector declarative content condition tracking"
[chromium-blink-merge.git] / base / message_loop / message_pump_win.h
blob042efdf9d9f72909aab052cfc99a762c376a14b6
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/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"
21 namespace base {
23 class Thread;
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 {
29 public:
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;
37 void Quit() override;
39 protected:
40 struct RunState {
41 Delegate* delegate;
42 MessagePumpDispatcher* dispatcher;
44 // Used to flag that the current Run() invocation should return ASAP.
45 bool should_quit;
47 // Used to count how many Run() invocations are on the stack.
48 int run_depth;
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.
60 LONG have_work_;
62 // State for the current invocation of Run.
63 RunState* state_;
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
75 // all processing.
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
88 // run.
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
99 // queued.
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 {
115 public:
116 // The application-defined code passed to the hook procedure.
117 static const int kMessageFilterCode = 0x5001;
119 MessagePumpForUI();
120 ~MessagePumpForUI() override;
122 // MessagePump methods:
123 void ScheduleWork() override;
124 void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
126 private:
127 static LRESULT CALLBACK WndProcThunk(HWND window_handle,
128 UINT message,
129 WPARAM wparam,
130 LPARAM lparam);
131 void DoRunLoop() override;
132 void InitMessageWnd();
133 void WaitForWork();
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 // Atom representing the registered window class.
162 ATOM atom_;
164 // A hidden message-only window.
165 HWND message_hwnd_;
167 // This thread is used to periodically wake up the main thread to process
168 // tasks.
169 scoped_ptr<base::Thread> ui_worker_thread_;
171 // The UI worker thread waits on this timer indefinitely. When the main
172 // thread has tasks ready to be processed it sets the timer.
173 base::win::ScopedHandle ui_worker_thread_timer_;
176 //-----------------------------------------------------------------------------
177 // MessagePumpForIO extends MessagePumpWin with methods that are particular to a
178 // MessageLoop instantiated with TYPE_IO. This version of MessagePump does not
179 // deal with Windows mesagges, and instead has a Run loop based on Completion
180 // Ports so it is better suited for IO operations.
182 class BASE_EXPORT MessagePumpForIO : public MessagePumpWin {
183 public:
184 struct IOContext;
186 // Clients interested in receiving OS notifications when asynchronous IO
187 // operations complete should implement this interface and register themselves
188 // with the message pump.
190 // Typical use #1:
191 // // Use only when there are no user's buffers involved on the actual IO,
192 // // so that all the cleanup can be done by the message pump.
193 // class MyFile : public IOHandler {
194 // MyFile() {
195 // ...
196 // context_ = new IOContext;
197 // context_->handler = this;
198 // message_pump->RegisterIOHandler(file_, this);
199 // }
200 // ~MyFile() {
201 // if (pending_) {
202 // // By setting the handler to NULL, we're asking for this context
203 // // to be deleted when received, without calling back to us.
204 // context_->handler = NULL;
205 // } else {
206 // delete context_;
207 // }
208 // }
209 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
210 // DWORD error) {
211 // pending_ = false;
212 // }
213 // void DoSomeIo() {
214 // ...
215 // // The only buffer required for this operation is the overlapped
216 // // structure.
217 // ConnectNamedPipe(file_, &context_->overlapped);
218 // pending_ = true;
219 // }
220 // bool pending_;
221 // IOContext* context_;
222 // HANDLE file_;
223 // };
225 // Typical use #2:
226 // class MyFile : public IOHandler {
227 // MyFile() {
228 // ...
229 // message_pump->RegisterIOHandler(file_, this);
230 // }
231 // // Plus some code to make sure that this destructor is not called
232 // // while there are pending IO operations.
233 // ~MyFile() {
234 // }
235 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
236 // DWORD error) {
237 // ...
238 // delete context;
239 // }
240 // void DoSomeIo() {
241 // ...
242 // IOContext* context = new IOContext;
243 // // This is not used for anything. It just prevents the context from
244 // // being considered "abandoned".
245 // context->handler = this;
246 // ReadFile(file_, buffer, num_bytes, &read, &context->overlapped);
247 // }
248 // HANDLE file_;
249 // };
251 // Typical use #3:
252 // Same as the previous example, except that in order to deal with the
253 // requirement stated for the destructor, the class calls WaitForIOCompletion
254 // from the destructor to block until all IO finishes.
255 // ~MyFile() {
256 // while(pending_)
257 // message_pump->WaitForIOCompletion(INFINITE, this);
258 // }
260 class IOHandler {
261 public:
262 virtual ~IOHandler() {}
263 // This will be called once the pending IO operation associated with
264 // |context| completes. |error| is the Win32 error code of the IO operation
265 // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero
266 // on error.
267 virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
268 DWORD error) = 0;
271 // An IOObserver is an object that receives IO notifications from the
272 // MessagePump.
274 // NOTE: An IOObserver implementation should be extremely fast!
275 class IOObserver {
276 public:
277 IOObserver() {}
279 virtual void WillProcessIOEvent() = 0;
280 virtual void DidProcessIOEvent() = 0;
282 protected:
283 virtual ~IOObserver() {}
286 // The extended context that should be used as the base structure on every
287 // overlapped IO operation. |handler| must be set to the registered IOHandler
288 // for the given file when the operation is started, and it can be set to NULL
289 // before the operation completes to indicate that the handler should not be
290 // called anymore, and instead, the IOContext should be deleted when the OS
291 // notifies the completion of this operation. Please remember that any buffers
292 // involved with an IO operation should be around until the callback is
293 // received, so this technique can only be used for IO that do not involve
294 // additional buffers (other than the overlapped structure itself).
295 struct IOContext {
296 OVERLAPPED overlapped;
297 IOHandler* handler;
300 MessagePumpForIO();
301 ~MessagePumpForIO() override;
303 // MessagePump methods:
304 void ScheduleWork() override;
305 void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
307 // Register the handler to be used when asynchronous IO for the given file
308 // completes. The registration persists as long as |file_handle| is valid, so
309 // |handler| must be valid as long as there is pending IO for the given file.
310 void RegisterIOHandler(HANDLE file_handle, IOHandler* handler);
312 // Register the handler to be used to process job events. The registration
313 // persists as long as the job object is live, so |handler| must be valid
314 // until the job object is destroyed. Returns true if the registration
315 // succeeded, and false otherwise.
316 bool RegisterJobObject(HANDLE job_handle, IOHandler* handler);
318 // Waits for the next IO completion that should be processed by |filter|, for
319 // up to |timeout| milliseconds. Return true if any IO operation completed,
320 // regardless of the involved handler, and false if the timeout expired. If
321 // the completion port received any message and the involved IO handler
322 // matches |filter|, the callback is called before returning from this code;
323 // if the handler is not the one that we are looking for, the callback will
324 // be postponed for another time, so reentrancy problems can be avoided.
325 // External use of this method should be reserved for the rare case when the
326 // caller is willing to allow pausing regular task dispatching on this thread.
327 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
329 void AddIOObserver(IOObserver* obs);
330 void RemoveIOObserver(IOObserver* obs);
332 private:
333 struct IOItem {
334 IOHandler* handler;
335 IOContext* context;
336 DWORD bytes_transfered;
337 DWORD error;
339 // In some cases |context| can be a non-pointer value casted to a pointer.
340 // |has_valid_io_context| is true if |context| is a valid IOContext
341 // pointer, and false otherwise.
342 bool has_valid_io_context;
345 void DoRunLoop() override;
346 void WaitForWork();
347 bool MatchCompletedIOItem(IOHandler* filter, IOItem* item);
348 bool GetIOItem(DWORD timeout, IOItem* item);
349 bool ProcessInternalIOItem(const IOItem& item);
350 void WillProcessIOEvent();
351 void DidProcessIOEvent();
353 // Converts an IOHandler pointer to a completion port key.
354 // |has_valid_io_context| specifies whether completion packets posted to
355 // |handler| will have valid OVERLAPPED pointers.
356 static ULONG_PTR HandlerToKey(IOHandler* handler, bool has_valid_io_context);
358 // Converts a completion port key to an IOHandler pointer.
359 static IOHandler* KeyToHandler(ULONG_PTR key, bool* has_valid_io_context);
361 // The completion port associated with this thread.
362 win::ScopedHandle port_;
363 // This list will be empty almost always. It stores IO completions that have
364 // not been delivered yet because somebody was doing cleanup.
365 std::list<IOItem> completed_io_;
367 ObserverList<IOObserver> io_observers_;
370 } // namespace base
372 #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_