Home | History | Annotate | Download | only in bindings
      1 // Copyright 2013 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 #include "mojo/apps/js/bindings/waiting_callback.h"
      6 
      7 #include "gin/per_context_data.h"
      8 #include "gin/per_isolate_data.h"
      9 
     10 namespace mojo {
     11 namespace js {
     12 
     13 namespace {
     14 
     15 v8::Handle<v8::String> GetHiddenPropertyName(v8::Isolate* isolate) {
     16   return gin::StringToSymbol(isolate, "::mojo::js::WaitingCallback");
     17 }
     18 
     19 }  // namespace
     20 
     21 gin::WrapperInfo WaitingCallback::kWrapperInfo = { gin::kEmbedderNativeGin };
     22 
     23 WaitingCallback::WaitingCallback(v8::Isolate* isolate,
     24                                  v8::Handle<v8::Function> callback)
     25       : wait_id_() {
     26   v8::Handle<v8::Context> context = isolate->GetCurrentContext();
     27   runner_ = gin::PerContextData::From(context)->runner()->GetWeakPtr();
     28   GetWrapper(isolate)->SetHiddenValue(GetHiddenPropertyName(isolate), callback);
     29 }
     30 
     31 WaitingCallback::~WaitingCallback() {
     32   DCHECK(!wait_id_) << "Waiting callback was destroyed before being cancelled.";
     33 }
     34 
     35 gin::Handle<WaitingCallback> WaitingCallback::Create(
     36     v8::Isolate* isolate, v8::Handle<v8::Function> callback) {
     37   return gin::CreateHandle(isolate, new WaitingCallback(isolate, callback));
     38 }
     39 
     40 void WaitingCallback::EnsureRegistered(v8::Isolate* isolate) {
     41   gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
     42   if (!data->GetObjectTemplate(&WaitingCallback::kWrapperInfo).IsEmpty()) {
     43     return;
     44   }
     45   v8::Handle<v8::ObjectTemplate> templ = v8::ObjectTemplate::New(isolate);
     46   templ->SetInternalFieldCount(gin::kNumberOfInternalFields);
     47   data->SetObjectTemplate(&WaitingCallback::kWrapperInfo, templ);
     48 }
     49 
     50 void WaitingCallback::OnHandleReady(MojoResult result) {
     51   wait_id_ = NULL;
     52 
     53   if (!runner_)
     54     return;
     55 
     56   gin::Runner::Scope scope(runner_.get());
     57   v8::Isolate* isolate = runner_->isolate();
     58 
     59   v8::Handle<v8::Value> hidden_value =
     60       GetWrapper(isolate)->GetHiddenValue(GetHiddenPropertyName(isolate));
     61   v8::Handle<v8::Function> callback;
     62   CHECK(gin::ConvertFromV8(isolate, hidden_value, &callback));
     63 
     64   v8::Handle<v8::Value> args[] = { gin::ConvertToV8(isolate, result) };
     65   runner_->Call(callback, runner_->global(), 1, args);
     66 }
     67 
     68 }  // namespace js
     69 }  // namespace mojo
     70