// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ATOM_COMMON_V8_SCOPED_PERSISTENT_H_ #define ATOM_COMMON_V8_SCOPED_PERSISTENT_H_ #include "base/logging.h" #include "base/memory/ref_counted.h" #include "v8/include/v8.h" namespace atom { // A v8::Persistent handle to a V8 value which destroys and clears the // underlying handle on destruction. template class ScopedPersistent { public: ScopedPersistent() { } explicit ScopedPersistent(v8::Handle handle) { reset(handle); } ~ScopedPersistent() { reset(); } void reset(v8::Handle handle) { if (!handle.IsEmpty()) handle_.Reset(GetIsolate(handle), handle); else reset(); } void reset() { handle_.Reset(); } bool IsEmpty() const { return handle_.IsEmpty(); } v8::Handle NewHandle() const { if (handle_.IsEmpty()) return v8::Local(); return v8::Local::New(GetIsolate(handle_), handle_); } v8::Handle NewHandle(v8::Isolate* isolate) const { if (handle_.IsEmpty()) return v8::Local(); return v8::Local::New(isolate, handle_); } template void MakeWeak(P* parameters, typename v8::WeakReferenceCallbacks::Revivable callback) { handle_.MakeWeak(parameters, callback); } private: template static v8::Isolate* GetIsolate(v8::Handle object_handle) { // Only works for v8::Object and its subclasses. Add specialisations for // anything else. if (!object_handle.IsEmpty()) return GetIsolate(object_handle->CreationContext()); return v8::Isolate::GetCurrent(); } static v8::Isolate* GetIsolate(v8::Handle context_handle) { if (!context_handle.IsEmpty()) return context_handle->GetIsolate(); return v8::Isolate::GetCurrent(); } static v8::Isolate* GetIsolate( v8::Handle template_handle) { return v8::Isolate::GetCurrent(); } template static v8::Isolate* GetIsolate(const U& any_handle) { return v8::Isolate::GetCurrent(); } v8::Persistent handle_; DISALLOW_COPY_AND_ASSIGN(ScopedPersistent); }; template class RefCountedPersistent : public ScopedPersistent, public base::RefCounted> { public: RefCountedPersistent() {} explicit RefCountedPersistent(v8::Handle handle) : ScopedPersistent(handle) { } protected: friend class base::RefCounted>; ~RefCountedPersistent() {} private: DISALLOW_COPY_AND_ASSIGN(RefCountedPersistent); }; typedef scoped_refptr> RefCountedV8Function; typedef scoped_refptr> RefCountedV8Object; } // namespace atom #endif // ATOM_COMMON_V8_SCOPED_PERSISTENT_H_