1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/message_pump_win.h"
9 #include "base/debug/trace_event.h"
10 #include "base/message_loop.h"
11 #include "base/metrics/histogram.h"
12 #include "base/process_util.h"
13 #include "base/win/wrapped_window_proc.h"
17 enum MessageLoopProblems
{
19 COMPLETION_POST_ERROR
,
21 MESSAGE_LOOP_PROBLEM_MAX
,
28 static const wchar_t kWndClass
[] = L
"Chrome_MessagePumpWindow";
30 // Message sent to get an additional time slice for pumping (processing) another
31 // task (a series of such messages creates a continuous task pump).
32 static const int kMsgHaveWork
= WM_USER
+ 1;
34 //-----------------------------------------------------------------------------
35 // MessagePumpWin public:
37 void MessagePumpWin::AddObserver(MessagePumpObserver
* observer
) {
38 observers_
.AddObserver(observer
);
41 void MessagePumpWin::RemoveObserver(MessagePumpObserver
* observer
) {
42 observers_
.RemoveObserver(observer
);
45 void MessagePumpWin::WillProcessMessage(const MSG
& msg
) {
46 FOR_EACH_OBSERVER(MessagePumpObserver
, observers_
, WillProcessEvent(msg
));
49 void MessagePumpWin::DidProcessMessage(const MSG
& msg
) {
50 FOR_EACH_OBSERVER(MessagePumpObserver
, observers_
, DidProcessEvent(msg
));
53 void MessagePumpWin::RunWithDispatcher(
54 Delegate
* delegate
, MessagePumpDispatcher
* dispatcher
) {
56 s
.delegate
= delegate
;
57 s
.dispatcher
= dispatcher
;
58 s
.should_quit
= false;
59 s
.run_depth
= state_
? state_
->run_depth
+ 1 : 1;
61 RunState
* previous_state
= state_
;
66 state_
= previous_state
;
69 void MessagePumpWin::Quit() {
71 state_
->should_quit
= true;
74 //-----------------------------------------------------------------------------
75 // MessagePumpWin protected:
77 int MessagePumpWin::GetCurrentDelay() const {
78 if (delayed_work_time_
.is_null())
81 // Be careful here. TimeDelta has a precision of microseconds, but we want a
82 // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
83 // 6? It should be 6 to avoid executing delayed work too early.
85 ceil((delayed_work_time_
- TimeTicks::Now()).InMillisecondsF());
87 // If this value is negative, then we need to run delayed work soon.
88 int delay
= static_cast<int>(timeout
);
95 //-----------------------------------------------------------------------------
96 // MessagePumpForUI public:
98 MessagePumpForUI::MessagePumpForUI()
100 message_filter_(new MessageFilter
) {
104 MessagePumpForUI::~MessagePumpForUI() {
105 DestroyWindow(message_hwnd_
);
106 UnregisterClass(kWndClass
, instance_
);
109 void MessagePumpForUI::ScheduleWork() {
110 if (InterlockedExchange(&have_work_
, 1))
111 return; // Someone else continued the pumping.
113 // Make sure the MessagePump does some work for us.
114 BOOL ret
= PostMessage(message_hwnd_
, kMsgHaveWork
,
115 reinterpret_cast<WPARAM
>(this), 0);
117 return; // There was room in the Window Message queue.
119 // We have failed to insert a have-work message, so there is a chance that we
120 // will starve tasks/timers while sitting in a nested message loop. Nested
121 // loops only look at Windows Message queues, and don't look at *our* task
122 // queues, etc., so we might not get a time slice in such. :-(
123 // We could abort here, but the fear is that this failure mode is plausibly
124 // common (queue is full, of about 2000 messages), so we'll do a near-graceful
125 // recovery. Nested loops are pretty transient (we think), so this will
126 // probably be recoverable.
127 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't really insert.
128 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR
,
129 MESSAGE_LOOP_PROBLEM_MAX
);
132 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
134 // We would *like* to provide high resolution timers. Windows timers using
135 // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
136 // mechanism because the application can enter modal windows loops where it
137 // is not running our MessageLoop; the only way to have our timers fire in
138 // these cases is to post messages there.
140 // To provide sub-10ms timers, we process timers directly from our run loop.
141 // For the common case, timers will be processed there as the run loop does
142 // its normal work. However, we *also* set the system timer so that WM_TIMER
143 // events fire. This mops up the case of timers not being able to work in
144 // modal message loops. It is possible for the SetTimer to pop and have no
145 // pending timers, because they could have already been processed by the
148 // We use a single SetTimer corresponding to the timer that will expire
149 // soonest. As new timers are created and destroyed, we update SetTimer.
150 // Getting a spurrious SetTimer event firing is benign, as we'll just be
151 // processing an empty timer queue.
153 delayed_work_time_
= delayed_work_time
;
155 int delay_msec
= GetCurrentDelay();
156 DCHECK_GE(delay_msec
, 0);
157 if (delay_msec
< USER_TIMER_MINIMUM
)
158 delay_msec
= USER_TIMER_MINIMUM
;
160 // Create a WM_TIMER event that will wake us up to check for any pending
161 // timers (in case we are running within a nested, external sub-pump).
162 BOOL ret
= SetTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this),
166 // If we can't set timers, we are in big trouble... but cross our fingers for
168 // TODO(jar): If we don't see this error, use a CHECK() here instead.
169 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", SET_TIMER_ERROR
,
170 MESSAGE_LOOP_PROBLEM_MAX
);
173 void MessagePumpForUI::PumpOutPendingPaintMessages() {
174 // If we are being called outside of the context of Run, then don't try to do
179 // Create a mini-message-pump to force immediate processing of only Windows
180 // WM_PAINT messages. Don't provide an infinite loop, but do enough peeking
181 // to get the job done. Actual common max is 4 peeks, but we'll be a little
183 const int kMaxPeekCount
= 20;
185 for (peek_count
= 0; peek_count
< kMaxPeekCount
; ++peek_count
) {
187 if (!PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
| PM_QS_PAINT
))
189 ProcessMessageHelper(msg
);
190 if (state_
->should_quit
) // Handle WM_QUIT.
193 // Histogram what was really being used, to help to adjust kMaxPeekCount.
194 DHISTOGRAM_COUNTS("Loop.PumpOutPendingPaintMessages Peeks", peek_count
);
197 //-----------------------------------------------------------------------------
198 // MessagePumpForUI private:
201 LRESULT CALLBACK
MessagePumpForUI::WndProcThunk(
202 HWND hwnd
, UINT message
, WPARAM wparam
, LPARAM lparam
) {
205 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleWorkMessage();
208 reinterpret_cast<MessagePumpForUI
*>(wparam
)->HandleTimerMessage();
211 return DefWindowProc(hwnd
, message
, wparam
, lparam
);
214 void MessagePumpForUI::DoRunLoop() {
215 // IF this was just a simple PeekMessage() loop (servicing all possible work
216 // queues), then Windows would try to achieve the following order according
217 // to MSDN documentation about PeekMessage with no filter):
220 // * Sent messages (again)
221 // * WM_PAINT messages
222 // * WM_TIMER messages
224 // Summary: none of the above classes is starved, and sent messages has twice
225 // the chance of being processed (i.e., reduced service time).
228 // If we do any work, we may create more messages etc., and more work may
229 // possibly be waiting in another task group. When we (for example)
230 // ProcessNextWindowsMessage(), there is a good chance there are still more
231 // messages waiting. On the other hand, when any of these methods return
232 // having done no work, then it is pretty unlikely that calling them again
233 // quickly will find any work to do. Finally, if they all say they had no
234 // work, then it is a good time to consider sleeping (waiting) for more
237 bool more_work_is_plausible
= ProcessNextWindowsMessage();
238 if (state_
->should_quit
)
241 more_work_is_plausible
|= state_
->delegate
->DoWork();
242 if (state_
->should_quit
)
245 more_work_is_plausible
|=
246 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
247 // If we did not process any delayed work, then we can assume that our
248 // existing WM_TIMER if any will fire when delayed work should run. We
249 // don't want to disturb that timer if it is already in flight. However,
250 // if we did do all remaining delayed work, then lets kill the WM_TIMER.
251 if (more_work_is_plausible
&& delayed_work_time_
.is_null())
252 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
253 if (state_
->should_quit
)
256 if (more_work_is_plausible
)
259 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
260 if (state_
->should_quit
)
263 if (more_work_is_plausible
)
266 WaitForWork(); // Wait (sleep) until we have work to do again.
270 void MessagePumpForUI::InitMessageWnd() {
272 wc
.cbSize
= sizeof(wc
);
273 wc
.lpfnWndProc
= base::win::WrappedWindowProc
<WndProcThunk
>;
274 wc
.hInstance
= base::GetModuleFromAddress(wc
.lpfnWndProc
);
275 wc
.lpszClassName
= kWndClass
;
276 instance_
= wc
.hInstance
;
277 RegisterClassEx(&wc
);
280 CreateWindow(kWndClass
, 0, 0, 0, 0, 0, 0, HWND_MESSAGE
, 0, instance_
, 0);
281 DCHECK(message_hwnd_
);
284 void MessagePumpForUI::WaitForWork() {
285 // Wait until a message is available, up to the time needed by the timer
286 // manager to fire the next set of timers.
287 int delay
= GetCurrentDelay();
288 if (delay
< 0) // Negative value means no timers waiting.
292 result
= MsgWaitForMultipleObjectsEx(0, NULL
, delay
, QS_ALLINPUT
,
293 MWMO_INPUTAVAILABLE
);
295 if (WAIT_OBJECT_0
== result
) {
296 // A WM_* message is available.
297 // If a parent child relationship exists between windows across threads
298 // then their thread inputs are implicitly attached.
299 // This causes the MsgWaitForMultipleObjectsEx API to return indicating
300 // that messages are ready for processing (Specifically, mouse messages
301 // intended for the child window may appear if the child window has
303 // The subsequent PeekMessages call may fail to return any messages thus
304 // causing us to enter a tight loop at times.
305 // The WaitMessage call below is a workaround to give the child window
306 // some time to process its input messages.
308 DWORD queue_status
= GetQueueStatus(QS_MOUSE
);
309 if (HIWORD(queue_status
) & QS_MOUSE
&&
310 !PeekMessage(&msg
, NULL
, WM_MOUSEFIRST
, WM_MOUSELAST
, PM_NOREMOVE
)) {
316 DCHECK_NE(WAIT_FAILED
, result
) << GetLastError();
319 void MessagePumpForUI::HandleWorkMessage() {
320 // If we are being called outside of the context of Run, then don't try to do
321 // any work. This could correspond to a MessageBox call or something of that
324 // Since we handled a kMsgHaveWork message, we must still update this flag.
325 InterlockedExchange(&have_work_
, 0);
329 // Let whatever would have run had we not been putting messages in the queue
330 // run now. This is an attempt to make our dummy message not starve other
331 // messages that may be in the Windows message queue.
332 ProcessPumpReplacementMessage();
334 // Now give the delegate a chance to do some work. He'll let us know if he
335 // needs to do more work.
336 if (state_
->delegate
->DoWork())
340 void MessagePumpForUI::HandleTimerMessage() {
341 KillTimer(message_hwnd_
, reinterpret_cast<UINT_PTR
>(this));
343 // If we are being called outside of the context of Run, then don't do
344 // anything. This could correspond to a MessageBox call or something of
349 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
350 if (!delayed_work_time_
.is_null()) {
351 // A bit gratuitous to set delayed_work_time_ again, but oh well.
352 ScheduleDelayedWork(delayed_work_time_
);
356 bool MessagePumpForUI::ProcessNextWindowsMessage() {
357 // If there are sent messages in the queue then PeekMessage internally
358 // dispatches the message and returns false. We return true in this
359 // case to ensure that the message loop peeks again instead of calling
360 // MsgWaitForMultipleObjectsEx again.
361 bool sent_messages_in_queue
= false;
362 DWORD queue_status
= GetQueueStatus(QS_SENDMESSAGE
);
363 if (HIWORD(queue_status
) & QS_SENDMESSAGE
)
364 sent_messages_in_queue
= true;
367 if (message_filter_
->DoPeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
))
368 return ProcessMessageHelper(msg
);
370 return sent_messages_in_queue
;
373 bool MessagePumpForUI::ProcessMessageHelper(const MSG
& msg
) {
374 TRACE_EVENT1("base", "MessagePumpForUI::ProcessMessageHelper",
375 "message", msg
.message
);
376 if (WM_QUIT
== msg
.message
) {
377 // Repost the QUIT message so that it will be retrieved by the primary
378 // GetMessage() loop.
379 state_
->should_quit
= true;
380 PostQuitMessage(static_cast<int>(msg
.wParam
));
384 // While running our main message pump, we discard kMsgHaveWork messages.
385 if (msg
.message
== kMsgHaveWork
&& msg
.hwnd
== message_hwnd_
)
386 return ProcessPumpReplacementMessage();
388 if (CallMsgFilter(const_cast<MSG
*>(&msg
), kMessageFilterCode
))
391 WillProcessMessage(msg
);
393 if (!message_filter_
->ProcessMessage(msg
)) {
394 if (state_
->dispatcher
) {
395 if (!state_
->dispatcher
->Dispatch(msg
))
396 state_
->should_quit
= true;
398 TranslateMessage(&msg
);
399 DispatchMessage(&msg
);
403 DidProcessMessage(msg
);
407 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
408 // When we encounter a kMsgHaveWork message, this method is called to peek
409 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
410 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
411 // a continuous stream of such messages are posted. This method carefully
412 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
413 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
414 // possibly be posted), and finally dispatches that peeked replacement. Note
415 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
417 bool have_message
= false;
419 // We should not process all window messages if we are in the context of an
420 // OS modal loop, i.e. in the context of a windows API call like MessageBox.
421 // This is to ensure that these messages are peeked out by the OS modal loop.
422 if (MessageLoop::current()->os_modal_loop()) {
423 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
424 have_message
= PeekMessage(&msg
, NULL
, WM_PAINT
, WM_PAINT
, PM_REMOVE
) ||
425 PeekMessage(&msg
, NULL
, WM_TIMER
, WM_TIMER
, PM_REMOVE
);
427 have_message
= !!message_filter_
->DoPeekMessage(&msg
, NULL
, 0, 0,
431 DCHECK(!have_message
|| kMsgHaveWork
!= msg
.message
||
432 msg
.hwnd
!= message_hwnd_
);
434 // Since we discarded a kMsgHaveWork message, we must update the flag.
435 int old_have_work
= InterlockedExchange(&have_work_
, 0);
436 DCHECK(old_have_work
);
438 // We don't need a special time slice if we didn't have_message to process.
442 // Guarantee we'll get another time slice in the case where we go into native
443 // windows code. This ScheduleWork() may hurt performance a tiny bit when
444 // tasks appear very infrequently, but when the event queue is busy, the
445 // kMsgHaveWork events get (percentage wise) rarer and rarer.
447 return ProcessMessageHelper(msg
);
450 void MessagePumpForUI::SetMessageFilter(
451 scoped_ptr
<MessageFilter
> message_filter
) {
452 message_filter_
= message_filter
.Pass();
455 //-----------------------------------------------------------------------------
456 // MessagePumpForIO public:
458 MessagePumpForIO::MessagePumpForIO() {
459 port_
.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE
, NULL
, NULL
, 1));
460 DCHECK(port_
.IsValid());
463 void MessagePumpForIO::ScheduleWork() {
464 if (InterlockedExchange(&have_work_
, 1))
465 return; // Someone else continued the pumping.
467 // Make sure the MessagePump does some work for us.
468 BOOL ret
= PostQueuedCompletionStatus(port_
, 0,
469 reinterpret_cast<ULONG_PTR
>(this),
470 reinterpret_cast<OVERLAPPED
*>(this));
472 return; // Post worked perfectly.
474 // See comment in MessagePumpForUI::ScheduleWork() for this error recovery.
475 InterlockedExchange(&have_work_
, 0); // Clarify that we didn't succeed.
476 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", COMPLETION_POST_ERROR
,
477 MESSAGE_LOOP_PROBLEM_MAX
);
480 void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) {
481 // We know that we can't be blocked right now since this method can only be
482 // called on the same thread as Run, so we only need to update our record of
483 // how long to sleep when we do sleep.
484 delayed_work_time_
= delayed_work_time
;
487 void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle
,
488 IOHandler
* handler
) {
489 ULONG_PTR key
= HandlerToKey(handler
, true);
490 HANDLE port
= CreateIoCompletionPort(file_handle
, port_
, key
, 1);
494 bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle
,
495 IOHandler
* handler
) {
496 // Job object notifications use the OVERLAPPED pointer to carry the message
497 // data. Mark the completion key correspondingly, so we will not try to
498 // convert OVERLAPPED* to IOContext*.
499 ULONG_PTR key
= HandlerToKey(handler
, false);
500 JOBOBJECT_ASSOCIATE_COMPLETION_PORT info
;
501 info
.CompletionKey
= reinterpret_cast<void*>(key
);
502 info
.CompletionPort
= port_
;
503 return SetInformationJobObject(job_handle
,
504 JobObjectAssociateCompletionPortInformation
,
506 sizeof(info
)) != FALSE
;
509 //-----------------------------------------------------------------------------
510 // MessagePumpForIO private:
512 void MessagePumpForIO::DoRunLoop() {
514 // If we do any work, we may create more messages etc., and more work may
515 // possibly be waiting in another task group. When we (for example)
516 // WaitForIOCompletion(), there is a good chance there are still more
517 // messages waiting. On the other hand, when any of these methods return
518 // having done no work, then it is pretty unlikely that calling them
519 // again quickly will find any work to do. Finally, if they all say they
520 // had no work, then it is a good time to consider sleeping (waiting) for
523 bool more_work_is_plausible
= state_
->delegate
->DoWork();
524 if (state_
->should_quit
)
527 more_work_is_plausible
|= WaitForIOCompletion(0, NULL
);
528 if (state_
->should_quit
)
531 more_work_is_plausible
|=
532 state_
->delegate
->DoDelayedWork(&delayed_work_time_
);
533 if (state_
->should_quit
)
536 if (more_work_is_plausible
)
539 more_work_is_plausible
= state_
->delegate
->DoIdleWork();
540 if (state_
->should_quit
)
543 if (more_work_is_plausible
)
546 WaitForWork(); // Wait (sleep) until we have work to do again.
550 // Wait until IO completes, up to the time needed by the timer manager to fire
551 // the next set of timers.
552 void MessagePumpForIO::WaitForWork() {
553 // We do not support nested IO message loops. This is to avoid messy
554 // recursion problems.
555 DCHECK_EQ(1, state_
->run_depth
) << "Cannot nest an IO message loop!";
557 int timeout
= GetCurrentDelay();
558 if (timeout
< 0) // Negative value means no timers waiting.
561 WaitForIOCompletion(timeout
, NULL
);
564 bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
) {
566 if (completed_io_
.empty() || !MatchCompletedIOItem(filter
, &item
)) {
567 // We have to ask the system for another IO completion.
568 if (!GetIOItem(timeout
, &item
))
571 if (ProcessInternalIOItem(item
))
575 // If |item.has_valid_io_context| is false then |item.context| does not point
576 // to a context structure, and so should not be dereferenced, although it may
577 // still hold valid non-pointer data.
578 if (!item
.has_valid_io_context
|| item
.context
->handler
) {
579 if (filter
&& item
.handler
!= filter
) {
580 // Save this item for later
581 completed_io_
.push_back(item
);
583 DCHECK(!item
.has_valid_io_context
||
584 (item
.context
->handler
== item
.handler
));
585 WillProcessIOEvent();
586 item
.handler
->OnIOCompleted(item
.context
, item
.bytes_transfered
,
591 // The handler must be gone by now, just cleanup the mess.
597 // Asks the OS for another IO completion result.
598 bool MessagePumpForIO::GetIOItem(DWORD timeout
, IOItem
* item
) {
599 memset(item
, 0, sizeof(*item
));
600 ULONG_PTR key
= NULL
;
601 OVERLAPPED
* overlapped
= NULL
;
602 if (!GetQueuedCompletionStatus(port_
.Get(), &item
->bytes_transfered
, &key
,
603 &overlapped
, timeout
)) {
605 return false; // Nothing in the queue.
606 item
->error
= GetLastError();
607 item
->bytes_transfered
= 0;
610 item
->handler
= KeyToHandler(key
, &item
->has_valid_io_context
);
611 item
->context
= reinterpret_cast<IOContext
*>(overlapped
);
615 bool MessagePumpForIO::ProcessInternalIOItem(const IOItem
& item
) {
616 if (this == reinterpret_cast<MessagePumpForIO
*>(item
.context
) &&
617 this == reinterpret_cast<MessagePumpForIO
*>(item
.handler
)) {
618 // This is our internal completion.
619 DCHECK(!item
.bytes_transfered
);
620 InterlockedExchange(&have_work_
, 0);
626 // Returns a completion item that was previously received.
627 bool MessagePumpForIO::MatchCompletedIOItem(IOHandler
* filter
, IOItem
* item
) {
628 DCHECK(!completed_io_
.empty());
629 for (std::list
<IOItem
>::iterator it
= completed_io_
.begin();
630 it
!= completed_io_
.end(); ++it
) {
631 if (!filter
|| it
->handler
== filter
) {
633 completed_io_
.erase(it
);
640 void MessagePumpForIO::AddIOObserver(IOObserver
*obs
) {
641 io_observers_
.AddObserver(obs
);
644 void MessagePumpForIO::RemoveIOObserver(IOObserver
*obs
) {
645 io_observers_
.RemoveObserver(obs
);
648 void MessagePumpForIO::WillProcessIOEvent() {
649 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, WillProcessIOEvent());
652 void MessagePumpForIO::DidProcessIOEvent() {
653 FOR_EACH_OBSERVER(IOObserver
, io_observers_
, DidProcessIOEvent());
657 ULONG_PTR
MessagePumpForIO::HandlerToKey(IOHandler
* handler
,
658 bool has_valid_io_context
) {
659 ULONG_PTR key
= reinterpret_cast<ULONG_PTR
>(handler
);
661 // |IOHandler| is at least pointer-size aligned, so the lowest two bits are
662 // always cleared. We use the lowest bit to distinguish completion keys with
663 // and without the associated |IOContext|.
664 DCHECK((key
& 1) == 0);
666 // Mark the completion key as context-less.
667 if (!has_valid_io_context
)
673 MessagePumpForIO::IOHandler
* MessagePumpForIO::KeyToHandler(
675 bool* has_valid_io_context
) {
676 *has_valid_io_context
= ((key
& 1) == 0);
677 return reinterpret_cast<IOHandler
*>(key
& ~static_cast<ULONG_PTR
>(1));