ipc/chromium/src/base/message_pump_win.cc

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 // Copyright (c) 2009 The Chromium Authors. All rights reserved.
michael@0 2 // Use of this source code is governed by a BSD-style license that can be
michael@0 3 // found in the LICENSE file.
michael@0 4
michael@0 5 #include "base/message_pump_win.h"
michael@0 6
michael@0 7 #include <math.h>
michael@0 8
michael@0 9 #include "base/message_loop.h"
michael@0 10 #include "base/histogram.h"
michael@0 11 #include "base/win_util.h"
michael@0 12
michael@0 13 using base::Time;
michael@0 14
michael@0 15 namespace base {
michael@0 16
michael@0 17 static const wchar_t kWndClass[] = L"Chrome_MessagePumpWindow";
michael@0 18
michael@0 19 // Message sent to get an additional time slice for pumping (processing) another
michael@0 20 // task (a series of such messages creates a continuous task pump).
michael@0 21 static const int kMsgHaveWork = WM_USER + 1;
michael@0 22
michael@0 23 //-----------------------------------------------------------------------------
michael@0 24 // MessagePumpWin public:
michael@0 25
michael@0 26 void MessagePumpWin::AddObserver(Observer* observer) {
michael@0 27 observers_.AddObserver(observer);
michael@0 28 }
michael@0 29
michael@0 30 void MessagePumpWin::RemoveObserver(Observer* observer) {
michael@0 31 observers_.RemoveObserver(observer);
michael@0 32 }
michael@0 33
michael@0 34 void MessagePumpWin::WillProcessMessage(const MSG& msg) {
michael@0 35 FOR_EACH_OBSERVER(Observer, observers_, WillProcessMessage(msg));
michael@0 36 }
michael@0 37
michael@0 38 void MessagePumpWin::DidProcessMessage(const MSG& msg) {
michael@0 39 FOR_EACH_OBSERVER(Observer, observers_, DidProcessMessage(msg));
michael@0 40 }
michael@0 41
michael@0 42 void MessagePumpWin::RunWithDispatcher(
michael@0 43 Delegate* delegate, Dispatcher* dispatcher) {
michael@0 44 RunState s;
michael@0 45 s.delegate = delegate;
michael@0 46 s.dispatcher = dispatcher;
michael@0 47 s.should_quit = false;
michael@0 48 s.run_depth = state_ ? state_->run_depth + 1 : 1;
michael@0 49
michael@0 50 RunState* previous_state = state_;
michael@0 51 state_ = &s;
michael@0 52
michael@0 53 DoRunLoop();
michael@0 54
michael@0 55 state_ = previous_state;
michael@0 56 }
michael@0 57
michael@0 58 void MessagePumpWin::Quit() {
michael@0 59 DCHECK(state_);
michael@0 60 state_->should_quit = true;
michael@0 61 }
michael@0 62
michael@0 63 //-----------------------------------------------------------------------------
michael@0 64 // MessagePumpWin protected:
michael@0 65
michael@0 66 int MessagePumpWin::GetCurrentDelay() const {
michael@0 67 if (delayed_work_time_.is_null())
michael@0 68 return -1;
michael@0 69
michael@0 70 // Be careful here. TimeDelta has a precision of microseconds, but we want a
michael@0 71 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
michael@0 72 // 6? It should be 6 to avoid executing delayed work too early.
michael@0 73 double timeout =
michael@0 74 ceil((delayed_work_time_ - TimeTicks::Now()).InMillisecondsF());
michael@0 75
michael@0 76 // If this value is negative, then we need to run delayed work soon.
michael@0 77 int delay = static_cast<int>(timeout);
michael@0 78 if (delay < 0)
michael@0 79 delay = 0;
michael@0 80
michael@0 81 return delay;
michael@0 82 }
michael@0 83
michael@0 84 //-----------------------------------------------------------------------------
michael@0 85 // MessagePumpForUI public:
michael@0 86
michael@0 87 MessagePumpForUI::MessagePumpForUI() {
michael@0 88 InitMessageWnd();
michael@0 89 }
michael@0 90
michael@0 91 MessagePumpForUI::~MessagePumpForUI() {
michael@0 92 DestroyWindow(message_hwnd_);
michael@0 93 UnregisterClass(kWndClass, GetModuleHandle(NULL));
michael@0 94 }
michael@0 95
michael@0 96 void MessagePumpForUI::ScheduleWork() {
michael@0 97 if (InterlockedExchange(&have_work_, 1))
michael@0 98 return; // Someone else continued the pumping.
michael@0 99
michael@0 100 // Make sure the MessagePump does some work for us.
michael@0 101 PostMessage(message_hwnd_, kMsgHaveWork, reinterpret_cast<WPARAM>(this), 0);
michael@0 102
michael@0 103 // In order to wake up any cross-process COM calls which may currently be
michael@0 104 // pending on the main thread, we also have to post a UI message.
michael@0 105 PostMessage(message_hwnd_, WM_NULL, 0, 0);
michael@0 106 }
michael@0 107
michael@0 108 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
michael@0 109 //
michael@0 110 // We would *like* to provide high resolution timers. Windows timers using
michael@0 111 // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
michael@0 112 // mechanism because the application can enter modal windows loops where it
michael@0 113 // is not running our MessageLoop; the only way to have our timers fire in
michael@0 114 // these cases is to post messages there.
michael@0 115 //
michael@0 116 // To provide sub-10ms timers, we process timers directly from our run loop.
michael@0 117 // For the common case, timers will be processed there as the run loop does
michael@0 118 // its normal work. However, we *also* set the system timer so that WM_TIMER
michael@0 119 // events fire. This mops up the case of timers not being able to work in
michael@0 120 // modal message loops. It is possible for the SetTimer to pop and have no
michael@0 121 // pending timers, because they could have already been processed by the
michael@0 122 // run loop itself.
michael@0 123 //
michael@0 124 // We use a single SetTimer corresponding to the timer that will expire
michael@0 125 // soonest. As new timers are created and destroyed, we update SetTimer.
michael@0 126 // Getting a spurrious SetTimer event firing is benign, as we'll just be
michael@0 127 // processing an empty timer queue.
michael@0 128 //
michael@0 129 delayed_work_time_ = delayed_work_time;
michael@0 130
michael@0 131 int delay_msec = GetCurrentDelay();
michael@0 132 DCHECK(delay_msec >= 0);
michael@0 133 if (delay_msec < USER_TIMER_MINIMUM)
michael@0 134 delay_msec = USER_TIMER_MINIMUM;
michael@0 135
michael@0 136 // Create a WM_TIMER event that will wake us up to check for any pending
michael@0 137 // timers (in case we are running within a nested, external sub-pump).
michael@0 138 SetTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this), delay_msec, NULL);
michael@0 139 }
michael@0 140
michael@0 141 void MessagePumpForUI::PumpOutPendingPaintMessages() {
michael@0 142 // If we are being called outside of the context of Run, then don't try to do
michael@0 143 // any work.
michael@0 144 if (!state_)
michael@0 145 return;
michael@0 146
michael@0 147 // Create a mini-message-pump to force immediate processing of only Windows
michael@0 148 // WM_PAINT messages. Don't provide an infinite loop, but do enough peeking
michael@0 149 // to get the job done. Actual common max is 4 peeks, but we'll be a little
michael@0 150 // safe here.
michael@0 151 const int kMaxPeekCount = 20;
michael@0 152 bool win2k = win_util::GetWinVersion() <= win_util::WINVERSION_2000;
michael@0 153 int peek_count;
michael@0 154 for (peek_count = 0; peek_count < kMaxPeekCount; ++peek_count) {
michael@0 155 MSG msg;
michael@0 156 if (win2k) {
michael@0 157 if (!PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE))
michael@0 158 break;
michael@0 159 } else {
michael@0 160 if (!PeekMessage(&msg, NULL, 0, 0, PM_REMOVE | PM_QS_PAINT))
michael@0 161 break;
michael@0 162 }
michael@0 163 ProcessMessageHelper(msg);
michael@0 164 if (state_->should_quit) // Handle WM_QUIT.
michael@0 165 break;
michael@0 166 }
michael@0 167 // Histogram what was really being used, to help to adjust kMaxPeekCount.
michael@0 168 DHISTOGRAM_COUNTS("Loop.PumpOutPendingPaintMessages Peeks", peek_count);
michael@0 169 }
michael@0 170
michael@0 171 //-----------------------------------------------------------------------------
michael@0 172 // MessagePumpForUI private:
michael@0 173
michael@0 174 // static
michael@0 175 LRESULT CALLBACK MessagePumpForUI::WndProcThunk(
michael@0 176 HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
michael@0 177 switch (message) {
michael@0 178 case kMsgHaveWork:
michael@0 179 reinterpret_cast<MessagePumpForUI*>(wparam)->HandleWorkMessage();
michael@0 180 break;
michael@0 181 case WM_TIMER:
michael@0 182 reinterpret_cast<MessagePumpForUI*>(wparam)->HandleTimerMessage();
michael@0 183 break;
michael@0 184 }
michael@0 185 return DefWindowProc(hwnd, message, wparam, lparam);
michael@0 186 }
michael@0 187
michael@0 188 void MessagePumpForUI::DoRunLoop() {
michael@0 189 // IF this was just a simple PeekMessage() loop (servicing all possible work
michael@0 190 // queues), then Windows would try to achieve the following order according
michael@0 191 // to MSDN documentation about PeekMessage with no filter):
michael@0 192 // * Sent messages
michael@0 193 // * Posted messages
michael@0 194 // * Sent messages (again)
michael@0 195 // * WM_PAINT messages
michael@0 196 // * WM_TIMER messages
michael@0 197 //
michael@0 198 // Summary: none of the above classes is starved, and sent messages has twice
michael@0 199 // the chance of being processed (i.e., reduced service time).
michael@0 200
michael@0 201 for (;;) {
michael@0 202 // If we do any work, we may create more messages etc., and more work may
michael@0 203 // possibly be waiting in another task group. When we (for example)
michael@0 204 // ProcessNextWindowsMessage(), there is a good chance there are still more
michael@0 205 // messages waiting. On the other hand, when any of these methods return
michael@0 206 // having done no work, then it is pretty unlikely that calling them again
michael@0 207 // quickly will find any work to do. Finally, if they all say they had no
michael@0 208 // work, then it is a good time to consider sleeping (waiting) for more
michael@0 209 // work.
michael@0 210
michael@0 211 bool more_work_is_plausible = ProcessNextWindowsMessage();
michael@0 212 if (state_->should_quit)
michael@0 213 break;
michael@0 214
michael@0 215 more_work_is_plausible |= state_->delegate->DoWork();
michael@0 216 if (state_->should_quit)
michael@0 217 break;
michael@0 218
michael@0 219 more_work_is_plausible |=
michael@0 220 state_->delegate->DoDelayedWork(&delayed_work_time_);
michael@0 221 // If we did not process any delayed work, then we can assume that our
michael@0 222 // existing WM_TIMER if any will fire when delayed work should run. We
michael@0 223 // don't want to disturb that timer if it is already in flight. However,
michael@0 224 // if we did do all remaining delayed work, then lets kill the WM_TIMER.
michael@0 225 if (more_work_is_plausible && delayed_work_time_.is_null())
michael@0 226 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
michael@0 227 if (state_->should_quit)
michael@0 228 break;
michael@0 229
michael@0 230 if (more_work_is_plausible)
michael@0 231 continue;
michael@0 232
michael@0 233 more_work_is_plausible = state_->delegate->DoIdleWork();
michael@0 234 if (state_->should_quit)
michael@0 235 break;
michael@0 236
michael@0 237 if (more_work_is_plausible)
michael@0 238 continue;
michael@0 239
michael@0 240 WaitForWork(); // Wait (sleep) until we have work to do again.
michael@0 241 }
michael@0 242 }
michael@0 243
michael@0 244 void MessagePumpForUI::InitMessageWnd() {
michael@0 245 HINSTANCE hinst = GetModuleHandle(NULL);
michael@0 246
michael@0 247 WNDCLASSEX wc = {0};
michael@0 248 wc.cbSize = sizeof(wc);
michael@0 249 wc.lpfnWndProc = WndProcThunk;
michael@0 250 wc.hInstance = hinst;
michael@0 251 wc.lpszClassName = kWndClass;
michael@0 252 RegisterClassEx(&wc);
michael@0 253
michael@0 254 message_hwnd_ =
michael@0 255 CreateWindow(kWndClass, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, 0);
michael@0 256 DCHECK(message_hwnd_);
michael@0 257 }
michael@0 258
michael@0 259 void MessagePumpForUI::WaitForWork() {
michael@0 260 // Wait until a message is available, up to the time needed by the timer
michael@0 261 // manager to fire the next set of timers.
michael@0 262 int delay = GetCurrentDelay();
michael@0 263 if (delay < 0) // Negative value means no timers waiting.
michael@0 264 delay = INFINITE;
michael@0 265
michael@0 266 DWORD result;
michael@0 267 result = MsgWaitForMultipleObjectsEx(0, NULL, delay, QS_ALLINPUT,
michael@0 268 MWMO_INPUTAVAILABLE);
michael@0 269
michael@0 270 if (WAIT_OBJECT_0 == result) {
michael@0 271 // A WM_* message is available.
michael@0 272 // If a parent child relationship exists between windows across threads
michael@0 273 // then their thread inputs are implicitly attached.
michael@0 274 // This causes the MsgWaitForMultipleObjectsEx API to return indicating
michael@0 275 // that messages are ready for processing (specifically mouse messages
michael@0 276 // intended for the child window. Occurs if the child window has capture)
michael@0 277 // The subsequent PeekMessages call fails to return any messages thus
michael@0 278 // causing us to enter a tight loop at times.
michael@0 279 // The WaitMessage call below is a workaround to give the child window
michael@0 280 // sometime to process its input messages.
michael@0 281 MSG msg = {0};
michael@0 282 DWORD queue_status = GetQueueStatus(QS_MOUSE);
michael@0 283 if (HIWORD(queue_status) & QS_MOUSE &&
michael@0 284 !PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_NOREMOVE)) {
michael@0 285 WaitMessage();
michael@0 286 }
michael@0 287 return;
michael@0 288 }
michael@0 289
michael@0 290 DCHECK_NE(WAIT_FAILED, result) << GetLastError();
michael@0 291 }
michael@0 292
michael@0 293 void MessagePumpForUI::HandleWorkMessage() {
michael@0 294 // If we are being called outside of the context of Run, then don't try to do
michael@0 295 // any work. This could correspond to a MessageBox call or something of that
michael@0 296 // sort.
michael@0 297 if (!state_) {
michael@0 298 // Since we handled a kMsgHaveWork message, we must still update this flag.
michael@0 299 InterlockedExchange(&have_work_, 0);
michael@0 300 return;
michael@0 301 }
michael@0 302
michael@0 303 // Let whatever would have run had we not been putting messages in the queue
michael@0 304 // run now. This is an attempt to make our dummy message not starve other
michael@0 305 // messages that may be in the Windows message queue.
michael@0 306 ProcessPumpReplacementMessage();
michael@0 307
michael@0 308 // Now give the delegate a chance to do some work. He'll let us know if he
michael@0 309 // needs to do more work.
michael@0 310 if (state_->delegate->DoWork())
michael@0 311 ScheduleWork();
michael@0 312 }
michael@0 313
michael@0 314 void MessagePumpForUI::HandleTimerMessage() {
michael@0 315 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
michael@0 316
michael@0 317 // If we are being called outside of the context of Run, then don't do
michael@0 318 // anything. This could correspond to a MessageBox call or something of
michael@0 319 // that sort.
michael@0 320 if (!state_)
michael@0 321 return;
michael@0 322
michael@0 323 state_->delegate->DoDelayedWork(&delayed_work_time_);
michael@0 324 if (!delayed_work_time_.is_null()) {
michael@0 325 // A bit gratuitous to set delayed_work_time_ again, but oh well.
michael@0 326 ScheduleDelayedWork(delayed_work_time_);
michael@0 327 }
michael@0 328 }
michael@0 329
michael@0 330 bool MessagePumpForUI::ProcessNextWindowsMessage() {
michael@0 331 // If there are sent messages in the queue then PeekMessage internally
michael@0 332 // dispatches the message and returns false. We return true in this
michael@0 333 // case to ensure that the message loop peeks again instead of calling
michael@0 334 // MsgWaitForMultipleObjectsEx again.
michael@0 335 bool sent_messages_in_queue = false;
michael@0 336 DWORD queue_status = GetQueueStatus(QS_SENDMESSAGE);
michael@0 337 if (HIWORD(queue_status) & QS_SENDMESSAGE)
michael@0 338 sent_messages_in_queue = true;
michael@0 339
michael@0 340 MSG msg;
michael@0 341 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
michael@0 342 return ProcessMessageHelper(msg);
michael@0 343
michael@0 344 return sent_messages_in_queue;
michael@0 345 }
michael@0 346
michael@0 347 bool MessagePumpForUI::ProcessMessageHelper(const MSG& msg) {
michael@0 348 if (WM_QUIT == msg.message) {
michael@0 349 // Repost the QUIT message so that it will be retrieved by the primary
michael@0 350 // GetMessage() loop.
michael@0 351 state_->should_quit = true;
michael@0 352 PostQuitMessage(static_cast<int>(msg.wParam));
michael@0 353 return false;
michael@0 354 }
michael@0 355
michael@0 356 // While running our main message pump, we discard kMsgHaveWork messages.
michael@0 357 if (msg.message == kMsgHaveWork && msg.hwnd == message_hwnd_)
michael@0 358 return ProcessPumpReplacementMessage();
michael@0 359
michael@0 360 WillProcessMessage(msg);
michael@0 361
michael@0 362 if (state_->dispatcher) {
michael@0 363 if (!state_->dispatcher->Dispatch(msg))
michael@0 364 state_->should_quit = true;
michael@0 365 } else {
michael@0 366 TranslateMessage(&msg);
michael@0 367 DispatchMessage(&msg);
michael@0 368 }
michael@0 369
michael@0 370 DidProcessMessage(msg);
michael@0 371 return true;
michael@0 372 }
michael@0 373
michael@0 374 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
michael@0 375 // When we encounter a kMsgHaveWork message, this method is called to peek
michael@0 376 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
michael@0 377 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
michael@0 378 // a continuous stream of such messages are posted. This method carefully
michael@0 379 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
michael@0 380 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
michael@0 381 // possibly be posted), and finally dispatches that peeked replacement. Note
michael@0 382 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
michael@0 383
michael@0 384 MSG msg;
michael@0 385 bool have_message = false;
michael@0 386 if (MessageLoop::current()->os_modal_loop()) {
michael@0 387 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
michael@0 388 have_message = PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE) ||
michael@0 389 PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
michael@0 390 } else {
michael@0 391 have_message = (0 != PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
michael@0 392
michael@0 393 if (have_message && msg.message == WM_NULL)
michael@0 394 have_message = (0 != PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
michael@0 395 }
michael@0 396
michael@0 397 DCHECK(!have_message || kMsgHaveWork != msg.message ||
michael@0 398 msg.hwnd != message_hwnd_);
michael@0 399
michael@0 400 // Since we discarded a kMsgHaveWork message, we must update the flag.
michael@0 401 int old_have_work = InterlockedExchange(&have_work_, 0);
michael@0 402 DCHECK(old_have_work);
michael@0 403
michael@0 404 // We don't need a special time slice if we didn't have_message to process.
michael@0 405 if (!have_message)
michael@0 406 return false;
michael@0 407
michael@0 408 // Guarantee we'll get another time slice in the case where we go into native
michael@0 409 // windows code. This ScheduleWork() may hurt performance a tiny bit when
michael@0 410 // tasks appear very infrequently, but when the event queue is busy, the
michael@0 411 // kMsgHaveWork events get (percentage wise) rarer and rarer.
michael@0 412 ScheduleWork();
michael@0 413 return ProcessMessageHelper(msg);
michael@0 414 }
michael@0 415
michael@0 416 //-----------------------------------------------------------------------------
michael@0 417 // MessagePumpForIO public:
michael@0 418
michael@0 419 MessagePumpForIO::MessagePumpForIO() {
michael@0 420 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1));
michael@0 421 DCHECK(port_.IsValid());
michael@0 422 }
michael@0 423
michael@0 424 void MessagePumpForIO::ScheduleWork() {
michael@0 425 if (InterlockedExchange(&have_work_, 1))
michael@0 426 return; // Someone else continued the pumping.
michael@0 427
michael@0 428 // Make sure the MessagePump does some work for us.
michael@0 429 BOOL ret = PostQueuedCompletionStatus(port_, 0,
michael@0 430 reinterpret_cast<ULONG_PTR>(this),
michael@0 431 reinterpret_cast<OVERLAPPED*>(this));
michael@0 432 DCHECK(ret);
michael@0 433 }
michael@0 434
michael@0 435 void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
michael@0 436 // We know that we can't be blocked right now since this method can only be
michael@0 437 // called on the same thread as Run, so we only need to update our record of
michael@0 438 // how long to sleep when we do sleep.
michael@0 439 delayed_work_time_ = delayed_work_time;
michael@0 440 }
michael@0 441
michael@0 442 void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle,
michael@0 443 IOHandler* handler) {
michael@0 444 ULONG_PTR key = reinterpret_cast<ULONG_PTR>(handler);
michael@0 445 HANDLE port = CreateIoCompletionPort(file_handle, port_, key, 1);
michael@0 446 DCHECK(port == port_.Get());
michael@0 447 }
michael@0 448
michael@0 449 //-----------------------------------------------------------------------------
michael@0 450 // MessagePumpForIO private:
michael@0 451
michael@0 452 void MessagePumpForIO::DoRunLoop() {
michael@0 453 for (;;) {
michael@0 454 // If we do any work, we may create more messages etc., and more work may
michael@0 455 // possibly be waiting in another task group. When we (for example)
michael@0 456 // WaitForIOCompletion(), there is a good chance there are still more
michael@0 457 // messages waiting. On the other hand, when any of these methods return
michael@0 458 // having done no work, then it is pretty unlikely that calling them
michael@0 459 // again quickly will find any work to do. Finally, if they all say they
michael@0 460 // had no work, then it is a good time to consider sleeping (waiting) for
michael@0 461 // more work.
michael@0 462
michael@0 463 bool more_work_is_plausible = state_->delegate->DoWork();
michael@0 464 if (state_->should_quit)
michael@0 465 break;
michael@0 466
michael@0 467 more_work_is_plausible |= WaitForIOCompletion(0, NULL);
michael@0 468 if (state_->should_quit)
michael@0 469 break;
michael@0 470
michael@0 471 more_work_is_plausible |=
michael@0 472 state_->delegate->DoDelayedWork(&delayed_work_time_);
michael@0 473 if (state_->should_quit)
michael@0 474 break;
michael@0 475
michael@0 476 if (more_work_is_plausible)
michael@0 477 continue;
michael@0 478
michael@0 479 more_work_is_plausible = state_->delegate->DoIdleWork();
michael@0 480 if (state_->should_quit)
michael@0 481 break;
michael@0 482
michael@0 483 if (more_work_is_plausible)
michael@0 484 continue;
michael@0 485
michael@0 486 WaitForWork(); // Wait (sleep) until we have work to do again.
michael@0 487 }
michael@0 488 }
michael@0 489
michael@0 490 // Wait until IO completes, up to the time needed by the timer manager to fire
michael@0 491 // the next set of timers.
michael@0 492 void MessagePumpForIO::WaitForWork() {
michael@0 493 // We do not support nested IO message loops. This is to avoid messy
michael@0 494 // recursion problems.
michael@0 495 DCHECK(state_->run_depth == 1) << "Cannot nest an IO message loop!";
michael@0 496
michael@0 497 int timeout = GetCurrentDelay();
michael@0 498 if (timeout < 0) // Negative value means no timers waiting.
michael@0 499 timeout = INFINITE;
michael@0 500
michael@0 501 WaitForIOCompletion(timeout, NULL);
michael@0 502 }
michael@0 503
michael@0 504 bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
michael@0 505 IOItem item;
michael@0 506 if (completed_io_.empty() || !MatchCompletedIOItem(filter, &item)) {
michael@0 507 // We have to ask the system for another IO completion.
michael@0 508 if (!GetIOItem(timeout, &item))
michael@0 509 return false;
michael@0 510
michael@0 511 if (ProcessInternalIOItem(item))
michael@0 512 return true;
michael@0 513 }
michael@0 514
michael@0 515 if (item.context->handler) {
michael@0 516 if (filter && item.handler != filter) {
michael@0 517 // Save this item for later
michael@0 518 completed_io_.push_back(item);
michael@0 519 } else {
michael@0 520 DCHECK(item.context->handler == item.handler);
michael@0 521 item.handler->OnIOCompleted(item.context, item.bytes_transfered,
michael@0 522 item.error);
michael@0 523 }
michael@0 524 } else {
michael@0 525 // The handler must be gone by now, just cleanup the mess.
michael@0 526 delete item.context;
michael@0 527 }
michael@0 528 return true;
michael@0 529 }
michael@0 530
michael@0 531 // Asks the OS for another IO completion result.
michael@0 532 bool MessagePumpForIO::GetIOItem(DWORD timeout, IOItem* item) {
michael@0 533 memset(item, 0, sizeof(*item));
michael@0 534 ULONG_PTR key = 0;
michael@0 535 OVERLAPPED* overlapped = NULL;
michael@0 536 if (!GetQueuedCompletionStatus(port_.Get(), &item->bytes_transfered, &key,
michael@0 537 &overlapped, timeout)) {
michael@0 538 if (!overlapped)
michael@0 539 return false; // Nothing in the queue.
michael@0 540 item->error = GetLastError();
michael@0 541 item->bytes_transfered = 0;
michael@0 542 }
michael@0 543
michael@0 544 item->handler = reinterpret_cast<IOHandler*>(key);
michael@0 545 item->context = reinterpret_cast<IOContext*>(overlapped);
michael@0 546 return true;
michael@0 547 }
michael@0 548
michael@0 549 bool MessagePumpForIO::ProcessInternalIOItem(const IOItem& item) {
michael@0 550 if (this == reinterpret_cast<MessagePumpForIO*>(item.context) &&
michael@0 551 this == reinterpret_cast<MessagePumpForIO*>(item.handler)) {
michael@0 552 // This is our internal completion.
michael@0 553 DCHECK(!item.bytes_transfered);
michael@0 554 InterlockedExchange(&have_work_, 0);
michael@0 555 return true;
michael@0 556 }
michael@0 557 return false;
michael@0 558 }
michael@0 559
michael@0 560 // Returns a completion item that was previously received.
michael@0 561 bool MessagePumpForIO::MatchCompletedIOItem(IOHandler* filter, IOItem* item) {
michael@0 562 DCHECK(!completed_io_.empty());
michael@0 563 for (std::list<IOItem>::iterator it = completed_io_.begin();
michael@0 564 it != completed_io_.end(); ++it) {
michael@0 565 if (!filter || it->handler == filter) {
michael@0 566 *item = *it;
michael@0 567 completed_io_.erase(it);
michael@0 568 return true;
michael@0 569 }
michael@0 570 }
michael@0 571 return false;
michael@0 572 }
michael@0 573
michael@0 574 } // namespace base

mercurial