1// Copyright 2014 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#ifndef MOJO_EDK_JS_DRAIN_DATA_H_ 6#define MOJO_EDK_JS_DRAIN_DATA_H_ 7 8#include "base/memory/scoped_vector.h" 9#include "gin/runner.h" 10#include "mojo/public/cpp/system/core.h" 11#include "mojo/public/cpp/system/watcher.h" 12#include "v8/include/v8.h" 13 14namespace mojo { 15namespace edk { 16namespace js { 17 18// This class is the implementation of the Mojo JavaScript core module's 19// drainData() method. It is not intended to be used directly. The caller 20// allocates a DrainData on the heap and returns GetPromise() to JS. The 21// implementation deletes itself after reading as much data as possible 22// and rejecting or resolving the Promise. 23 24class DrainData { 25 public: 26 // Starts waiting for data on the specified data pipe consumer handle. 27 // See WaitForData(). The constructor does not block. 28 DrainData(v8::Isolate* isolate, mojo::Handle handle); 29 30 // Returns a Promise that will be settled when no more data can be read. 31 // Should be called just once on a newly allocated DrainData object. 32 v8::Handle<v8::Value> GetPromise(); 33 34 private: 35 ~DrainData(); 36 37 // Waits for data to be available. DataReady() will be notified. 38 void WaitForData(); 39 40 // Use ReadData() to read whatever is availble now on handle_ and save 41 // it in data_buffers_. 42 void DataReady(MojoResult result); 43 MojoResult ReadData(); 44 45 // When the remote data pipe handle is closed, or an error occurs, deliver 46 // all of the buffered data to the JS Promise and then delete this. 47 void DeliverData(MojoResult result); 48 49 using DataBuffer = std::vector<char>; 50 51 v8::Isolate* isolate_; 52 ScopedDataPipeConsumerHandle handle_; 53 Watcher handle_watcher_; 54 base::WeakPtr<gin::Runner> runner_; 55 v8::UniquePersistent<v8::Promise::Resolver> resolver_; 56 ScopedVector<DataBuffer> data_buffers_; 57}; 58 59} // namespace js 60} // namespace edk 61} // namespace mojo 62 63#endif // MOJO_EDK_JS_DRAIN_DATA_H_ 64