web_ui_mojo_context_state.cc revision 5f1c94371a64b3196d4be9466099bb892df9b88e
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#include "content/renderer/web_ui_mojo_context_state.h"
6
7#include "base/bind.h"
8#include "base/stl_util.h"
9#include "content/public/renderer/resource_fetcher.h"
10#include "content/renderer/web_ui_runner.h"
11#include "gin/converter.h"
12#include "gin/modules/module_registry.h"
13#include "gin/per_context_data.h"
14#include "gin/public/context_holder.h"
15#include "gin/try_catch.h"
16#include "mojo/bindings/js/core.h"
17#include "mojo/bindings/js/handle.h"
18#include "mojo/bindings/js/support.h"
19#include "third_party/WebKit/public/platform/WebURLResponse.h"
20#include "third_party/WebKit/public/web/WebFrame.h"
21#include "third_party/WebKit/public/web/WebScriptSource.h"
22
23using v8::Context;
24using v8::HandleScope;
25using v8::Isolate;
26using v8::Object;
27using v8::ObjectTemplate;
28using v8::Script;
29
30namespace content {
31
32namespace {
33
34// All modules have this prefixed to them when downloading.
35// TODO(sky): move this into some common place.
36const char kModulePrefix[] = "chrome://mojo/";
37
38void RunMain(base::WeakPtr<gin::Runner> runner,
39             v8::Handle<v8::Value> module) {
40  v8::Isolate* isolate = runner->GetContextHolder()->isolate();
41  v8::Handle<v8::Function> start;
42  CHECK(gin::ConvertFromV8(isolate, module, &start));
43  runner->Call(start, runner->global(), 0, NULL);
44}
45
46}  // namespace
47
48// WebUIMojo -------------------------------------------------------------------
49
50WebUIMojoContextState::WebUIMojoContextState(blink::WebFrame* frame,
51                                             v8::Handle<v8::Context> context)
52    : frame_(frame),
53      module_added_(false) {
54  gin::PerContextData* context_data = gin::PerContextData::From(context);
55  gin::ContextHolder* context_holder = context_data->context_holder();
56  runner_.reset(new WebUIRunner(frame_, context_holder));
57  gin::Runner::Scope scoper(runner_.get());
58  gin::ModuleRegistry::From(context)->AddObserver(this);
59  runner_->RegisterBuiltinModules();
60  gin::ModuleRegistry::InstallGlobals(context->GetIsolate(), context->Global());
61  // Warning |frame| may be destroyed.
62  // TODO(sky): add test for this.
63}
64
65WebUIMojoContextState::~WebUIMojoContextState() {
66  gin::Runner::Scope scoper(runner_.get());
67  gin::ModuleRegistry::From(
68      runner_->GetContextHolder()->context())->RemoveObserver(this);
69}
70
71void WebUIMojoContextState::Run() {
72  gin::ContextHolder* context_holder = runner_->GetContextHolder();
73  gin::ModuleRegistry::From(context_holder->context())->LoadModule(
74      context_holder->isolate(),
75      "main",
76      base::Bind(RunMain, runner_->GetWeakPtr()));
77}
78
79void WebUIMojoContextState::FetchModules(const std::vector<std::string>& ids) {
80  gin::Runner::Scope scoper(runner_.get());
81  gin::ContextHolder* context_holder = runner_->GetContextHolder();
82  gin::ModuleRegistry* registry = gin::ModuleRegistry::From(
83      context_holder->context());
84  for (size_t i = 0; i < ids.size(); ++i) {
85    if (fetched_modules_.find(ids[i]) == fetched_modules_.end() &&
86        registry->available_modules().count(ids[i]) == 0) {
87      FetchModule(ids[i]);
88    }
89  }
90}
91
92void WebUIMojoContextState::FetchModule(const std::string& id) {
93  const GURL url(kModulePrefix + id);
94  // TODO(sky): better error checks here?
95  DCHECK(url.is_valid() && !url.is_empty());
96  DCHECK(fetched_modules_.find(id) == fetched_modules_.end());
97  fetched_modules_.insert(id);
98  ResourceFetcher* fetcher = ResourceFetcher::Create(url);
99  module_fetchers_.push_back(fetcher);
100  fetcher->Start(frame_,
101                 blink::WebURLRequest::RequestContextScript,
102                 blink::WebURLRequest::FrameTypeNone,
103                 base::Bind(&WebUIMojoContextState::OnFetchModuleComplete,
104                            base::Unretained(this),
105                            fetcher));
106}
107
108void WebUIMojoContextState::OnFetchModuleComplete(
109    ResourceFetcher* fetcher,
110    const blink::WebURLResponse& response,
111    const std::string& data) {
112  DCHECK_EQ(kModulePrefix,
113      response.url().string().utf8().substr(0, arraysize(kModulePrefix) - 1));
114  const std::string module =
115      response.url().string().utf8().substr(arraysize(kModulePrefix) - 1);
116  // We can't delete fetch right now as the arguments to this function come from
117  // it and are used below. Instead use a scope_ptr to cleanup.
118  scoped_ptr<ResourceFetcher> deleter(fetcher);
119  module_fetchers_.weak_erase(
120      std::find(module_fetchers_.begin(), module_fetchers_.end(), fetcher));
121  if (data.empty()) {
122    NOTREACHED();
123    return;  // TODO(sky): log something?
124  }
125
126  runner_->Run(data, module);
127}
128
129void WebUIMojoContextState::OnDidAddPendingModule(
130    const std::string& id,
131    const std::vector<std::string>& dependencies) {
132  FetchModules(dependencies);
133
134  gin::ContextHolder* context_holder = runner_->GetContextHolder();
135  gin::ModuleRegistry* registry = gin::ModuleRegistry::From(
136      context_holder->context());
137  registry->AttemptToLoadMoreModules(context_holder->isolate());
138}
139
140}  // namespace content
141