1 // Copyright 2016 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 "mojo/edk/system/watcher.h"
6 
7 #include "mojo/edk/system/handle_signals_state.h"
8 #include "mojo/edk/system/request_context.h"
9 
10 namespace mojo {
11 namespace edk {
12 
Watcher(MojoHandleSignals signals,const WatchCallback & callback)13 Watcher::Watcher(MojoHandleSignals signals, const WatchCallback& callback)
14     : signals_(signals), callback_(callback) {
15 }
16 
MaybeInvokeCallback(MojoResult result,const HandleSignalsState & state,MojoWatchNotificationFlags flags)17 void Watcher::MaybeInvokeCallback(MojoResult result,
18                                   const HandleSignalsState& state,
19                                   MojoWatchNotificationFlags flags) {
20   base::AutoLock lock(lock_);
21   if (is_cancelled_)
22     return;
23 
24   callback_.Run(result, state, flags);
25 }
26 
NotifyForStateChange(const HandleSignalsState & signals_state)27 void Watcher::NotifyForStateChange(const HandleSignalsState& signals_state) {
28   RequestContext* request_context = RequestContext::current();
29   if (signals_state.satisfies(signals_)) {
30     request_context->AddWatchNotifyFinalizer(
31         make_scoped_refptr(this), MOJO_RESULT_OK, signals_state);
32   } else if (!signals_state.can_satisfy(signals_)) {
33     request_context->AddWatchNotifyFinalizer(
34         make_scoped_refptr(this), MOJO_RESULT_FAILED_PRECONDITION,
35         signals_state);
36   }
37 }
38 
NotifyClosed()39 void Watcher::NotifyClosed() {
40   static const HandleSignalsState closed_state = {0, 0};
41   RequestContext::current()->AddWatchNotifyFinalizer(
42       make_scoped_refptr(this), MOJO_RESULT_CANCELLED, closed_state);
43 }
44 
Cancel()45 void Watcher::Cancel() {
46   base::AutoLock lock(lock_);
47   is_cancelled_ = true;
48 }
49 
~Watcher()50 Watcher::~Watcher() {}
51 
52 }  // namespace edk
53 }  // namespace mojo
54