This source file includes following definitions.
- AddObserver
- RemoveObserver
- WillProcessMessage
- DidProcessMessage
- RunWithDispatcher
- Quit
- GetCurrentDelay
- ScheduleWork
- ScheduleDelayedWork
- WndProcThunk
- DoRunLoop
- InitMessageWnd
- WaitForWork
- HandleWorkMessage
- HandleTimerMessage
- ProcessNextWindowsMessage
- ProcessMessageHelper
- ProcessPumpReplacementMessage
- ScheduleWork
- ScheduleDelayedWork
- RegisterIOHandler
- RegisterJobObject
- DoRunLoop
- WaitForWork
- WaitForIOCompletion
- GetIOItem
- ProcessInternalIOItem
- MatchCompletedIOItem
- AddIOObserver
- RemoveIOObserver
- WillProcessIOEvent
- DidProcessIOEvent
- HandlerToKey
- KeyToHandler
#include "base/message_loop/message_pump_win.h"
#include <math.h>
#include "base/debug/trace_event.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/process/memory.h"
#include "base/strings/stringprintf.h"
#include "base/win/wrapped_window_proc.h"
namespace base {
namespace {
enum MessageLoopProblems {
MESSAGE_POST_ERROR,
COMPLETION_POST_ERROR,
SET_TIMER_ERROR,
MESSAGE_LOOP_PROBLEM_MAX,
};
}
static const wchar_t kWndClassFormat[] = L"Chrome_MessagePumpWindow_%p";
static const int kMsgHaveWork = WM_USER + 1;
void MessagePumpWin::AddObserver(MessagePumpObserver* observer) {
observers_.AddObserver(observer);
}
void MessagePumpWin::RemoveObserver(MessagePumpObserver* observer) {
observers_.RemoveObserver(observer);
}
void MessagePumpWin::WillProcessMessage(const MSG& msg) {
FOR_EACH_OBSERVER(MessagePumpObserver, observers_, WillProcessEvent(msg));
}
void MessagePumpWin::DidProcessMessage(const MSG& msg) {
FOR_EACH_OBSERVER(MessagePumpObserver, observers_, DidProcessEvent(msg));
}
void MessagePumpWin::RunWithDispatcher(
Delegate* delegate, MessagePumpDispatcher* dispatcher) {
RunState s;
s.delegate = delegate;
s.dispatcher = dispatcher;
s.should_quit = false;
s.run_depth = state_ ? state_->run_depth + 1 : 1;
RunState* previous_state = state_;
state_ = &s;
DoRunLoop();
state_ = previous_state;
}
void MessagePumpWin::Quit() {
DCHECK(state_);
state_->should_quit = true;
}
int MessagePumpWin::GetCurrentDelay() const {
if (delayed_work_time_.is_null())
return -1;
double timeout =
ceil((delayed_work_time_ - TimeTicks::Now()).InMillisecondsF());
int delay = static_cast<int>(timeout);
if (delay < 0)
delay = 0;
return delay;
}
MessagePumpForUI::MessagePumpForUI()
: atom_(0) {
InitMessageWnd();
}
MessagePumpForUI::~MessagePumpForUI() {
DestroyWindow(message_hwnd_);
UnregisterClass(MAKEINTATOM(atom_),
GetModuleFromAddress(&WndProcThunk));
}
void MessagePumpForUI::ScheduleWork() {
if (InterlockedExchange(&have_work_, 1))
return;
BOOL ret = PostMessage(message_hwnd_, kMsgHaveWork,
reinterpret_cast<WPARAM>(this), 0);
if (ret)
return;
InterlockedExchange(&have_work_, 0);
UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR,
MESSAGE_LOOP_PROBLEM_MAX);
}
void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
delayed_work_time_ = delayed_work_time;
int delay_msec = GetCurrentDelay();
DCHECK_GE(delay_msec, 0);
if (delay_msec < USER_TIMER_MINIMUM)
delay_msec = USER_TIMER_MINIMUM;
BOOL ret = SetTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this),
delay_msec, NULL);
if (ret)
return;
UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", SET_TIMER_ERROR,
MESSAGE_LOOP_PROBLEM_MAX);
}
LRESULT CALLBACK MessagePumpForUI::WndProcThunk(
HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
switch (message) {
case kMsgHaveWork:
reinterpret_cast<MessagePumpForUI*>(wparam)->HandleWorkMessage();
break;
case WM_TIMER:
reinterpret_cast<MessagePumpForUI*>(wparam)->HandleTimerMessage();
break;
}
return DefWindowProc(hwnd, message, wparam, lparam);
}
void MessagePumpForUI::DoRunLoop() {
for (;;) {
bool more_work_is_plausible = ProcessNextWindowsMessage();
if (state_->should_quit)
break;
more_work_is_plausible |= state_->delegate->DoWork();
if (state_->should_quit)
break;
more_work_is_plausible |=
state_->delegate->DoDelayedWork(&delayed_work_time_);
if (more_work_is_plausible && delayed_work_time_.is_null())
KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
if (state_->should_quit)
break;
if (more_work_is_plausible)
continue;
more_work_is_plausible = state_->delegate->DoIdleWork();
if (state_->should_quit)
break;
if (more_work_is_plausible)
continue;
WaitForWork();
}
}
void MessagePumpForUI::InitMessageWnd() {
string16 class_name = StringPrintf(kWndClassFormat, this);
HINSTANCE instance = GetModuleFromAddress(&WndProcThunk);
WNDCLASSEX wc = {0};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = base::win::WrappedWindowProc<WndProcThunk>;
wc.hInstance = instance;
wc.lpszClassName = class_name.c_str();
atom_ = RegisterClassEx(&wc);
DCHECK(atom_);
message_hwnd_ = CreateWindow(MAKEINTATOM(atom_), 0, 0, 0, 0, 0, 0,
HWND_MESSAGE, 0, instance, 0);
DCHECK(message_hwnd_);
}
void MessagePumpForUI::WaitForWork() {
int delay = GetCurrentDelay();
if (delay < 0)
delay = INFINITE;
DWORD result;
result = MsgWaitForMultipleObjectsEx(0, NULL, delay, QS_ALLINPUT,
MWMO_INPUTAVAILABLE);
if (WAIT_OBJECT_0 == result) {
MSG msg = {0};
DWORD queue_status = GetQueueStatus(QS_MOUSE);
if (HIWORD(queue_status) & QS_MOUSE &&
!PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_NOREMOVE)) {
WaitMessage();
}
return;
}
DCHECK_NE(WAIT_FAILED, result) << GetLastError();
}
void MessagePumpForUI::HandleWorkMessage() {
if (!state_) {
InterlockedExchange(&have_work_, 0);
return;
}
ProcessPumpReplacementMessage();
if (state_->delegate->DoWork())
ScheduleWork();
}
void MessagePumpForUI::HandleTimerMessage() {
KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
if (!state_)
return;
state_->delegate->DoDelayedWork(&delayed_work_time_);
if (!delayed_work_time_.is_null()) {
ScheduleDelayedWork(delayed_work_time_);
}
}
bool MessagePumpForUI::ProcessNextWindowsMessage() {
bool sent_messages_in_queue = false;
DWORD queue_status = GetQueueStatus(QS_SENDMESSAGE);
if (HIWORD(queue_status) & QS_SENDMESSAGE)
sent_messages_in_queue = true;
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE)
return ProcessMessageHelper(msg);
return sent_messages_in_queue;
}
bool MessagePumpForUI::ProcessMessageHelper(const MSG& msg) {
TRACE_EVENT1("base", "MessagePumpForUI::ProcessMessageHelper",
"message", msg.message);
if (WM_QUIT == msg.message) {
state_->should_quit = true;
PostQuitMessage(static_cast<int>(msg.wParam));
return false;
}
if (msg.message == kMsgHaveWork && msg.hwnd == message_hwnd_)
return ProcessPumpReplacementMessage();
if (CallMsgFilter(const_cast<MSG*>(&msg), kMessageFilterCode))
return true;
WillProcessMessage(msg);
uint32_t action = MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT;
if (state_->dispatcher)
action = state_->dispatcher->Dispatch(msg);
if (action & MessagePumpDispatcher::POST_DISPATCH_QUIT_LOOP)
state_->should_quit = true;
if (action & MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
DidProcessMessage(msg);
return true;
}
bool MessagePumpForUI::ProcessPumpReplacementMessage() {
bool have_message = false;
MSG msg;
if (MessageLoop::current()->os_modal_loop()) {
have_message = PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE) ||
PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
} else {
have_message = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE;
}
DCHECK(!have_message || kMsgHaveWork != msg.message ||
msg.hwnd != message_hwnd_);
int old_have_work = InterlockedExchange(&have_work_, 0);
DCHECK(old_have_work);
if (!have_message)
return false;
ScheduleWork();
return ProcessMessageHelper(msg);
}
MessagePumpForIO::MessagePumpForIO() {
port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1));
DCHECK(port_.IsValid());
}
void MessagePumpForIO::ScheduleWork() {
if (InterlockedExchange(&have_work_, 1))
return;
BOOL ret = PostQueuedCompletionStatus(port_, 0,
reinterpret_cast<ULONG_PTR>(this),
reinterpret_cast<OVERLAPPED*>(this));
if (ret)
return;
InterlockedExchange(&have_work_, 0);
UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", COMPLETION_POST_ERROR,
MESSAGE_LOOP_PROBLEM_MAX);
}
void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
delayed_work_time_ = delayed_work_time;
}
void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle,
IOHandler* handler) {
ULONG_PTR key = HandlerToKey(handler, true);
HANDLE port = CreateIoCompletionPort(file_handle, port_, key, 1);
DPCHECK(port);
}
bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle,
IOHandler* handler) {
ULONG_PTR key = HandlerToKey(handler, false);
JOBOBJECT_ASSOCIATE_COMPLETION_PORT info;
info.CompletionKey = reinterpret_cast<void*>(key);
info.CompletionPort = port_;
return SetInformationJobObject(job_handle,
JobObjectAssociateCompletionPortInformation,
&info,
sizeof(info)) != FALSE;
}
void MessagePumpForIO::DoRunLoop() {
for (;;) {
bool more_work_is_plausible = state_->delegate->DoWork();
if (state_->should_quit)
break;
more_work_is_plausible |= WaitForIOCompletion(0, NULL);
if (state_->should_quit)
break;
more_work_is_plausible |=
state_->delegate->DoDelayedWork(&delayed_work_time_);
if (state_->should_quit)
break;
if (more_work_is_plausible)
continue;
more_work_is_plausible = state_->delegate->DoIdleWork();
if (state_->should_quit)
break;
if (more_work_is_plausible)
continue;
WaitForWork();
}
}
void MessagePumpForIO::WaitForWork() {
DCHECK_EQ(1, state_->run_depth) << "Cannot nest an IO message loop!";
int timeout = GetCurrentDelay();
if (timeout < 0)
timeout = INFINITE;
WaitForIOCompletion(timeout, NULL);
}
bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
IOItem item;
if (completed_io_.empty() || !MatchCompletedIOItem(filter, &item)) {
if (!GetIOItem(timeout, &item))
return false;
if (ProcessInternalIOItem(item))
return true;
}
if (!item.has_valid_io_context || item.context->handler) {
if (filter && item.handler != filter) {
completed_io_.push_back(item);
} else {
DCHECK(!item.has_valid_io_context ||
(item.context->handler == item.handler));
WillProcessIOEvent();
item.handler->OnIOCompleted(item.context, item.bytes_transfered,
item.error);
DidProcessIOEvent();
}
} else {
delete item.context;
}
return true;
}
bool MessagePumpForIO::GetIOItem(DWORD timeout, IOItem* item) {
memset(item, 0, sizeof(*item));
ULONG_PTR key = NULL;
OVERLAPPED* overlapped = NULL;
if (!GetQueuedCompletionStatus(port_.Get(), &item->bytes_transfered, &key,
&overlapped, timeout)) {
if (!overlapped)
return false;
item->error = GetLastError();
item->bytes_transfered = 0;
}
item->handler = KeyToHandler(key, &item->has_valid_io_context);
item->context = reinterpret_cast<IOContext*>(overlapped);
return true;
}
bool MessagePumpForIO::ProcessInternalIOItem(const IOItem& item) {
if (this == reinterpret_cast<MessagePumpForIO*>(item.context) &&
this == reinterpret_cast<MessagePumpForIO*>(item.handler)) {
DCHECK(!item.bytes_transfered);
InterlockedExchange(&have_work_, 0);
return true;
}
return false;
}
bool MessagePumpForIO::MatchCompletedIOItem(IOHandler* filter, IOItem* item) {
DCHECK(!completed_io_.empty());
for (std::list<IOItem>::iterator it = completed_io_.begin();
it != completed_io_.end(); ++it) {
if (!filter || it->handler == filter) {
*item = *it;
completed_io_.erase(it);
return true;
}
}
return false;
}
void MessagePumpForIO::AddIOObserver(IOObserver *obs) {
io_observers_.AddObserver(obs);
}
void MessagePumpForIO::RemoveIOObserver(IOObserver *obs) {
io_observers_.RemoveObserver(obs);
}
void MessagePumpForIO::WillProcessIOEvent() {
FOR_EACH_OBSERVER(IOObserver, io_observers_, WillProcessIOEvent());
}
void MessagePumpForIO::DidProcessIOEvent() {
FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent());
}
ULONG_PTR MessagePumpForIO::HandlerToKey(IOHandler* handler,
bool has_valid_io_context) {
ULONG_PTR key = reinterpret_cast<ULONG_PTR>(handler);
DCHECK((key & 1) == 0);
if (!has_valid_io_context)
key = key | 1;
return key;
}
MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler(
ULONG_PTR key,
bool* has_valid_io_context) {
*has_valid_io_context = ((key & 1) == 0);
return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1));
}
}