aboutsummaryrefslogtreecommitdiffhomepage
path: root/experimental/SkV8Example/Path2D.cpp
blob: dded6881671fa5915e52d7c8d0b0cc7cff52f7bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
 * Copyright 2014 Google Inc.
 *
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 */

#include "Path2D.h"
#include "Global.h"

Global* Path2D::gGlobal = NULL;
v8::Persistent<v8::ObjectTemplate> Path2D::gPath2DTemplate;

void weakPath2DCallback(const v8::WeakCallbackData<v8::Object, Path2D>& args) {
    delete args.GetParameter();
}

// Wraps an SkPath* in a Path2D object.
Path2D::Path2D(SkPath* path) : path_(path) {
    // Handle scope for temporary handles.
    v8::HandleScope handleScope(gGlobal->getIsolate());

    // Just once create the ObjectTemplate for what Path2D looks like in JS.
    if (gPath2DTemplate.IsEmpty()) {
        v8::Local<v8::ObjectTemplate> localTemplate = v8::ObjectTemplate::New();

        // Add a field to store the pointer to a SkPath pointer.
        localTemplate->SetInternalFieldCount(1);

        gPath2DTemplate.Reset(gGlobal->getIsolate(), localTemplate);
    }
    v8::Handle<v8::ObjectTemplate> templ =
            v8::Local<v8::ObjectTemplate>::New(gGlobal->getIsolate(), gPath2DTemplate);

    // Create an empty Path2D wrapper.
    v8::Local<v8::Object> result = templ->NewInstance();

    // Store the SkPath pointer in the JavaScript wrapper.
    result->SetInternalField(0, v8::External::New(gGlobal->getIsolate(), this));
    gGlobal->getIsolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(SkPath));

    // Make a weak persistent and set up the callback so we can delete the path pointer.
    // TODO(jcgregorio) Figure out why weakPath2DCallback never gets called and we leak.
    v8::Persistent<v8::Object> weak(gGlobal->getIsolate(), result);
    weak.SetWeak(this, weakPath2DCallback);
    this->handle_.Reset(gGlobal->getIsolate(), weak);
}

Path2D::~Path2D() {
    delete path_;
    handle_.Reset();
    gGlobal->getIsolate()->AdjustAmountOfExternalAllocatedMemory(-sizeof(SkPath));
}