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