Fix for Hyperlinks do not open in new tab by Print preview window.
[chromium-blink-merge.git] / base / message_loop / message_pump_win.cc
blob800c601c1e65f0fb81915135616d063a29b3187d
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 #include "base/message_loop/message_pump_win.h"
7 #include <limits>
8 #include <math.h>
10 #include "base/debug/trace_event.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/metrics/histogram.h"
13 #include "base/process/memory.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/win/wrapped_window_proc.h"
18 namespace base {
20 namespace {
22 enum MessageLoopProblems {
23 MESSAGE_POST_ERROR,
24 COMPLETION_POST_ERROR,
25 SET_TIMER_ERROR,
26 MESSAGE_LOOP_PROBLEM_MAX,
29 } // namespace
31 static const wchar_t kWndClassFormat[] = L"Chrome_MessagePumpWindow_%p";
33 // Message sent to get an additional time slice for pumping (processing) another
34 // task (a series of such messages creates a continuous task pump).
35 static const int kMsgHaveWork = WM_USER + 1;
37 //-----------------------------------------------------------------------------
38 // MessagePumpWin public:
40 void MessagePumpWin::RunWithDispatcher(
41 Delegate* delegate, MessagePumpDispatcher* dispatcher) {
42 RunState s;
43 s.delegate = delegate;
44 s.dispatcher = dispatcher;
45 s.should_quit = false;
46 s.run_depth = state_ ? state_->run_depth + 1 : 1;
48 RunState* previous_state = state_;
49 state_ = &s;
51 DoRunLoop();
53 state_ = previous_state;
56 void MessagePumpWin::Quit() {
57 DCHECK(state_);
58 state_->should_quit = true;
61 //-----------------------------------------------------------------------------
62 // MessagePumpWin protected:
64 int MessagePumpWin::GetCurrentDelay() const {
65 if (delayed_work_time_.is_null())
66 return -1;
68 // Be careful here. TimeDelta has a precision of microseconds, but we want a
69 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
70 // 6? It should be 6 to avoid executing delayed work too early.
71 double timeout =
72 ceil((delayed_work_time_ - TimeTicks::Now()).InMillisecondsF());
74 // Range check the |timeout| while converting to an integer. If the |timeout|
75 // is negative, then we need to run delayed work soon. If the |timeout| is
76 // "overflowingly" large, that means a delayed task was posted with a
77 // super-long delay.
78 return timeout < 0 ? 0 :
79 (timeout > std::numeric_limits<int>::max() ?
80 std::numeric_limits<int>::max() : static_cast<int>(timeout));
83 //-----------------------------------------------------------------------------
84 // MessagePumpForUI public:
86 MessagePumpForUI::MessagePumpForUI()
87 : atom_(0) {
88 InitMessageWnd();
91 MessagePumpForUI::~MessagePumpForUI() {
92 DestroyWindow(message_hwnd_);
93 UnregisterClass(MAKEINTATOM(atom_),
94 GetModuleFromAddress(&WndProcThunk));
97 void MessagePumpForUI::ScheduleWork() {
98 if (InterlockedExchange(&have_work_, 1))
99 return; // Someone else continued the pumping.
101 // Make sure the MessagePump does some work for us.
102 BOOL ret = PostMessage(message_hwnd_, kMsgHaveWork,
103 reinterpret_cast<WPARAM>(this), 0);
104 if (ret)
105 return; // There was room in the Window Message queue.
107 // We have failed to insert a have-work message, so there is a chance that we
108 // will starve tasks/timers while sitting in a nested message loop. Nested
109 // loops only look at Windows Message queues, and don't look at *our* task
110 // queues, etc., so we might not get a time slice in such. :-(
111 // We could abort here, but the fear is that this failure mode is plausibly
112 // common (queue is full, of about 2000 messages), so we'll do a near-graceful
113 // recovery. Nested loops are pretty transient (we think), so this will
114 // probably be recoverable.
115 InterlockedExchange(&have_work_, 0); // Clarify that we didn't really insert.
116 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR,
117 MESSAGE_LOOP_PROBLEM_MAX);
120 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
122 // We would *like* to provide high resolution timers. Windows timers using
123 // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
124 // mechanism because the application can enter modal windows loops where it
125 // is not running our MessageLoop; the only way to have our timers fire in
126 // these cases is to post messages there.
128 // To provide sub-10ms timers, we process timers directly from our run loop.
129 // For the common case, timers will be processed there as the run loop does
130 // its normal work. However, we *also* set the system timer so that WM_TIMER
131 // events fire. This mops up the case of timers not being able to work in
132 // modal message loops. It is possible for the SetTimer to pop and have no
133 // pending timers, because they could have already been processed by the
134 // run loop itself.
136 // We use a single SetTimer corresponding to the timer that will expire
137 // soonest. As new timers are created and destroyed, we update SetTimer.
138 // Getting a spurrious SetTimer event firing is benign, as we'll just be
139 // processing an empty timer queue.
141 delayed_work_time_ = delayed_work_time;
143 int delay_msec = GetCurrentDelay();
144 DCHECK_GE(delay_msec, 0);
145 if (delay_msec < USER_TIMER_MINIMUM)
146 delay_msec = USER_TIMER_MINIMUM;
148 // Create a WM_TIMER event that will wake us up to check for any pending
149 // timers (in case we are running within a nested, external sub-pump).
150 BOOL ret = SetTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this),
151 delay_msec, NULL);
152 if (ret)
153 return;
154 // If we can't set timers, we are in big trouble... but cross our fingers for
155 // now.
156 // TODO(jar): If we don't see this error, use a CHECK() here instead.
157 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", SET_TIMER_ERROR,
158 MESSAGE_LOOP_PROBLEM_MAX);
161 //-----------------------------------------------------------------------------
162 // MessagePumpForUI private:
164 // static
165 LRESULT CALLBACK MessagePumpForUI::WndProcThunk(
166 HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
167 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
168 tracked_objects::ScopedTracker tracking_profile1(
169 FROM_HERE_WITH_EXPLICIT_FUNCTION(
170 "440919 MessagePumpForUI::WndProcThunk1"));
172 switch (message) {
173 case kMsgHaveWork:
174 reinterpret_cast<MessagePumpForUI*>(wparam)->HandleWorkMessage();
175 break;
176 case WM_TIMER:
177 reinterpret_cast<MessagePumpForUI*>(wparam)->HandleTimerMessage();
178 break;
181 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
182 tracked_objects::ScopedTracker tracking_profile2(
183 FROM_HERE_WITH_EXPLICIT_FUNCTION(
184 "440919 MessagePumpForUI::WndProcThunk2"));
186 return DefWindowProc(hwnd, message, wparam, lparam);
189 void MessagePumpForUI::DoRunLoop() {
190 // IF this was just a simple PeekMessage() loop (servicing all possible work
191 // queues), then Windows would try to achieve the following order according
192 // to MSDN documentation about PeekMessage with no filter):
193 // * Sent messages
194 // * Posted messages
195 // * Sent messages (again)
196 // * WM_PAINT messages
197 // * WM_TIMER messages
199 // Summary: none of the above classes is starved, and sent messages has twice
200 // the chance of being processed (i.e., reduced service time).
202 for (;;) {
203 // If we do any work, we may create more messages etc., and more work may
204 // possibly be waiting in another task group. When we (for example)
205 // ProcessNextWindowsMessage(), there is a good chance there are still more
206 // messages waiting. On the other hand, when any of these methods return
207 // having done no work, then it is pretty unlikely that calling them again
208 // quickly will find any work to do. Finally, if they all say they had no
209 // work, then it is a good time to consider sleeping (waiting) for more
210 // work.
212 bool more_work_is_plausible = ProcessNextWindowsMessage();
213 if (state_->should_quit)
214 break;
216 more_work_is_plausible |= state_->delegate->DoWork();
217 if (state_->should_quit)
218 break;
220 more_work_is_plausible |=
221 state_->delegate->DoDelayedWork(&delayed_work_time_);
222 // If we did not process any delayed work, then we can assume that our
223 // existing WM_TIMER if any will fire when delayed work should run. We
224 // don't want to disturb that timer if it is already in flight. However,
225 // if we did do all remaining delayed work, then lets kill the WM_TIMER.
226 if (more_work_is_plausible && delayed_work_time_.is_null())
227 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
228 if (state_->should_quit)
229 break;
231 if (more_work_is_plausible)
232 continue;
234 more_work_is_plausible = state_->delegate->DoIdleWork();
235 if (state_->should_quit)
236 break;
238 if (more_work_is_plausible)
239 continue;
241 WaitForWork(); // Wait (sleep) until we have work to do again.
245 void MessagePumpForUI::InitMessageWnd() {
246 // Generate a unique window class name.
247 string16 class_name = StringPrintf(kWndClassFormat, this);
249 HINSTANCE instance = GetModuleFromAddress(&WndProcThunk);
250 WNDCLASSEX wc = {0};
251 wc.cbSize = sizeof(wc);
252 wc.lpfnWndProc = base::win::WrappedWindowProc<WndProcThunk>;
253 wc.hInstance = instance;
254 wc.lpszClassName = class_name.c_str();
255 atom_ = RegisterClassEx(&wc);
256 DCHECK(atom_);
258 message_hwnd_ = CreateWindow(MAKEINTATOM(atom_), 0, 0, 0, 0, 0, 0,
259 HWND_MESSAGE, 0, instance, 0);
260 DCHECK(message_hwnd_);
263 void MessagePumpForUI::WaitForWork() {
264 // Wait until a message is available, up to the time needed by the timer
265 // manager to fire the next set of timers.
266 int delay = GetCurrentDelay();
267 if (delay < 0) // Negative value means no timers waiting.
268 delay = INFINITE;
270 DWORD result;
271 result = MsgWaitForMultipleObjectsEx(0, NULL, delay, QS_ALLINPUT,
272 MWMO_INPUTAVAILABLE);
274 if (WAIT_OBJECT_0 == result) {
275 // A WM_* message is available.
276 // If a parent child relationship exists between windows across threads
277 // then their thread inputs are implicitly attached.
278 // This causes the MsgWaitForMultipleObjectsEx API to return indicating
279 // that messages are ready for processing (Specifically, mouse messages
280 // intended for the child window may appear if the child window has
281 // capture).
282 // The subsequent PeekMessages call may fail to return any messages thus
283 // causing us to enter a tight loop at times.
284 // The WaitMessage call below is a workaround to give the child window
285 // some time to process its input messages.
286 MSG msg = {0};
287 DWORD queue_status = GetQueueStatus(QS_MOUSE);
288 if (HIWORD(queue_status) & QS_MOUSE &&
289 !PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_NOREMOVE)) {
290 WaitMessage();
292 return;
295 DCHECK_NE(WAIT_FAILED, result) << GetLastError();
298 void MessagePumpForUI::HandleWorkMessage() {
299 // If we are being called outside of the context of Run, then don't try to do
300 // any work. This could correspond to a MessageBox call or something of that
301 // sort.
302 if (!state_) {
303 // Since we handled a kMsgHaveWork message, we must still update this flag.
304 InterlockedExchange(&have_work_, 0);
305 return;
308 // Let whatever would have run had we not been putting messages in the queue
309 // run now. This is an attempt to make our dummy message not starve other
310 // messages that may be in the Windows message queue.
311 ProcessPumpReplacementMessage();
313 // Now give the delegate a chance to do some work. He'll let us know if he
314 // needs to do more work.
315 if (state_->delegate->DoWork())
316 ScheduleWork();
319 void MessagePumpForUI::HandleTimerMessage() {
320 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
322 // If we are being called outside of the context of Run, then don't do
323 // anything. This could correspond to a MessageBox call or something of
324 // that sort.
325 if (!state_)
326 return;
328 state_->delegate->DoDelayedWork(&delayed_work_time_);
329 if (!delayed_work_time_.is_null()) {
330 // A bit gratuitous to set delayed_work_time_ again, but oh well.
331 ScheduleDelayedWork(delayed_work_time_);
335 bool MessagePumpForUI::ProcessNextWindowsMessage() {
336 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
337 tracked_objects::ScopedTracker tracking_profile1(
338 FROM_HERE_WITH_EXPLICIT_FUNCTION(
339 "440919 MessagePumpForUI::ProcessNextWindowsMessage1"));
341 // If there are sent messages in the queue then PeekMessage internally
342 // dispatches the message and returns false. We return true in this
343 // case to ensure that the message loop peeks again instead of calling
344 // MsgWaitForMultipleObjectsEx again.
345 bool sent_messages_in_queue = false;
346 DWORD queue_status = GetQueueStatus(QS_SENDMESSAGE);
347 if (HIWORD(queue_status) & QS_SENDMESSAGE)
348 sent_messages_in_queue = true;
350 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
351 tracked_objects::ScopedTracker tracking_profile2(
352 FROM_HERE_WITH_EXPLICIT_FUNCTION(
353 "440919 MessagePumpForUI::ProcessNextWindowsMessage2"));
355 MSG msg;
356 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE)
357 return ProcessMessageHelper(msg);
359 return sent_messages_in_queue;
362 bool MessagePumpForUI::ProcessMessageHelper(const MSG& msg) {
363 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
364 tracked_objects::ScopedTracker tracking_profile1(
365 FROM_HERE_WITH_EXPLICIT_FUNCTION(
366 "440919 MessagePumpForUI::ProcessMessageHelper1"));
368 TRACE_EVENT1("base", "MessagePumpForUI::ProcessMessageHelper",
369 "message", msg.message);
370 if (WM_QUIT == msg.message) {
371 // Repost the QUIT message so that it will be retrieved by the primary
372 // GetMessage() loop.
373 state_->should_quit = true;
374 PostQuitMessage(static_cast<int>(msg.wParam));
375 return false;
378 // While running our main message pump, we discard kMsgHaveWork messages.
379 if (msg.message == kMsgHaveWork && msg.hwnd == message_hwnd_)
380 return ProcessPumpReplacementMessage();
382 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
383 tracked_objects::ScopedTracker tracking_profile2(
384 FROM_HERE_WITH_EXPLICIT_FUNCTION(
385 "440919 MessagePumpForUI::ProcessMessageHelper2"));
387 if (CallMsgFilter(const_cast<MSG*>(&msg), kMessageFilterCode))
388 return true;
390 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
391 tracked_objects::ScopedTracker tracking_profile3(
392 FROM_HERE_WITH_EXPLICIT_FUNCTION(
393 "440919 MessagePumpForUI::ProcessMessageHelper3"));
395 uint32_t action = MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT;
396 if (state_->dispatcher) {
397 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
398 tracked_objects::ScopedTracker tracking_profile4(
399 FROM_HERE_WITH_EXPLICIT_FUNCTION(
400 "440919 MessagePumpForUI::ProcessMessageHelper4"));
402 action = state_->dispatcher->Dispatch(msg);
404 if (action & MessagePumpDispatcher::POST_DISPATCH_QUIT_LOOP)
405 state_->should_quit = true;
406 if (action & MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT) {
407 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
408 tracked_objects::ScopedTracker tracking_profile5(
409 FROM_HERE_WITH_EXPLICIT_FUNCTION(
410 "440919 MessagePumpForUI::ProcessMessageHelper5"));
412 TranslateMessage(&msg);
414 // TODO(vadimt): Remove ScopedTracker below once crbug.com/440919 is fixed.
415 tracked_objects::ScopedTracker tracking_profile6(
416 FROM_HERE_WITH_EXPLICIT_FUNCTION(
417 "440919 MessagePumpForUI::ProcessMessageHelper6"));
419 DispatchMessage(&msg);
422 return true;
425 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
426 // When we encounter a kMsgHaveWork message, this method is called to peek
427 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
428 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
429 // a continuous stream of such messages are posted. This method carefully
430 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
431 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
432 // possibly be posted), and finally dispatches that peeked replacement. Note
433 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
435 bool have_message = false;
436 MSG msg;
437 // We should not process all window messages if we are in the context of an
438 // OS modal loop, i.e. in the context of a windows API call like MessageBox.
439 // This is to ensure that these messages are peeked out by the OS modal loop.
440 if (MessageLoop::current()->os_modal_loop()) {
441 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
442 have_message = PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE) ||
443 PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
444 } else {
445 have_message = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE;
448 DCHECK(!have_message || kMsgHaveWork != msg.message ||
449 msg.hwnd != message_hwnd_);
451 // Since we discarded a kMsgHaveWork message, we must update the flag.
452 int old_have_work = InterlockedExchange(&have_work_, 0);
453 DCHECK(old_have_work);
455 // We don't need a special time slice if we didn't have_message to process.
456 if (!have_message)
457 return false;
459 // Guarantee we'll get another time slice in the case where we go into native
460 // windows code. This ScheduleWork() may hurt performance a tiny bit when
461 // tasks appear very infrequently, but when the event queue is busy, the
462 // kMsgHaveWork events get (percentage wise) rarer and rarer.
463 ScheduleWork();
464 return ProcessMessageHelper(msg);
467 //-----------------------------------------------------------------------------
468 // MessagePumpForIO public:
470 MessagePumpForIO::MessagePumpForIO() {
471 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1));
472 DCHECK(port_.IsValid());
475 void MessagePumpForIO::ScheduleWork() {
476 if (InterlockedExchange(&have_work_, 1))
477 return; // Someone else continued the pumping.
479 // Make sure the MessagePump does some work for us.
480 BOOL ret = PostQueuedCompletionStatus(port_.Get(), 0,
481 reinterpret_cast<ULONG_PTR>(this),
482 reinterpret_cast<OVERLAPPED*>(this));
483 if (ret)
484 return; // Post worked perfectly.
486 // See comment in MessagePumpForUI::ScheduleWork() for this error recovery.
487 InterlockedExchange(&have_work_, 0); // Clarify that we didn't succeed.
488 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", COMPLETION_POST_ERROR,
489 MESSAGE_LOOP_PROBLEM_MAX);
492 void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
493 // We know that we can't be blocked right now since this method can only be
494 // called on the same thread as Run, so we only need to update our record of
495 // how long to sleep when we do sleep.
496 delayed_work_time_ = delayed_work_time;
499 void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle,
500 IOHandler* handler) {
501 ULONG_PTR key = HandlerToKey(handler, true);
502 HANDLE port = CreateIoCompletionPort(file_handle, port_.Get(), key, 1);
503 DPCHECK(port);
506 bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle,
507 IOHandler* handler) {
508 // Job object notifications use the OVERLAPPED pointer to carry the message
509 // data. Mark the completion key correspondingly, so we will not try to
510 // convert OVERLAPPED* to IOContext*.
511 ULONG_PTR key = HandlerToKey(handler, false);
512 JOBOBJECT_ASSOCIATE_COMPLETION_PORT info;
513 info.CompletionKey = reinterpret_cast<void*>(key);
514 info.CompletionPort = port_.Get();
515 return SetInformationJobObject(job_handle,
516 JobObjectAssociateCompletionPortInformation,
517 &info,
518 sizeof(info)) != FALSE;
521 //-----------------------------------------------------------------------------
522 // MessagePumpForIO private:
524 void MessagePumpForIO::DoRunLoop() {
525 for (;;) {
526 // If we do any work, we may create more messages etc., and more work may
527 // possibly be waiting in another task group. When we (for example)
528 // WaitForIOCompletion(), there is a good chance there are still more
529 // messages waiting. On the other hand, when any of these methods return
530 // having done no work, then it is pretty unlikely that calling them
531 // again quickly will find any work to do. Finally, if they all say they
532 // had no work, then it is a good time to consider sleeping (waiting) for
533 // more work.
535 bool more_work_is_plausible = state_->delegate->DoWork();
536 if (state_->should_quit)
537 break;
539 more_work_is_plausible |= WaitForIOCompletion(0, NULL);
540 if (state_->should_quit)
541 break;
543 more_work_is_plausible |=
544 state_->delegate->DoDelayedWork(&delayed_work_time_);
545 if (state_->should_quit)
546 break;
548 if (more_work_is_plausible)
549 continue;
551 more_work_is_plausible = state_->delegate->DoIdleWork();
552 if (state_->should_quit)
553 break;
555 if (more_work_is_plausible)
556 continue;
558 WaitForWork(); // Wait (sleep) until we have work to do again.
562 // Wait until IO completes, up to the time needed by the timer manager to fire
563 // the next set of timers.
564 void MessagePumpForIO::WaitForWork() {
565 // We do not support nested IO message loops. This is to avoid messy
566 // recursion problems.
567 DCHECK_EQ(1, state_->run_depth) << "Cannot nest an IO message loop!";
569 int timeout = GetCurrentDelay();
570 if (timeout < 0) // Negative value means no timers waiting.
571 timeout = INFINITE;
573 WaitForIOCompletion(timeout, NULL);
576 bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
577 IOItem item;
578 if (completed_io_.empty() || !MatchCompletedIOItem(filter, &item)) {
579 // We have to ask the system for another IO completion.
580 if (!GetIOItem(timeout, &item))
581 return false;
583 if (ProcessInternalIOItem(item))
584 return true;
587 // If |item.has_valid_io_context| is false then |item.context| does not point
588 // to a context structure, and so should not be dereferenced, although it may
589 // still hold valid non-pointer data.
590 if (!item.has_valid_io_context || item.context->handler) {
591 if (filter && item.handler != filter) {
592 // Save this item for later
593 completed_io_.push_back(item);
594 } else {
595 DCHECK(!item.has_valid_io_context ||
596 (item.context->handler == item.handler));
597 WillProcessIOEvent();
598 item.handler->OnIOCompleted(item.context, item.bytes_transfered,
599 item.error);
600 DidProcessIOEvent();
602 } else {
603 // The handler must be gone by now, just cleanup the mess.
604 delete item.context;
606 return true;
609 // Asks the OS for another IO completion result.
610 bool MessagePumpForIO::GetIOItem(DWORD timeout, IOItem* item) {
611 memset(item, 0, sizeof(*item));
612 ULONG_PTR key = NULL;
613 OVERLAPPED* overlapped = NULL;
614 if (!GetQueuedCompletionStatus(port_.Get(), &item->bytes_transfered, &key,
615 &overlapped, timeout)) {
616 if (!overlapped)
617 return false; // Nothing in the queue.
618 item->error = GetLastError();
619 item->bytes_transfered = 0;
622 item->handler = KeyToHandler(key, &item->has_valid_io_context);
623 item->context = reinterpret_cast<IOContext*>(overlapped);
624 return true;
627 bool MessagePumpForIO::ProcessInternalIOItem(const IOItem& item) {
628 if (this == reinterpret_cast<MessagePumpForIO*>(item.context) &&
629 this == reinterpret_cast<MessagePumpForIO*>(item.handler)) {
630 // This is our internal completion.
631 DCHECK(!item.bytes_transfered);
632 InterlockedExchange(&have_work_, 0);
633 return true;
635 return false;
638 // Returns a completion item that was previously received.
639 bool MessagePumpForIO::MatchCompletedIOItem(IOHandler* filter, IOItem* item) {
640 DCHECK(!completed_io_.empty());
641 for (std::list<IOItem>::iterator it = completed_io_.begin();
642 it != completed_io_.end(); ++it) {
643 if (!filter || it->handler == filter) {
644 *item = *it;
645 completed_io_.erase(it);
646 return true;
649 return false;
652 void MessagePumpForIO::AddIOObserver(IOObserver *obs) {
653 io_observers_.AddObserver(obs);
656 void MessagePumpForIO::RemoveIOObserver(IOObserver *obs) {
657 io_observers_.RemoveObserver(obs);
660 void MessagePumpForIO::WillProcessIOEvent() {
661 FOR_EACH_OBSERVER(IOObserver, io_observers_, WillProcessIOEvent());
664 void MessagePumpForIO::DidProcessIOEvent() {
665 FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent());
668 // static
669 ULONG_PTR MessagePumpForIO::HandlerToKey(IOHandler* handler,
670 bool has_valid_io_context) {
671 ULONG_PTR key = reinterpret_cast<ULONG_PTR>(handler);
673 // |IOHandler| is at least pointer-size aligned, so the lowest two bits are
674 // always cleared. We use the lowest bit to distinguish completion keys with
675 // and without the associated |IOContext|.
676 DCHECK((key & 1) == 0);
678 // Mark the completion key as context-less.
679 if (!has_valid_io_context)
680 key = key | 1;
681 return key;
684 // static
685 MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler(
686 ULONG_PTR key,
687 bool* has_valid_io_context) {
688 *has_valid_io_context = ((key & 1) == 0);
689 return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1));
692 } // namespace base