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_BINDINGS_JS_HANDLE_H_ 6 #define MOJO_BINDINGS_JS_HANDLE_H_ 7 8 #include "gin/converter.h" 9 #include "gin/handle.h" 10 #include "gin/wrappable.h" 11 #include "mojo/public/cpp/system/core.h" 12 13 namespace gin { 14 15 // Wrapper for mojo Handles exposed to JavaScript. This ensures the Handle 16 // is Closed when its JS object is garbage collected. 17 class HandleWrapper : public gin::Wrappable<HandleWrapper> { 18 public: 19 static gin::WrapperInfo kWrapperInfo; 20 Create(v8::Isolate * isolate,MojoHandle handle)21 static gin::Handle<HandleWrapper> Create(v8::Isolate* isolate, 22 MojoHandle handle) { 23 return gin::CreateHandle(isolate, new HandleWrapper(handle)); 24 } 25 get()26 mojo::Handle get() const { return handle_.get(); } release()27 mojo::Handle release() { return handle_.release(); } Close()28 void Close() { handle_.reset(); } 29 30 protected: 31 HandleWrapper(MojoHandle handle); 32 virtual ~HandleWrapper(); 33 mojo::ScopedHandle handle_; 34 }; 35 36 // Note: It's important to use this converter rather than the one for 37 // MojoHandle, since that will do a simple int32 conversion. It's unfortunate 38 // there's no way to prevent against accidental use. 39 // TODO(mpcomplete): define converters for all Handle subtypes. 40 template<> 41 struct Converter<mojo::Handle> { 42 static v8::Handle<v8::Value> ToV8(v8::Isolate* isolate, 43 const mojo::Handle& val); 44 static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, 45 mojo::Handle* out); 46 }; 47 48 // We need to specialize the normal gin::Handle converter in order to handle 49 // converting |null| to a wrapper for an empty mojo::Handle. 50 template<> 51 struct Converter<gin::Handle<gin::HandleWrapper> > { 52 static v8::Handle<v8::Value> ToV8( 53 v8::Isolate* isolate, const gin::Handle<gin::HandleWrapper>& val) { 54 return val.ToV8(); 55 } 56 57 static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, 58 gin::Handle<gin::HandleWrapper>* out) { 59 if (val->IsNull()) { 60 *out = HandleWrapper::Create(isolate, MOJO_HANDLE_INVALID); 61 return true; 62 } 63 64 gin::HandleWrapper* object = NULL; 65 if (!Converter<gin::HandleWrapper*>::FromV8(isolate, val, &object)) { 66 return false; 67 } 68 *out = gin::Handle<gin::HandleWrapper>(val, object); 69 return true; 70 } 71 }; 72 73 } // namespace gin 74 75 #endif // MOJO_BINDINGS_JS_HANDLE_H_ 76