summaryrefslogtreecommitdiffstats
path: root/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc
blob: f54c87891c75e53e129c2ca9ad6e37e494ae2ef2 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright 2014 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.

#include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"

#include <string>
#include <utility>

#include "base/bind.h"
#include "components/guest_view/common/guest_view_constants.h"
#include "components/guest_view/common/guest_view_messages.h"
#include "components/guest_view/renderer/guest_view_request.h"
#include "components/guest_view/renderer/iframe_guest_view_container.h"
#include "components/guest_view/renderer/iframe_guest_view_request.h"
#include "content/public/child/v8_value_converter.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/guest_view/extensions_guest_view_messages.h"
#include "extensions/renderer/guest_view/extensions_guest_view_container.h"
#include "extensions/renderer/script_context.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebRemoteFrame.h"
#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "v8/include/v8.h"

using content::V8ValueConverter;

namespace {

// A map from view instance ID to view object (stored via weak V8 reference).
// Views are registered into this map via
// GuestViewInternalCustomBindings::RegisterView(), and accessed via
// GuestViewInternalCustomBindings::GetViewFromID().
using ViewMap = std::map<int, v8::Global<v8::Object>*>;
static base::LazyInstance<ViewMap> weak_view_map = LAZY_INSTANCE_INITIALIZER;

}  // namespace

namespace extensions {

namespace {

content::RenderFrame* GetRenderFrame(v8::Handle<v8::Value> value) {
  v8::Local<v8::Context> context =
      v8::Local<v8::Object>::Cast(value)->CreationContext();
  if (context.IsEmpty())
    return nullptr;
  blink::WebLocalFrame* frame = blink::WebLocalFrame::frameForContext(context);
  if (!frame)
    return nullptr;
  return content::RenderFrame::FromWebFrame(frame);
}

}  // namespace

GuestViewInternalCustomBindings::GuestViewInternalCustomBindings(
    ScriptContext* context)
    : ObjectBackedNativeHandler(context) {
  RouteFunction("AttachGuest",
                base::Bind(&GuestViewInternalCustomBindings::AttachGuest,
                           base::Unretained(this)));
  RouteFunction("DetachGuest",
                base::Bind(&GuestViewInternalCustomBindings::DetachGuest,
                           base::Unretained(this)));
  RouteFunction("AttachIframeGuest",
                base::Bind(&GuestViewInternalCustomBindings::AttachIframeGuest,
                           base::Unretained(this)));
  RouteFunction("DestroyContainer",
                base::Bind(&GuestViewInternalCustomBindings::DestroyContainer,
                           base::Unretained(this)));
  RouteFunction("GetContentWindow",
                base::Bind(&GuestViewInternalCustomBindings::GetContentWindow,
                           base::Unretained(this)));
  RouteFunction("GetViewFromID",
                base::Bind(&GuestViewInternalCustomBindings::GetViewFromID,
                           base::Unretained(this)));
  RouteFunction(
      "RegisterDestructionCallback",
      base::Bind(&GuestViewInternalCustomBindings::RegisterDestructionCallback,
                 base::Unretained(this)));
  RouteFunction(
      "RegisterElementResizeCallback",
      base::Bind(
          &GuestViewInternalCustomBindings::RegisterElementResizeCallback,
          base::Unretained(this)));
  RouteFunction("RegisterView",
                base::Bind(&GuestViewInternalCustomBindings::RegisterView,
                           base::Unretained(this)));
  RouteFunction(
      "RunWithGesture",
      base::Bind(&GuestViewInternalCustomBindings::RunWithGesture,
                 base::Unretained(this)));
}

GuestViewInternalCustomBindings::~GuestViewInternalCustomBindings() {}

// static
void GuestViewInternalCustomBindings::ResetMapEntry(
    const v8::WeakCallbackInfo<int>& data) {
  int* param = data.GetParameter();
  int view_instance_id = *param;
  delete param;
  ViewMap& view_map = weak_view_map.Get();
  auto entry = view_map.find(view_instance_id);
  if (entry == view_map.end())
    return;

  // V8 says we need to explicitly reset weak handles from their callbacks.
  // It is not implicit as one might expect.
  entry->second->Reset();
  delete entry->second;
  view_map.erase(entry);

  // Let the GuestViewManager know that a GuestView has been garbage collected.
  content::RenderThread::Get()->Send(
      new GuestViewHostMsg_ViewGarbageCollected(view_instance_id));
}

void GuestViewInternalCustomBindings::AttachGuest(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // Allow for an optional callback parameter.
  CHECK(args.Length() >= 3 && args.Length() <= 4);
  // Element Instance ID.
  CHECK(args[0]->IsInt32());
  // Guest Instance ID.
  CHECK(args[1]->IsInt32());
  // Attach Parameters.
  CHECK(args[2]->IsObject());
  // Optional Callback Function.
  CHECK(args.Length() < 4 || args[3]->IsFunction());

  int element_instance_id = args[0]->Int32Value();
  // An element instance ID uniquely identifies a GuestViewContainer.
  auto guest_view_container =
      guest_view::GuestViewContainer::FromID(element_instance_id);

  // TODO(fsamuel): Should we be reporting an error if the element instance ID
  // is invalid?
  if (!guest_view_container)
    return;

  int guest_instance_id = args[1]->Int32Value();

  scoped_ptr<base::DictionaryValue> params;
  {
    scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
    scoped_ptr<base::Value> params_as_value(
        converter->FromV8Value(args[2], context()->v8_context()));
    params = base::DictionaryValue::From(std::move(params_as_value));
    CHECK(params);
  }

  // Add flag to |params| to indicate that the element size is specified in
  // logical units.
  params->SetBoolean(guest_view::kElementSizeIsLogical, true);

  linked_ptr<guest_view::GuestViewRequest> request(
      new guest_view::GuestViewAttachRequest(
          guest_view_container, guest_instance_id, std::move(params),
          args.Length() == 4 ? args[3].As<v8::Function>()
                             : v8::Local<v8::Function>(),
          args.GetIsolate()));
  guest_view_container->IssueRequest(request);

  args.GetReturnValue().Set(v8::Boolean::New(context()->isolate(), true));
}

void GuestViewInternalCustomBindings::DetachGuest(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // Allow for an optional callback parameter.
  CHECK(args.Length() >= 1 && args.Length() <= 2);
  // Element Instance ID.
  CHECK(args[0]->IsInt32());
  // Optional Callback Function.
  CHECK(args.Length() < 2 || args[1]->IsFunction());

  int element_instance_id = args[0]->Int32Value();
  // An element instance ID uniquely identifies a GuestViewContainer.
  auto guest_view_container =
      guest_view::GuestViewContainer::FromID(element_instance_id);

  // TODO(fsamuel): Should we be reporting an error if the element instance ID
  // is invalid?
  if (!guest_view_container)
    return;

  linked_ptr<guest_view::GuestViewRequest> request(
      new guest_view::GuestViewDetachRequest(
          guest_view_container, args.Length() == 2 ? args[1].As<v8::Function>()
                                                   : v8::Local<v8::Function>(),
          args.GetIsolate()));
  guest_view_container->IssueRequest(request);

  args.GetReturnValue().Set(v8::Boolean::New(context()->isolate(), true));
}

void GuestViewInternalCustomBindings::AttachIframeGuest(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // Allow for an optional callback parameter.
  const int num_required_params = 4;
  CHECK(args.Length() >= num_required_params &&
        args.Length() <= (num_required_params + 1));
  // Element Instance ID.
  CHECK(args[0]->IsInt32());
  // Guest Instance ID.
  CHECK(args[1]->IsInt32());
  // Attach Parameters.
  CHECK(args[2]->IsObject());
  // <iframe>.contentWindow.
  CHECK(args[3]->IsObject());
  // Optional Callback Function.
  CHECK(args.Length() <= num_required_params ||
        args[num_required_params]->IsFunction());

  int element_instance_id = args[0]->Int32Value();
  int guest_instance_id = args[1]->Int32Value();

  scoped_ptr<base::DictionaryValue> params;
  {
    scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
    scoped_ptr<base::Value> params_as_value(
        converter->FromV8Value(args[2], context()->v8_context()));
    params = base::DictionaryValue::From(std::move(params_as_value));
    CHECK(params);
  }

  // Add flag to |params| to indicate that the element size is specified in
  // logical units.
  params->SetBoolean(guest_view::kElementSizeIsLogical, true);

  content::RenderFrame* render_frame = GetRenderFrame(args[3]);
  blink::WebLocalFrame* frame = render_frame->GetWebFrame();

  // Parent must exist.
  blink::WebFrame* parent_frame = frame->parent();
  DCHECK(parent_frame);
  DCHECK(parent_frame->isWebLocalFrame());

  content::RenderFrame* embedder_parent_frame =
      content::RenderFrame::FromWebFrame(parent_frame);

  // Create a GuestViewContainer if it does not exist.
  // An element instance ID uniquely identifies an IframeGuestViewContainer
  // within a RenderView.
  auto* guest_view_container =
      static_cast<guest_view::IframeGuestViewContainer*>(
          guest_view::GuestViewContainer::FromID(element_instance_id));
  // This is the first time we hear about the |element_instance_id|.
  DCHECK(!guest_view_container);
  // The <webview> element's GC takes ownership of |guest_view_container|.
  guest_view_container =
      new guest_view::IframeGuestViewContainer(embedder_parent_frame);
  guest_view_container->SetElementInstanceID(element_instance_id);

  linked_ptr<guest_view::GuestViewRequest> request(
      new guest_view::GuestViewAttachIframeRequest(
          guest_view_container, render_frame->GetRoutingID(), guest_instance_id,
          std::move(params), args.Length() == (num_required_params + 1)
                                 ? args[num_required_params].As<v8::Function>()
                                 : v8::Local<v8::Function>(),
          args.GetIsolate()));
  guest_view_container->IssueRequest(request);

  args.GetReturnValue().Set(v8::Boolean::New(context()->isolate(), true));
}

void GuestViewInternalCustomBindings::DestroyContainer(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().SetNull();

  if (args.Length() != 1)
    return;

  // Element Instance ID.
  if (!args[0]->IsInt32())
    return;

  int element_instance_id = args[0]->Int32Value();
  auto* guest_view_container =
      guest_view::GuestViewContainer::FromID(element_instance_id);
  if (!guest_view_container)
    return;

  // Note: |guest_view_container| is deleted.
  // GuestViewContainer::DidDestroyElement() currently also destroys
  // a GuestViewContainer. That won't be necessary once GuestViewContainer
  // always runs w/o plugin.
  guest_view_container->Destroy(false /* embedder_frame_destroyed */);
}

void GuestViewInternalCustomBindings::GetContentWindow(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // Default to returning null.
  args.GetReturnValue().SetNull();

  if (args.Length() != 1)
    return;

  // The routing ID for the RenderView.
  if (!args[0]->IsInt32())
    return;

  int view_id = args[0]->Int32Value();
  if (view_id == MSG_ROUTING_NONE)
    return;

  content::RenderView* view = content::RenderView::FromRoutingID(view_id);
  if (!view)
    return;

  blink::WebFrame* frame = view->GetWebView()->mainFrame();
  // TODO(lazyboy,nasko): The WebLocalFrame branch is not used when running
  // on top of out-of-process iframes. Remove it once the code is converted.
  v8::Local<v8::Value> window;
  if (frame->isWebLocalFrame()) {
    window = frame->mainWorldScriptContext()->Global();
  } else {
    window =
        frame->toWebRemoteFrame()->deprecatedMainWorldScriptContext()->Global();
  }
  args.GetReturnValue().Set(window);
}

void GuestViewInternalCustomBindings::GetViewFromID(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // Default to returning null.
  args.GetReturnValue().SetNull();
  // There is one argument.
  CHECK(args.Length() == 1);
  // The view ID.
  CHECK(args[0]->IsInt32());
  int view_id = args[0]->Int32Value();

  ViewMap& view_map = weak_view_map.Get();
  auto map_entry = view_map.find(view_id);
  if (map_entry == view_map.end())
    return;

  auto return_object = v8::Handle<v8::Object>::New(args.GetIsolate(),
                                                   *map_entry->second);
  args.GetReturnValue().Set(return_object);
}

void GuestViewInternalCustomBindings::RegisterDestructionCallback(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // There are two parameters.
  CHECK(args.Length() == 2);
  // Element Instance ID.
  CHECK(args[0]->IsInt32());
  // Callback function.
  CHECK(args[1]->IsFunction());

  int element_instance_id = args[0]->Int32Value();
  // An element instance ID uniquely identifies a GuestViewContainer within a
  // RenderView.
  auto* guest_view_container =
      guest_view::GuestViewContainer::FromID(element_instance_id);
  if (!guest_view_container)
    return;

  guest_view_container->RegisterDestructionCallback(args[1].As<v8::Function>(),
                                                    args.GetIsolate());

  args.GetReturnValue().Set(v8::Boolean::New(context()->isolate(), true));
}

void GuestViewInternalCustomBindings::RegisterElementResizeCallback(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // There are two parameters.
  CHECK(args.Length() == 2);
  // Element Instance ID.
  CHECK(args[0]->IsInt32());
  // Callback function.
  CHECK(args[1]->IsFunction());

  int element_instance_id = args[0]->Int32Value();
  // An element instance ID uniquely identifies a ExtensionsGuestViewContainer
  // within a RenderView.
  auto guest_view_container = static_cast<ExtensionsGuestViewContainer*>(
      guest_view::GuestViewContainer::FromID(element_instance_id));
  if (!guest_view_container)
    return;

  guest_view_container->RegisterElementResizeCallback(
      args[1].As<v8::Function>(), args.GetIsolate());

  args.GetReturnValue().Set(v8::Boolean::New(context()->isolate(), true));
}

void GuestViewInternalCustomBindings::RegisterView(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // There are three parameters.
  CHECK(args.Length() == 3);
  // View Instance ID.
  CHECK(args[0]->IsInt32());
  // View element.
  CHECK(args[1]->IsObject());
  // View type (e.g. "webview").
  CHECK(args[2]->IsString());

  // A reference to the view object is stored in |weak_view_map| using its view
  // ID as the key. The reference is made weak so that it will not extend the
  // lifetime of the object.
  int view_instance_id = args[0]->Int32Value();
  auto object =
      new v8::Global<v8::Object>(args.GetIsolate(), args[1].As<v8::Object>());
  weak_view_map.Get().insert(std::make_pair(view_instance_id, object));

  // The |view_instance_id| is given to the SetWeak callback so that that view's
  // entry in |weak_view_map| can be cleared when the view object is garbage
  // collected.
  object->SetWeak(new int(view_instance_id),
                  &GuestViewInternalCustomBindings::ResetMapEntry,
                  v8::WeakCallbackType::kParameter);

  // Let the GuestViewManager know that a GuestView has been created.
  const std::string& view_type = *v8::String::Utf8Value(args[2]);
  content::RenderThread::Get()->Send(
      new GuestViewHostMsg_ViewCreated(view_instance_id, view_type));
}

void GuestViewInternalCustomBindings::RunWithGesture(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  // Gesture is required to request fullscreen.
  blink::WebScopedUserGesture user_gesture;
  CHECK_EQ(args.Length(), 1);
  CHECK(args[0]->IsFunction());
  v8::Local<v8::Value> no_args;
  context()->CallFunction(v8::Local<v8::Function>::Cast(args[0]), 0, &no_args);
}

}  // namespace extensions