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