#include "base/win/object_watcher.h"
#include <windows.h>
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/task/sequenced_task_runner.h"
namespace base {
namespace win {
ObjectWatcher::ObjectWatcher() = default;
ObjectWatcher::~ObjectWatcher() {
StopWatching();
}
bool ObjectWatcher::StartWatchingOnce(HANDLE object,
Delegate* delegate,
const Location& from_here) {
return StartWatchingInternal(object, delegate, true, from_here);
}
bool ObjectWatcher::StartWatchingMultipleTimes(HANDLE object,
Delegate* delegate,
const Location& from_here) {
return StartWatchingInternal(object, delegate, false, from_here);
}
bool ObjectWatcher::StopWatching() {
if (!wait_object_)
return false;
DCHECK(task_runner_->RunsTasksInCurrentSequence());
if (!UnregisterWaitEx(wait_object_, INVALID_HANDLE_VALUE)) {
DPLOG(FATAL) << "UnregisterWaitEx failed";
return false;
}
Reset();
return true;
}
bool ObjectWatcher::IsWatching() const {
return object_ != nullptr;
}
HANDLE ObjectWatcher::GetWatchedObject() const {
return object_;
}
void CALLBACK ObjectWatcher::DoneWaiting(void* param, BOOLEAN timed_out) {
DCHECK(!timed_out);
ObjectWatcher* that = static_cast<ObjectWatcher*>(param);
that->task_runner_->PostTask(that->location_, that->callback_);
if (that->run_once_)
that->callback_.Reset();
}
bool ObjectWatcher::StartWatchingInternal(HANDLE object,
Delegate* delegate,
bool execute_only_once,
const Location& from_here) {
DCHECK(delegate);
DCHECK(!wait_object_) << "Already watching an object";
DCHECK(SequencedTaskRunner::HasCurrentDefault());
location_ = from_here;
task_runner_ = SequencedTaskRunner::GetCurrentDefault();
run_once_ = execute_only_once;
DWORD wait_flags = WT_EXECUTEINWAITTHREAD;
if (run_once_)
wait_flags |= WT_EXECUTEONLYONCE;
callback_ = BindRepeating(&ObjectWatcher::Signal, weak_factory_.GetWeakPtr(),
base::UnsafeDanglingUntriaged(delegate));
object_ = object;
if (!RegisterWaitForSingleObject(&wait_object_, object, DoneWaiting, this,
INFINITE, wait_flags)) {
DPLOG(FATAL) << "RegisterWaitForSingleObject failed";
Reset();
return false;
}
return true;
}
void ObjectWatcher::Signal(Delegate* delegate) {
HANDLE object = object_;
if (run_once_)
StopWatching();
delegate->OnObjectSignaled(object);
}
void ObjectWatcher::Reset() {
callback_.Reset();
location_ = {};
object_ = nullptr;
wait_object_ = nullptr;
task_runner_ = nullptr;
run_once_ = true;
weak_factory_.InvalidateWeakPtrs();
}
}
}