1 /*
2  * Copyright 2014 Google Inc.
3  *
4  *
5  * Use of this source code is governed by a BSD-style license that can be
6  * found in the LICENSE file.
7  *
8  */
9 
10 #include "Path2D.h"
11 #include "Global.h"
12 
13 Global* Path2D::gGlobal = NULL;
14 v8::Persistent<v8::ObjectTemplate> Path2D::gPath2DTemplate;
15 
weakPath2DCallback(const v8::WeakCallbackData<v8::Object,Path2D> & args)16 void weakPath2DCallback(const v8::WeakCallbackData<v8::Object, Path2D>& args) {
17     delete args.GetParameter();
18 }
19 
20 // Wraps an SkPath* in a Path2D object.
Path2D(SkPath * path)21 Path2D::Path2D(SkPath* path) : path_(path) {
22     // Handle scope for temporary handles.
23     v8::HandleScope handleScope(gGlobal->getIsolate());
24 
25     // Just once create the ObjectTemplate for what Path2D looks like in JS.
26     if (gPath2DTemplate.IsEmpty()) {
27         v8::Local<v8::ObjectTemplate> localTemplate = v8::ObjectTemplate::New();
28 
29         // Add a field to store the pointer to a SkPath pointer.
30         localTemplate->SetInternalFieldCount(1);
31 
32         gPath2DTemplate.Reset(gGlobal->getIsolate(), localTemplate);
33     }
34     v8::Handle<v8::ObjectTemplate> templ =
35             v8::Local<v8::ObjectTemplate>::New(gGlobal->getIsolate(), gPath2DTemplate);
36 
37     // Create an empty Path2D wrapper.
38     v8::Local<v8::Object> result = templ->NewInstance();
39 
40     // Store the SkPath pointer in the JavaScript wrapper.
41     result->SetInternalField(0, v8::External::New(gGlobal->getIsolate(), this));
42     gGlobal->getIsolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(SkPath));
43 
44     // Make a weak persistent and set up the callback so we can delete the path pointer.
45     // TODO(jcgregorio) Figure out why weakPath2DCallback never gets called and we leak.
46     v8::Persistent<v8::Object> weak(gGlobal->getIsolate(), result);
47     weak.SetWeak(this, weakPath2DCallback);
48     this->handle_.Reset(gGlobal->getIsolate(), weak);
49 }
50 
~Path2D()51 Path2D::~Path2D() {
52     delete path_;
53     handle_.Reset();
54     gGlobal->getIsolate()->AdjustAmountOfExternalAllocatedMemory(-sizeof(SkPath));
55 }
56