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