pepper_plugin_instance_impl.cc revision 6e8cce623b6e4fe0c9e4af605d675dd9d0338c38
1// Copyright (c) 2012 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/pepper/pepper_plugin_instance_impl.h"
6
7#include "base/bind.h"
8#include "base/callback_helpers.h"
9#include "base/command_line.h"
10#include "base/debug/trace_event.h"
11#include "base/logging.h"
12#include "base/memory/linked_ptr.h"
13#include "base/message_loop/message_loop.h"
14#include "base/stl_util.h"
15#include "base/strings/stringprintf.h"
16#include "base/strings/utf_offset_string_conversions.h"
17#include "base/strings/utf_string_conversions.h"
18#include "base/time/time.h"
19#include "cc/base/latency_info_swap_promise.h"
20#include "cc/layers/texture_layer.h"
21#include "cc/trees/layer_tree_host.h"
22#include "content/common/content_constants_internal.h"
23#include "content/common/input/web_input_event_traits.h"
24#include "content/public/common/content_switches.h"
25#include "content/public/common/page_zoom.h"
26#include "content/public/renderer/content_renderer_client.h"
27#include "content/renderer/compositor_bindings/web_layer_impl.h"
28#include "content/renderer/gpu/render_widget_compositor.h"
29#include "content/renderer/pepper/content_decryptor_delegate.h"
30#include "content/renderer/pepper/event_conversion.h"
31#include "content/renderer/pepper/fullscreen_container.h"
32#include "content/renderer/pepper/gfx_conversion.h"
33#include "content/renderer/pepper/host_dispatcher_wrapper.h"
34#include "content/renderer/pepper/host_globals.h"
35#include "content/renderer/pepper/message_channel.h"
36#include "content/renderer/pepper/npapi_glue.h"
37#include "content/renderer/pepper/pepper_browser_connection.h"
38#include "content/renderer/pepper/pepper_compositor_host.h"
39#include "content/renderer/pepper/pepper_file_ref_renderer_host.h"
40#include "content/renderer/pepper/pepper_graphics_2d_host.h"
41#include "content/renderer/pepper/pepper_in_process_router.h"
42#include "content/renderer/pepper/pepper_url_loader_host.h"
43#include "content/renderer/pepper/plugin_module.h"
44#include "content/renderer/pepper/plugin_object.h"
45#include "content/renderer/pepper/ppapi_preferences_builder.h"
46#include "content/renderer/pepper/ppb_buffer_impl.h"
47#include "content/renderer/pepper/ppb_graphics_3d_impl.h"
48#include "content/renderer/pepper/ppb_image_data_impl.h"
49#include "content/renderer/pepper/renderer_ppapi_host_impl.h"
50#include "content/renderer/pepper/url_request_info_util.h"
51#include "content/renderer/pepper/url_response_info_util.h"
52#include "content/renderer/render_frame_impl.h"
53#include "content/renderer/render_thread_impl.h"
54#include "content/renderer/render_view_impl.h"
55#include "content/renderer/render_widget.h"
56#include "content/renderer/render_widget_fullscreen_pepper.h"
57#include "content/renderer/sad_plugin.h"
58#include "media/base/audio_hardware_config.h"
59#include "ppapi/c/dev/ppb_zoom_dev.h"
60#include "ppapi/c/dev/ppp_selection_dev.h"
61#include "ppapi/c/dev/ppp_text_input_dev.h"
62#include "ppapi/c/dev/ppp_zoom_dev.h"
63#include "ppapi/c/pp_rect.h"
64#include "ppapi/c/ppb_audio_config.h"
65#include "ppapi/c/ppb_core.h"
66#include "ppapi/c/ppb_gamepad.h"
67#include "ppapi/c/ppp_input_event.h"
68#include "ppapi/c/ppp_instance.h"
69#include "ppapi/c/ppp_messaging.h"
70#include "ppapi/c/ppp_mouse_lock.h"
71#include "ppapi/c/private/ppb_find_private.h"
72#include "ppapi/c/private/ppp_find_private.h"
73#include "ppapi/c/private/ppp_instance_private.h"
74#include "ppapi/c/private/ppp_pdf.h"
75#include "ppapi/host/ppapi_host.h"
76#include "ppapi/proxy/ppapi_messages.h"
77#include "ppapi/proxy/serialized_var.h"
78#include "ppapi/proxy/uma_private_resource.h"
79#include "ppapi/proxy/url_loader_resource.h"
80#include "ppapi/shared_impl/ppapi_permissions.h"
81#include "ppapi/shared_impl/ppapi_preferences.h"
82#include "ppapi/shared_impl/ppb_gamepad_shared.h"
83#include "ppapi/shared_impl/ppb_input_event_shared.h"
84#include "ppapi/shared_impl/ppb_url_util_shared.h"
85#include "ppapi/shared_impl/ppb_view_shared.h"
86#include "ppapi/shared_impl/ppp_instance_combined.h"
87#include "ppapi/shared_impl/resource.h"
88#include "ppapi/shared_impl/scoped_pp_resource.h"
89#include "ppapi/shared_impl/scoped_pp_var.h"
90#include "ppapi/shared_impl/time_conversion.h"
91#include "ppapi/shared_impl/url_request_info_data.h"
92#include "ppapi/shared_impl/var.h"
93#include "ppapi/thunk/enter.h"
94#include "ppapi/thunk/ppb_buffer_api.h"
95#include "printing/metafile.h"
96#include "printing/metafile_skia_wrapper.h"
97#include "printing/units.h"
98#include "skia/ext/platform_canvas.h"
99#include "skia/ext/platform_device.h"
100#include "third_party/WebKit/public/platform/WebCursorInfo.h"
101#include "third_party/WebKit/public/platform/WebGamepads.h"
102#include "third_party/WebKit/public/platform/WebRect.h"
103#include "third_party/WebKit/public/platform/WebString.h"
104#include "third_party/WebKit/public/platform/WebURL.h"
105#include "third_party/WebKit/public/platform/WebURLError.h"
106#include "third_party/WebKit/public/platform/WebURLRequest.h"
107#include "third_party/WebKit/public/web/WebBindings.h"
108#include "third_party/WebKit/public/web/WebCompositionUnderline.h"
109#include "third_party/WebKit/public/web/WebDataSource.h"
110#include "third_party/WebKit/public/web/WebDocument.h"
111#include "third_party/WebKit/public/web/WebElement.h"
112#include "third_party/WebKit/public/web/WebInputEvent.h"
113#include "third_party/WebKit/public/web/WebLocalFrame.h"
114#include "third_party/WebKit/public/web/WebPluginContainer.h"
115#include "third_party/WebKit/public/web/WebPrintParams.h"
116#include "third_party/WebKit/public/web/WebPrintScalingOption.h"
117#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
118#include "third_party/WebKit/public/web/WebSecurityOrigin.h"
119#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
120#include "third_party/WebKit/public/web/WebView.h"
121#include "third_party/khronos/GLES2/gl2.h"
122#include "third_party/skia/include/core/SkCanvas.h"
123#include "third_party/skia/include/core/SkRect.h"
124#include "ui/gfx/image/image_skia.h"
125#include "ui/gfx/image/image_skia_rep.h"
126#include "ui/gfx/range/range.h"
127#include "ui/gfx/rect_conversions.h"
128#include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h"
129#include "v8/include/v8.h"
130
131#if defined(OS_CHROMEOS)
132#include "ui/events/keycodes/keyboard_codes_posix.h"
133#endif
134
135#if defined(OS_MACOSX)
136#include "printing/metafile_impl.h"
137#endif  // defined(OS_MACOSX)
138
139#if defined(OS_WIN)
140#include "base/metrics/histogram.h"
141#include "base/win/windows_version.h"
142#include "skia/ext/platform_canvas.h"
143#include "ui/gfx/codec/jpeg_codec.h"
144#include "ui/gfx/gdi_util.h"
145#endif
146
147using base::StringPrintf;
148using ppapi::InputEventData;
149using ppapi::PpapiGlobals;
150using ppapi::PPB_InputEvent_Shared;
151using ppapi::PPB_View_Shared;
152using ppapi::PPP_Instance_Combined;
153using ppapi::Resource;
154using ppapi::ScopedPPResource;
155using ppapi::ScopedPPVar;
156using ppapi::StringVar;
157using ppapi::TrackedCallback;
158using ppapi::thunk::EnterResourceNoLock;
159using ppapi::thunk::PPB_Buffer_API;
160using ppapi::thunk::PPB_Gamepad_API;
161using ppapi::thunk::PPB_Graphics2D_API;
162using ppapi::thunk::PPB_Graphics3D_API;
163using ppapi::thunk::PPB_ImageData_API;
164using ppapi::Var;
165using ppapi::ArrayBufferVar;
166using ppapi::ViewData;
167using blink::WebBindings;
168using blink::WebCanvas;
169using blink::WebCursorInfo;
170using blink::WebDocument;
171using blink::WebElement;
172using blink::WebFrame;
173using blink::WebInputEvent;
174using blink::WebLocalFrame;
175using blink::WebPlugin;
176using blink::WebPluginContainer;
177using blink::WebPrintParams;
178using blink::WebPrintScalingOption;
179using blink::WebScopedUserGesture;
180using blink::WebString;
181using blink::WebURLError;
182using blink::WebURLLoader;
183using blink::WebURLLoaderClient;
184using blink::WebURLRequest;
185using blink::WebURLResponse;
186using blink::WebUserGestureIndicator;
187using blink::WebUserGestureToken;
188using blink::WebView;
189
190namespace content {
191
192#if defined(OS_WIN)
193// Exported by pdf.dll
194typedef bool (*RenderPDFPageToDCProc)(const unsigned char* pdf_buffer,
195                                      int buffer_size,
196                                      int page_number,
197                                      HDC dc,
198                                      int dpi_x,
199                                      int dpi_y,
200                                      int bounds_origin_x,
201                                      int bounds_origin_y,
202                                      int bounds_width,
203                                      int bounds_height,
204                                      bool fit_to_bounds,
205                                      bool stretch_to_bounds,
206                                      bool keep_aspect_ratio,
207                                      bool center_in_bounds,
208                                      bool autorotate);
209
210void DrawEmptyRectangle(HDC dc) {
211  // TODO(sanjeevr): This is a temporary hack. If we output a JPEG
212  // to the EMF, the EnumEnhMetaFile call fails in the browser
213  // process. The failure also happens if we output nothing here.
214  // We need to investigate the reason for this failure and fix it.
215  // In the meantime this temporary hack of drawing an empty
216  // rectangle in the DC gets us by.
217  Rectangle(dc, 0, 0, 0, 0);
218}
219#endif  // defined(OS_WIN)
220
221namespace {
222
223// Check PP_TextInput_Type and ui::TextInputType are kept in sync.
224COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NONE) == int(PP_TEXTINPUT_TYPE_NONE),
225               mismatching_enums);
226COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TEXT) == int(PP_TEXTINPUT_TYPE_TEXT),
227               mismatching_enums);
228COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_PASSWORD) ==
229                   int(PP_TEXTINPUT_TYPE_PASSWORD),
230               mismatching_enums);
231COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_SEARCH) == int(PP_TEXTINPUT_TYPE_SEARCH),
232               mismatching_enums);
233COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_EMAIL) == int(PP_TEXTINPUT_TYPE_EMAIL),
234               mismatching_enums);
235COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NUMBER) == int(PP_TEXTINPUT_TYPE_NUMBER),
236               mismatching_enums);
237COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TELEPHONE) ==
238                   int(PP_TEXTINPUT_TYPE_TELEPHONE),
239               mismatching_enums);
240COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_URL) == int(PP_TEXTINPUT_TYPE_URL),
241               mismatching_enums);
242
243// The default text input type is to regard the plugin always accept text input.
244// This is for allowing users to use input methods even on completely-IME-
245// unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
246// Plugins need to explicitly opt out the text input mode if they know
247// that they don't accept texts.
248const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
249
250#define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name)       \
251  COMPILE_ASSERT(static_cast<int>(WebCursorInfo::webkit_name) == \
252                     static_cast<int>(np_name),                  \
253                 mismatching_enums)
254
255#define COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(webkit_name, pp_name)     \
256  COMPILE_ASSERT(static_cast<int>(webkit_name) == static_cast<int>(pp_name), \
257                 mismatching_enums)
258
259// <embed>/<object> attributes.
260const char kWidth[] = "width";
261const char kHeight[] = "height";
262const char kBorder[] = "border";  // According to w3c, deprecated.
263const char kStyle[] = "style";
264
265COMPILE_ASSERT_MATCHING_ENUM(TypePointer, PP_MOUSECURSOR_TYPE_POINTER);
266COMPILE_ASSERT_MATCHING_ENUM(TypeCross, PP_MOUSECURSOR_TYPE_CROSS);
267COMPILE_ASSERT_MATCHING_ENUM(TypeHand, PP_MOUSECURSOR_TYPE_HAND);
268COMPILE_ASSERT_MATCHING_ENUM(TypeIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
269COMPILE_ASSERT_MATCHING_ENUM(TypeWait, PP_MOUSECURSOR_TYPE_WAIT);
270COMPILE_ASSERT_MATCHING_ENUM(TypeHelp, PP_MOUSECURSOR_TYPE_HELP);
271COMPILE_ASSERT_MATCHING_ENUM(TypeEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
272COMPILE_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
273COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastResize,
274                             PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
275COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestResize,
276                             PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
277COMPILE_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
278COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastResize,
279                             PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
280COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestResize,
281                             PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
282COMPILE_ASSERT_MATCHING_ENUM(TypeWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
283COMPILE_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
284                             PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
285COMPILE_ASSERT_MATCHING_ENUM(TypeEastWestResize,
286                             PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
287COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
288                             PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
289COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
290                             PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
291COMPILE_ASSERT_MATCHING_ENUM(TypeColumnResize,
292                             PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
293COMPILE_ASSERT_MATCHING_ENUM(TypeRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
294COMPILE_ASSERT_MATCHING_ENUM(TypeMiddlePanning,
295                             PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
296COMPILE_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
297COMPILE_ASSERT_MATCHING_ENUM(TypeNorthPanning,
298                             PP_MOUSECURSOR_TYPE_NORTHPANNING);
299COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
300                             PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
301COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
302                             PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
303COMPILE_ASSERT_MATCHING_ENUM(TypeSouthPanning,
304                             PP_MOUSECURSOR_TYPE_SOUTHPANNING);
305COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
306                             PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
307COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
308                             PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
309COMPILE_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
310COMPILE_ASSERT_MATCHING_ENUM(TypeMove, PP_MOUSECURSOR_TYPE_MOVE);
311COMPILE_ASSERT_MATCHING_ENUM(TypeVerticalText,
312                             PP_MOUSECURSOR_TYPE_VERTICALTEXT);
313COMPILE_ASSERT_MATCHING_ENUM(TypeCell, PP_MOUSECURSOR_TYPE_CELL);
314COMPILE_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
315COMPILE_ASSERT_MATCHING_ENUM(TypeAlias, PP_MOUSECURSOR_TYPE_ALIAS);
316COMPILE_ASSERT_MATCHING_ENUM(TypeProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
317COMPILE_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
318COMPILE_ASSERT_MATCHING_ENUM(TypeCopy, PP_MOUSECURSOR_TYPE_COPY);
319COMPILE_ASSERT_MATCHING_ENUM(TypeNone, PP_MOUSECURSOR_TYPE_NONE);
320COMPILE_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
321COMPILE_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
322COMPILE_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
323COMPILE_ASSERT_MATCHING_ENUM(TypeGrab, PP_MOUSECURSOR_TYPE_GRAB);
324COMPILE_ASSERT_MATCHING_ENUM(TypeGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
325// Do not assert WebCursorInfo::TypeCustom == PP_CURSORTYPE_CUSTOM;
326// PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
327
328COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(blink::WebPrintScalingOptionNone,
329                                           PP_PRINTSCALINGOPTION_NONE);
330COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
331    blink::WebPrintScalingOptionFitToPrintableArea,
332    PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
333COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
334    blink::WebPrintScalingOptionSourceSize,
335    PP_PRINTSCALINGOPTION_SOURCE_SIZE);
336
337// Sets |*security_origin| to be the WebKit security origin associated with the
338// document containing the given plugin instance. On success, returns true. If
339// the instance is invalid, returns false and |*security_origin| will be
340// unchanged.
341bool SecurityOriginForInstance(PP_Instance instance_id,
342                               blink::WebSecurityOrigin* security_origin) {
343  PepperPluginInstanceImpl* instance =
344      HostGlobals::Get()->GetInstance(instance_id);
345  if (!instance)
346    return false;
347
348  WebElement plugin_element = instance->container()->element();
349  *security_origin = plugin_element.document().securityOrigin();
350  return true;
351}
352
353// Convert the given vector to an array of C-strings. The strings in the
354// returned vector are only guaranteed valid so long as the vector of strings
355// is not modified.
356scoped_ptr<const char* []> StringVectorToArgArray(
357    const std::vector<std::string>& vector) {
358  scoped_ptr<const char * []> array(new const char* [vector.size()]);
359  for (size_t i = 0; i < vector.size(); ++i)
360    array[i] = vector[i].c_str();
361  return array.Pass();
362}
363
364// Returns true if this is a "system reserved" key which should not be sent to
365// a plugin. Some poorly behaving plugins (like Flash) incorrectly report that
366// they handle all keys sent to them. This can prevent keystrokes from working
367// for things like screen brightness and volume control.
368bool IsReservedSystemInputEvent(const blink::WebInputEvent& event) {
369#if defined(OS_CHROMEOS)
370  if (event.type != WebInputEvent::KeyDown &&
371      event.type != WebInputEvent::KeyUp)
372    return false;
373  const blink::WebKeyboardEvent& key_event =
374      static_cast<const blink::WebKeyboardEvent&>(event);
375  switch (key_event.windowsKeyCode) {
376    case ui::VKEY_BRIGHTNESS_DOWN:
377    case ui::VKEY_BRIGHTNESS_UP:
378    case ui::VKEY_KBD_BRIGHTNESS_DOWN:
379    case ui::VKEY_KBD_BRIGHTNESS_UP:
380    case ui::VKEY_VOLUME_MUTE:
381    case ui::VKEY_VOLUME_DOWN:
382    case ui::VKEY_VOLUME_UP:
383      return true;
384    default:
385      return false;
386  }
387#endif  // defined(OS_CHROMEOS)
388  return false;
389}
390
391class PluginInstanceLockTarget : public MouseLockDispatcher::LockTarget {
392 public:
393  PluginInstanceLockTarget(PepperPluginInstanceImpl* plugin)
394      : plugin_(plugin) {}
395
396  virtual void OnLockMouseACK(bool succeeded) OVERRIDE {
397    plugin_->OnLockMouseACK(succeeded);
398  }
399
400  virtual void OnMouseLockLost() OVERRIDE { plugin_->OnMouseLockLost(); }
401
402  virtual bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event)
403      OVERRIDE {
404    plugin_->HandleMouseLockedInputEvent(event);
405    return true;
406  }
407
408 private:
409  PepperPluginInstanceImpl* plugin_;
410};
411
412void InitLatencyInfo(ui::LatencyInfo* new_latency,
413                     const ui::LatencyInfo* old_latency,
414                     blink::WebInputEvent::Type type,
415                     int64 input_sequence) {
416  new_latency->AddLatencyNumber(
417      ui::INPUT_EVENT_LATENCY_BEGIN_PLUGIN_COMPONENT,
418      0,
419      input_sequence);
420  new_latency->TraceEventType(WebInputEventTraits::GetName(type));
421  if (old_latency) {
422    new_latency->CopyLatencyFrom(*old_latency,
423                                 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
424    new_latency->CopyLatencyFrom(*old_latency,
425                                 ui::INPUT_EVENT_LATENCY_UI_COMPONENT);
426  }
427}
428
429}  // namespace
430
431// static
432PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
433    RenderFrameImpl* render_frame,
434    PluginModule* module,
435    WebPluginContainer* container,
436    const GURL& plugin_url) {
437  base::Callback<const void*(const char*)> get_plugin_interface_func =
438      base::Bind(&PluginModule::GetPluginInterface, module);
439  PPP_Instance_Combined* ppp_instance_combined =
440      PPP_Instance_Combined::Create(get_plugin_interface_func);
441  if (!ppp_instance_combined)
442    return NULL;
443  return new PepperPluginInstanceImpl(
444      render_frame, module, ppp_instance_combined, container, plugin_url);
445}
446
447PepperPluginInstanceImpl::ExternalDocumentLoader::ExternalDocumentLoader()
448    : finished_loading_(false) {}
449
450PepperPluginInstanceImpl::ExternalDocumentLoader::~ExternalDocumentLoader() {}
451
452void PepperPluginInstanceImpl::ExternalDocumentLoader::ReplayReceivedData(
453    WebURLLoaderClient* document_loader) {
454  for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
455       ++it) {
456    document_loader->didReceiveData(
457        NULL, it->c_str(), it->length(), 0 /* encoded_data_length */);
458  }
459  if (finished_loading_) {
460    document_loader->didFinishLoading(
461        NULL,
462        0 /* finish_time */,
463        blink::WebURLLoaderClient::kUnknownEncodedDataLength);
464  }
465  if (error_.get()) {
466    document_loader->didFail(NULL, *error_);
467  }
468}
469
470void PepperPluginInstanceImpl::ExternalDocumentLoader::didReceiveData(
471    WebURLLoader* loader,
472    const char* data,
473    int data_length,
474    int encoded_data_length) {
475  data_.push_back(std::string(data, data_length));
476}
477
478void PepperPluginInstanceImpl::ExternalDocumentLoader::didFinishLoading(
479    WebURLLoader* loader,
480    double finish_time,
481    int64_t total_encoded_data_length) {
482  DCHECK(!finished_loading_);
483  finished_loading_ = true;
484}
485
486void PepperPluginInstanceImpl::ExternalDocumentLoader::didFail(
487    WebURLLoader* loader,
488    const WebURLError& error) {
489  DCHECK(!error_.get());
490  error_.reset(new WebURLError(error));
491}
492
493PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
494    : Resource(ppapi::Resource::Untracked()) {}
495
496PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
497
498PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
499  return this;
500}
501
502void PepperPluginInstanceImpl::GamepadImpl::Sample(
503    PP_Instance instance,
504    PP_GamepadsSampleData* data) {
505  blink::WebGamepads webkit_data;
506  RenderThreadImpl::current()->SampleGamepads(&webkit_data);
507  ConvertWebKitGamepadData(bit_cast<ppapi::WebKitGamepads>(webkit_data), data);
508}
509
510PepperPluginInstanceImpl::PepperPluginInstanceImpl(
511    RenderFrameImpl* render_frame,
512    PluginModule* module,
513    ppapi::PPP_Instance_Combined* instance_interface,
514    WebPluginContainer* container,
515    const GURL& plugin_url)
516    : RenderFrameObserver(render_frame),
517      render_frame_(render_frame),
518      module_(module),
519      instance_interface_(instance_interface),
520      pp_instance_(0),
521      container_(container),
522      layer_bound_to_fullscreen_(false),
523      layer_is_hardware_(false),
524      plugin_url_(plugin_url),
525      full_frame_(false),
526      sent_initial_did_change_view_(false),
527      bound_graphics_2d_platform_(NULL),
528      bound_compositor_(NULL),
529      has_webkit_focus_(false),
530      has_content_area_focus_(false),
531      find_identifier_(-1),
532      plugin_find_interface_(NULL),
533      plugin_input_event_interface_(NULL),
534      plugin_mouse_lock_interface_(NULL),
535      plugin_pdf_interface_(NULL),
536      plugin_private_interface_(NULL),
537      plugin_selection_interface_(NULL),
538      plugin_textinput_interface_(NULL),
539      plugin_zoom_interface_(NULL),
540      checked_for_plugin_input_event_interface_(false),
541      checked_for_plugin_pdf_interface_(false),
542      gamepad_impl_(new GamepadImpl()),
543      uma_private_impl_(NULL),
544      plugin_print_interface_(NULL),
545      plugin_graphics_3d_interface_(NULL),
546      always_on_top_(false),
547      fullscreen_container_(NULL),
548      flash_fullscreen_(false),
549      desired_fullscreen_state_(false),
550      sad_plugin_(NULL),
551      input_event_mask_(0),
552      filtered_input_event_mask_(0),
553      text_input_type_(kPluginDefaultTextInputType),
554      text_input_caret_(0, 0, 0, 0),
555      text_input_caret_bounds_(0, 0, 0, 0),
556      text_input_caret_set_(false),
557      selection_caret_(0),
558      selection_anchor_(0),
559      pending_user_gesture_(0.0),
560      document_loader_(NULL),
561      external_document_load_(false),
562      npp_(new NPP_t),
563      isolate_(v8::Isolate::GetCurrent()),
564      is_deleted_(false),
565      last_input_number_(0),
566      is_tracking_latency_(false),
567      view_change_weak_ptr_factory_(this),
568      weak_factory_(this) {
569  pp_instance_ = HostGlobals::Get()->AddInstance(this);
570
571  memset(&current_print_settings_, 0, sizeof(current_print_settings_));
572  module_->InstanceCreated(this);
573
574  if (render_frame) {  // NULL in tests
575    render_frame->render_view()->PepperInstanceCreated(this);
576    // Bind a callback now so that we can inform the RenderViewImpl when we are
577    // destroyed. This works around a temporary problem stemming from work to
578    // move parts of RenderViewImpl in to RenderFrameImpl (see
579    // crbug.com/245126). If destruction happens in this order:
580    //  1) RenderFrameImpl
581    //  2) PepperPluginInstanceImpl
582    //  3) RenderViewImpl
583    // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
584    // to the RenderViewImpl. But when the instance is destroyed, it still
585    // needs to inform the RenderViewImpl that it has gone away, otherwise
586    // between (2) and (3), the RenderViewImpl will still have the dead
587    // instance in its active set, and so might make calls on the deleted
588    // instance. See crbug.com/343576 for more information. Once the plugin
589    // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
590    // can be a little bit simplified by instead making a direct call on
591    // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
592    instance_deleted_callback_ =
593        base::Bind(&RenderViewImpl::PepperInstanceDeleted,
594                   render_frame->render_view()->AsWeakPtr(),
595                   base::Unretained(this));
596    view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
597
598    // Set the initial focus.
599    SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
600
601    if (!module_->IsProxied()) {
602      PepperBrowserConnection* browser_connection =
603          PepperBrowserConnection::Get(render_frame_);
604      browser_connection->DidCreateInProcessInstance(
605          pp_instance(),
606          render_frame_->GetRoutingID(),
607          container_->element().document().url(),
608          GetPluginURL());
609    }
610  }
611
612  RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
613  resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
614
615  if (GetContentClient()->renderer() &&  // NULL in unit tests.
616      GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
617    external_document_load_ = true;
618}
619
620PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
621  DCHECK(!fullscreen_container_);
622
623  // Free all the plugin objects. This will automatically clear the back-
624  // pointer from the NPObject so WebKit can't call into the plugin any more.
625  //
626  // Swap out the set so we can delete from it (the objects will try to
627  // unregister themselves inside the delete call).
628  PluginObjectSet plugin_object_copy;
629  live_plugin_objects_.swap(plugin_object_copy);
630  for (PluginObjectSet::iterator i = plugin_object_copy.begin();
631       i != plugin_object_copy.end();
632       ++i)
633    delete *i;
634
635  if (TrackedCallback::IsPending(lock_mouse_callback_))
636    lock_mouse_callback_->Abort();
637
638  if (!instance_deleted_callback_.is_null())
639    instance_deleted_callback_.Run();
640
641  if (!module_->IsProxied() && render_frame_) {
642    PepperBrowserConnection* browser_connection =
643        PepperBrowserConnection::Get(render_frame_);
644    browser_connection->DidDeleteInProcessInstance(pp_instance());
645  }
646
647  UnSetAndDeleteLockTargetAdapter();
648  module_->InstanceDeleted(this);
649  // If we switched from the NaCl plugin module, notify it too.
650  if (original_module_.get())
651    original_module_->InstanceDeleted(this);
652
653  // This should be last since some of the above "instance deleted" calls will
654  // want to look up in the global map to get info off of our object.
655  HostGlobals::Get()->InstanceDeleted(pp_instance_);
656}
657
658// NOTE: Any of these methods that calls into the plugin needs to take into
659// account that the plugin may use Var to remove the <embed> from the DOM, which
660// will make the PepperWebPluginImpl drop its reference, usually the last one.
661// If a method needs to access a member of the instance after the call has
662// returned, then it needs to keep its own reference on the stack.
663
664v8::Local<v8::Context> PepperPluginInstanceImpl::GetContext() {
665  if (!container_)
666    return v8::Handle<v8::Context>();
667  WebLocalFrame* frame = container_->element().document().frame();
668  if (!frame)
669    return v8::Handle<v8::Context>();
670
671  v8::Local<v8::Context> context = frame->mainWorldScriptContext();
672  DCHECK(context->GetIsolate() == isolate_);
673  return context;
674}
675
676void PepperPluginInstanceImpl::Delete() {
677  is_deleted_ = true;
678
679  if (render_frame_ &&
680      render_frame_->render_view()->plugin_find_handler() == this) {
681    render_frame_->render_view()->set_plugin_find_handler(NULL);
682  }
683
684  // Keep a reference on the stack. See NOTE above.
685  scoped_refptr<PepperPluginInstanceImpl> ref(this);
686  // Force the MessageChannel to release its "passthrough object" which should
687  // release our last reference to the "InstanceObject" and will probably
688  // destroy it. We want to do this prior to calling DidDestroy in case the
689  // destructor of the instance object tries to use the instance.
690  message_channel_->SetPassthroughObject(NULL);
691  // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
692  // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
693  // since there is little that it can do at this point.
694  if (original_instance_interface_)
695    original_instance_interface_->DidDestroy(pp_instance());
696  else
697    instance_interface_->DidDestroy(pp_instance());
698  // Ensure we don't attempt to call functions on the destroyed instance.
699  original_instance_interface_.reset();
700  instance_interface_.reset();
701
702  if (fullscreen_container_) {
703    fullscreen_container_->Destroy();
704    fullscreen_container_ = NULL;
705  }
706
707  // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
708  // leaks the graphics 2D, it may actually get cleaned up after our
709  // destruction, so we need its pointers to be up-to-date.
710  BindGraphics(pp_instance(), 0);
711  container_ = NULL;
712}
713
714bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
715
716void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
717                                     const gfx::Rect& plugin_rect,
718                                     const gfx::Rect& paint_rect) {
719  TRACE_EVENT0("ppapi", "PluginInstance::Paint");
720  if (module()->is_crashed()) {
721    // Crashed plugin painting.
722    if (!sad_plugin_)  // Lazily initialize bitmap.
723      sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
724    if (sad_plugin_)
725      PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
726    return;
727  }
728
729  if (bound_graphics_2d_platform_)
730    bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
731}
732
733void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
734  if (fullscreen_container_) {
735    if (rect.IsEmpty())
736      fullscreen_container_->Invalidate();
737    else
738      fullscreen_container_->InvalidateRect(rect);
739  } else {
740    if (!container_ || view_data_.rect.size.width == 0 ||
741        view_data_.rect.size.height == 0)
742      return;  // Nothing to do.
743    if (rect.IsEmpty())
744      container_->invalidate();
745    else
746      container_->invalidateRect(rect);
747  }
748
749  cc::Layer* layer =
750      texture_layer_ ? texture_layer_.get() : compositor_layer_.get();
751  if (layer) {
752    if (rect.IsEmpty()) {
753      layer->SetNeedsDisplay();
754    } else {
755      layer->SetNeedsDisplayRect(rect);
756    }
757  }
758}
759
760void PepperPluginInstanceImpl::ScrollRect(int dx,
761                                          int dy,
762                                          const gfx::Rect& rect) {
763  cc::Layer* layer =
764      texture_layer_ ? texture_layer_.get() : compositor_layer_.get();
765  if (layer) {
766    InvalidateRect(rect);
767  } else if (fullscreen_container_) {
768    fullscreen_container_->ScrollRect(dx, dy, rect);
769  } else {
770    if (full_frame_ && !IsViewAccelerated()) {
771      container_->scrollRect(rect);
772    } else {
773      // Can't do optimized scrolling since there could be other elements on top
774      // of us or the view renders via the accelerated compositor which is
775      // incompatible with the move and backfill scrolling model.
776      InvalidateRect(rect);
777    }
778  }
779}
780
781void PepperPluginInstanceImpl::CommitBackingTexture() {
782  if (!texture_layer_.get())
783    return;
784  gpu::Mailbox mailbox;
785  uint32 sync_point = 0;
786  bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
787  DCHECK(!mailbox.IsZero());
788  DCHECK_NE(sync_point, 0u);
789  texture_layer_->SetTextureMailboxWithoutReleaseCallback(
790      cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
791  texture_layer_->SetNeedsDisplay();
792}
793
794void PepperPluginInstanceImpl::InstanceCrashed() {
795  // Force free all resources and vars.
796  HostGlobals::Get()->InstanceCrashed(pp_instance());
797
798  // Free any associated graphics.
799  SetFullscreen(false);
800  FlashSetFullscreen(false, false);
801  // Unbind current 2D or 3D graphics context.
802  BindGraphics(pp_instance(), 0);
803  InvalidateRect(gfx::Rect());
804
805  if (content_decryptor_delegate_) {
806    content_decryptor_delegate_->InstanceCrashed();
807    content_decryptor_delegate_.reset();
808  }
809
810  if (render_frame_)
811    render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
812  UnSetAndDeleteLockTargetAdapter();
813}
814
815static void SetGPUHistogram(const ppapi::Preferences& prefs,
816                            const std::vector<std::string>& arg_names,
817                            const std::vector<std::string>& arg_values) {
818// Calculate a histogram to let us determine how likely people are to try to
819// run Stage3D content on machines that have it blacklisted.
820#if defined(OS_WIN)
821  bool needs_gpu = false;
822  bool is_xp = base::win::GetVersion() <= base::win::VERSION_XP;
823
824  for (size_t i = 0; i < arg_names.size(); i++) {
825    if (arg_names[i] == "wmode") {
826      // In theory content other than Flash could have a "wmode" argument,
827      // but that's pretty unlikely.
828      if (arg_values[i] == "direct" || arg_values[i] == "gpu")
829        needs_gpu = true;
830      break;
831    }
832  }
833  // 0 : No 3D content and GPU is blacklisted
834  // 1 : No 3D content and GPU is not blacklisted
835  // 2 : 3D content but GPU is blacklisted
836  // 3 : 3D content and GPU is not blacklisted
837  // 4 : No 3D content and GPU is blacklisted on XP
838  // 5 : No 3D content and GPU is not blacklisted on XP
839  // 6 : 3D content but GPU is blacklisted on XP
840  // 7 : 3D content and GPU is not blacklisted on XP
841  UMA_HISTOGRAM_ENUMERATION(
842      "Flash.UsesGPU", is_xp * 4 + needs_gpu * 2 + prefs.is_webgl_supported, 8);
843#endif
844}
845
846bool PepperPluginInstanceImpl::Initialize(
847    const std::vector<std::string>& arg_names,
848    const std::vector<std::string>& arg_values,
849    bool full_frame) {
850  if (!render_frame_)
851    return false;
852  message_channel_.reset(new MessageChannel(this));
853
854  full_frame_ = full_frame;
855
856  UpdateTouchEventRequest();
857  container_->setWantsWheelEvents(IsAcceptingWheelEvents());
858
859  SetGPUHistogram(ppapi::Preferences(PpapiPreferencesBuilder::Build(
860                      render_frame_->render_view()->webkit_preferences())),
861                  arg_names,
862                  arg_values);
863
864  argn_ = arg_names;
865  argv_ = arg_values;
866  scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
867  scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
868  bool success = PP_ToBool(instance_interface_->DidCreate(
869      pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
870  // If this is a plugin that hosts external plugins, we should delay messages
871  // so that the child plugin that's created later will receive all the
872  // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
873  //
874  // A host for external plugins will call ResetAsProxied later, at which point
875  // we can Start() the message_channel_.
876  if (success && (!module_->renderer_ppapi_host()->IsExternalPluginHost()))
877    message_channel_->Start();
878  return success;
879}
880
881bool PepperPluginInstanceImpl::HandleDocumentLoad(
882    const blink::WebURLResponse& response) {
883  DCHECK(!document_loader_);
884  if (external_document_load_) {
885    // The external proxy isn't available, so save the response and record
886    // document load notifications for later replay.
887    external_document_response_ = response;
888    external_document_loader_.reset(new ExternalDocumentLoader());
889    document_loader_ = external_document_loader_.get();
890    return true;
891  }
892
893  if (module()->is_crashed()) {
894    // Don't create a resource for a crashed plugin.
895    container()->element().document().frame()->stopLoading();
896    return false;
897  }
898
899  DCHECK(!document_loader_);
900
901  // Create a loader resource host for this load. Note that we have to set
902  // the document_loader before issuing the in-process
903  // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
904  // call into the instance and expect it to be valid.
905  RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
906  PepperURLLoaderHost* loader_host =
907      new PepperURLLoaderHost(host_impl, true, pp_instance(), 0);
908  // TODO(teravest): Remove set_document_loader() from instance and clean up
909  // this relationship.
910  set_document_loader(loader_host);
911  loader_host->didReceiveResponse(NULL, response);
912
913  // This host will be pending until the resource object attaches to it.
914  //
915  // PpapiHost now owns the pointer to loader_host, so we don't have to worry
916  // about managing it.
917  int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
918      scoped_ptr<ppapi::host::ResourceHost>(loader_host));
919  DCHECK(pending_host_id);
920
921  DataFromWebURLResponse(
922      host_impl,
923      pp_instance(),
924      response,
925      base::Bind(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
926                 weak_factory_.GetWeakPtr(),
927                 response,
928                 pending_host_id));
929
930  // If the load was not abandoned, document_loader_ will now be set. It's
931  // possible that the load was canceled by now and document_loader_ was
932  // already nulled out.
933  return true;
934}
935
936bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
937    PP_InputEvent_Type type,
938    const base::string16& text) {
939  std::vector<blink::WebCompositionUnderline> empty;
940  return SendCompositionEventWithUnderlineInformationToPlugin(
941      type,
942      text,
943      empty,
944      static_cast<int>(text.size()),
945      static_cast<int>(text.size()));
946}
947
948bool
949PepperPluginInstanceImpl::SendCompositionEventWithUnderlineInformationToPlugin(
950    PP_InputEvent_Type type,
951    const base::string16& text,
952    const std::vector<blink::WebCompositionUnderline>& underlines,
953    int selection_start,
954    int selection_end) {
955  // Keep a reference on the stack. See NOTE above.
956  scoped_refptr<PepperPluginInstanceImpl> ref(this);
957
958  if (!LoadInputEventInterface())
959    return false;
960
961  PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
962  if (!(filtered_input_event_mask_ & event_class) &&
963      !(input_event_mask_ & event_class))
964    return false;
965
966  ppapi::InputEventData event;
967  event.event_type = type;
968  event.event_time_stamp =
969      ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
970
971  // Convert UTF16 text to UTF8 with offset conversion.
972  std::vector<size_t> utf16_offsets;
973  utf16_offsets.push_back(selection_start);
974  utf16_offsets.push_back(selection_end);
975  for (size_t i = 0; i < underlines.size(); ++i) {
976    utf16_offsets.push_back(underlines[i].startOffset);
977    utf16_offsets.push_back(underlines[i].endOffset);
978  }
979  std::vector<size_t> utf8_offsets(utf16_offsets);
980  event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
981
982  // Set the converted selection range.
983  event.composition_selection_start =
984      (utf8_offsets[0] == std::string::npos ? event.character_text.size()
985                                            : utf8_offsets[0]);
986  event.composition_selection_end =
987      (utf8_offsets[1] == std::string::npos ? event.character_text.size()
988                                            : utf8_offsets[1]);
989
990  // Set the converted segmentation points.
991  // Be sure to add 0 and size(), and remove duplication or errors.
992  std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
993  offset_set.insert(0);
994  offset_set.insert(event.character_text.size());
995  offset_set.erase(std::string::npos);
996  event.composition_segment_offsets.assign(offset_set.begin(),
997                                           offset_set.end());
998
999  // Set the composition target.
1000  for (size_t i = 0; i < underlines.size(); ++i) {
1001    if (underlines[i].thick) {
1002      std::vector<uint32_t>::iterator it =
1003          std::find(event.composition_segment_offsets.begin(),
1004                    event.composition_segment_offsets.end(),
1005                    utf8_offsets[2 * i + 2]);
1006      if (it != event.composition_segment_offsets.end()) {
1007        event.composition_target_segment =
1008            it - event.composition_segment_offsets.begin();
1009        break;
1010      }
1011    }
1012  }
1013
1014  // Send the event.
1015  bool handled = false;
1016  if (filtered_input_event_mask_ & event_class)
1017    event.is_filtered = true;
1018  else
1019    handled = true;  // Unfiltered events are assumed to be handled.
1020  scoped_refptr<PPB_InputEvent_Shared> event_resource(
1021      new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
1022  handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1023      pp_instance(), event_resource->pp_resource()));
1024  return handled;
1025}
1026
1027void PepperPluginInstanceImpl::RequestInputEventsHelper(
1028    uint32_t event_classes) {
1029  if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
1030    UpdateTouchEventRequest();
1031  if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
1032    container_->setWantsWheelEvents(IsAcceptingWheelEvents());
1033}
1034
1035bool PepperPluginInstanceImpl::HandleCompositionStart(
1036    const base::string16& text) {
1037  return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1038                                      text);
1039}
1040
1041bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1042    const base::string16& text,
1043    const std::vector<blink::WebCompositionUnderline>& underlines,
1044    int selection_start,
1045    int selection_end) {
1046  return SendCompositionEventWithUnderlineInformationToPlugin(
1047      PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
1048      text,
1049      underlines,
1050      selection_start,
1051      selection_end);
1052}
1053
1054bool PepperPluginInstanceImpl::HandleCompositionEnd(
1055    const base::string16& text) {
1056  return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1057                                      text);
1058}
1059
1060bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1061  return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1062}
1063
1064void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1065                                                  gfx::Range* range) const {
1066  std::vector<size_t> offsets;
1067  offsets.push_back(selection_anchor_);
1068  offsets.push_back(selection_caret_);
1069  *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1070  range->set_start(offsets[0] == base::string16::npos ? text->size()
1071                                                      : offsets[0]);
1072  range->set_end(offsets[1] == base::string16::npos ? text->size()
1073                                                    : offsets[1]);
1074}
1075
1076bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1077  return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1078         (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1079}
1080
1081gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1082  if (!text_input_caret_set_) {
1083    // If it is never set by the plugin, use the bottom left corner.
1084    return gfx::Rect(view_data_.rect.point.x,
1085                     view_data_.rect.point.y + view_data_.rect.size.height,
1086                     0,
1087                     0);
1088  }
1089
1090  // TODO(kinaba) Take CSS transformation into accont.
1091  // TODO(kinaba) Take bounding_box into account. On some platforms, an
1092  // "exclude rectangle" where candidate window must avoid the region can be
1093  // passed to IME. Currently, we pass only the caret rectangle because
1094  // it is the only information supported uniformly in Chromium.
1095  gfx::Rect caret(text_input_caret_);
1096  caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1097  return caret;
1098}
1099
1100bool PepperPluginInstanceImpl::HandleInputEvent(
1101    const blink::WebInputEvent& event,
1102    WebCursorInfo* cursor_info) {
1103  TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1104
1105  if (!render_frame_)
1106    return false;
1107  if (WebInputEvent::isMouseEventType(event.type)) {
1108    render_frame_->PepperDidReceiveMouseEvent(this);
1109  }
1110
1111  // Don't dispatch input events to crashed plugins.
1112  if (module()->is_crashed())
1113    return false;
1114
1115  // Don't send reserved system key events to plugins.
1116  if (IsReservedSystemInputEvent(event))
1117    return false;
1118
1119  // Keep a reference on the stack. See NOTE above.
1120  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1121
1122  bool rv = false;
1123  if (LoadInputEventInterface()) {
1124    PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
1125    if (!event_class)
1126      return false;
1127
1128    if ((filtered_input_event_mask_ & event_class) ||
1129        (input_event_mask_ & event_class)) {
1130      // Actually send the event.
1131      std::vector<ppapi::InputEventData> events;
1132      CreateInputEventData(event, &events);
1133
1134      // Allow the user gesture to be pending after the plugin handles the
1135      // event. This allows out-of-process plugins to respond to the user
1136      // gesture after processing has finished here.
1137      if (WebUserGestureIndicator::isProcessingUserGesture()) {
1138        pending_user_gesture_ =
1139            ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
1140        pending_user_gesture_token_ =
1141            WebUserGestureIndicator::currentUserGestureToken();
1142        pending_user_gesture_token_.setOutOfProcess();
1143      }
1144
1145      const ui::LatencyInfo* current_event_latency_info = NULL;
1146      if (render_frame_->GetRenderWidget()) {
1147        current_event_latency_info =
1148            render_frame_->GetRenderWidget()->current_event_latency_info();
1149      }
1150
1151      // Each input event may generate more than one PP_InputEvent.
1152      for (size_t i = 0; i < events.size(); i++) {
1153        if (is_tracking_latency_) {
1154          InitLatencyInfo(&events[i].latency_info,
1155                          current_event_latency_info,
1156                          event.type,
1157                          last_input_number_++);
1158        }
1159        if (filtered_input_event_mask_ & event_class)
1160          events[i].is_filtered = true;
1161        else
1162          rv = true;  // Unfiltered events are assumed to be handled.
1163        scoped_refptr<PPB_InputEvent_Shared> event_resource(
1164            new PPB_InputEvent_Shared(
1165                ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1166
1167        rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1168            pp_instance(), event_resource->pp_resource()));
1169      }
1170    }
1171  }
1172
1173  if (cursor_)
1174    *cursor_info = *cursor_;
1175  return rv;
1176}
1177
1178void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1179  TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1180  ppapi::proxy::HostDispatcher* dispatcher =
1181      ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1182  if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1183    // The dispatcher should always be valid, and MessageChannel should never
1184    // send an 'object' var over PPP_Messaging.
1185    NOTREACHED();
1186    return;
1187  }
1188  dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1189      ppapi::API_ID_PPP_MESSAGING,
1190      pp_instance(),
1191      ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1192                                                pp_instance())));
1193}
1194
1195bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1196                                                     ScopedPPVar* result) {
1197  TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
1198  ppapi::proxy::HostDispatcher* dispatcher =
1199      ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1200  if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1201    // The dispatcher should always be valid, and MessageChannel should never
1202    // send an 'object' var over PPP_Messaging.
1203    NOTREACHED();
1204    return false;
1205  }
1206  ppapi::proxy::ReceiveSerializedVarReturnValue msg_reply;
1207  bool was_handled = false;
1208  dispatcher->Send(new PpapiMsg_PPPMessageHandler_HandleBlockingMessage(
1209      ppapi::API_ID_PPP_MESSAGING,
1210      pp_instance(),
1211      ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1212                                                pp_instance()),
1213      &msg_reply,
1214      &was_handled));
1215  *result = ScopedPPVar(ScopedPPVar::PassRef(), msg_reply.Return(dispatcher));
1216  TRACE_EVENT0("ppapi",
1217               "PepperPluginInstanceImpl::HandleBlockingMessage return.");
1218  return was_handled;
1219}
1220
1221PP_Var PepperPluginInstanceImpl::GetInstanceObject() {
1222  // Keep a reference on the stack. See NOTE above.
1223  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1224
1225  // If the plugin supports the private instance interface, try to retrieve its
1226  // instance object.
1227  if (LoadPrivateInterface())
1228    return plugin_private_interface_->GetInstanceObject(pp_instance());
1229  return PP_MakeUndefined();
1230}
1231
1232void PepperPluginInstanceImpl::ViewChanged(
1233    const gfx::Rect& position,
1234    const gfx::Rect& clip,
1235    const std::vector<gfx::Rect>& cut_outs_rects) {
1236  // WebKit can give weird (x,y) positions for empty clip rects (since the
1237  // position technically doesn't matter). But we want to make these
1238  // consistent since this is given to the plugin, so force everything to 0
1239  // in the "everything is clipped" case.
1240  gfx::Rect new_clip;
1241  if (!clip.IsEmpty())
1242    new_clip = clip;
1243
1244  cut_outs_rects_ = cut_outs_rects;
1245
1246  view_data_.rect = PP_FromGfxRect(position);
1247  view_data_.clip_rect = PP_FromGfxRect(clip);
1248  view_data_.device_scale = container_->deviceScaleFactor();
1249  view_data_.css_scale =
1250      container_->pageZoomFactor() * container_->pageScaleFactor();
1251
1252  gfx::Size scroll_offset =
1253      container_->element().document().frame()->scrollOffset();
1254  view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1255                                          scroll_offset.height());
1256
1257  if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1258    WebElement element = container_->element();
1259    WebDocument document = element.document();
1260    bool is_fullscreen_element = (element == document.fullScreenElement());
1261    if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1262        render_frame()->GetRenderWidget()->is_fullscreen() &&
1263        is_fullscreen_element) {
1264      // Entered fullscreen. Only possible via SetFullscreen().
1265      view_data_.is_fullscreen = true;
1266    } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1267      // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1268      // so desired_fullscreen_state might be out-of-date.
1269      desired_fullscreen_state_ = false;
1270      view_data_.is_fullscreen = false;
1271
1272      // This operation will cause the plugin to re-layout which will send more
1273      // DidChangeView updates. Schedule an asynchronous update and suppress
1274      // notifications until that completes to avoid sending intermediate sizes
1275      // to the plugins.
1276      ScheduleAsyncDidChangeView();
1277
1278      // Reset the size attributes that we hacked to fill in the screen and
1279      // retrigger ViewChanged. Make sure we don't forward duplicates of
1280      // this view to the plugin.
1281      ResetSizeAttributesAfterFullscreen();
1282      return;
1283    }
1284  }
1285
1286  UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1287
1288  SendDidChangeView();
1289}
1290
1291void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1292  if (has_webkit_focus_ == has_focus)
1293    return;
1294
1295  bool old_plugin_focus = PluginHasFocus();
1296  has_webkit_focus_ = has_focus;
1297  if (PluginHasFocus() != old_plugin_focus)
1298    SendFocusChangeNotification();
1299}
1300
1301void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1302  if (has_content_area_focus_ == has_focus)
1303    return;
1304
1305  bool old_plugin_focus = PluginHasFocus();
1306  has_content_area_focus_ = has_focus;
1307  if (PluginHasFocus() != old_plugin_focus)
1308    SendFocusChangeNotification();
1309}
1310
1311void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1312  if (is_visible == view_data_.is_page_visible)
1313    return;  // Nothing to do.
1314  view_data_.is_page_visible = is_visible;
1315
1316  // If the initial DidChangeView notification hasn't been sent to the plugin,
1317  // let it pass the visibility state for us, instead of sending a notification
1318  // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1319  // hasn't been called for the first time. In that case, most of the fields in
1320  // |view_data_| haven't been properly initialized.
1321  if (sent_initial_did_change_view_)
1322    SendDidChangeView();
1323}
1324
1325void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1326  if (bound_graphics_2d_platform_)
1327    bound_graphics_2d_platform_->ViewInitiatedPaint();
1328  else if (bound_graphics_3d_.get())
1329    bound_graphics_3d_->ViewInitiatedPaint();
1330  else if (bound_compositor_)
1331    bound_compositor_->ViewInitiatedPaint();
1332}
1333
1334void PepperPluginInstanceImpl::ViewFlushedPaint() {
1335  // Keep a reference on the stack. See NOTE above.
1336  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1337  if (bound_graphics_2d_platform_)
1338    bound_graphics_2d_platform_->ViewFlushedPaint();
1339  else if (bound_graphics_3d_.get())
1340    bound_graphics_3d_->ViewFlushedPaint();
1341  else if (bound_compositor_)
1342    bound_compositor_->ViewFlushedPaint();
1343}
1344
1345void PepperPluginInstanceImpl::SetSelectedText(
1346    const base::string16& selected_text) {
1347  selected_text_ = selected_text;
1348}
1349
1350void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1351  link_under_cursor_ = base::UTF8ToUTF16(url);
1352}
1353
1354void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1355  text_input_type_ = type;
1356  render_frame_->PepperTextInputTypeChanged(this);
1357}
1358
1359void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1360  message_channel_->PostMessageToJavaScript(message);
1361}
1362
1363int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1364    PP_Instance instance,
1365    void* user_data,
1366    const PPP_MessageHandler_0_1* handler,
1367    PP_Resource message_loop) {
1368  // Not supported in-process.
1369  NOTIMPLEMENTED();
1370  return PP_ERROR_FAILED;
1371}
1372
1373void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1374  // Not supported in-process.
1375  NOTIMPLEMENTED();
1376}
1377
1378base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1379  // Keep a reference on the stack. See NOTE above.
1380  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1381  if (!LoadSelectionInterface())
1382    return selected_text_;
1383
1384  PP_Var rv = plugin_selection_interface_->GetSelectedText(pp_instance(),
1385                                                           PP_FromBool(html));
1386  StringVar* string = StringVar::FromPPVar(rv);
1387  base::string16 selection;
1388  if (string)
1389    selection = base::UTF8ToUTF16(string->value());
1390  // Release the ref the plugin transfered to us.
1391  HostGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1392  return selection;
1393}
1394
1395base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1396    const gfx::Point& point) {
1397  // Keep a reference on the stack. See NOTE above.
1398  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1399  if (!LoadPdfInterface()) {
1400    // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1401    // return |link_under_cursor_| here because this is only ever called with
1402    // the current mouse coordinates.
1403    return link_under_cursor_;
1404  }
1405
1406  PP_Point p;
1407  p.x = point.x();
1408  p.y = point.y();
1409  PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1410  // If the plugin returns undefined for this function it has switched to
1411  // providing us with the link under the cursor eagerly.
1412  if (rv.type == PP_VARTYPE_UNDEFINED)
1413    return link_under_cursor_;
1414  StringVar* string = StringVar::FromPPVar(rv);
1415  base::string16 link;
1416  if (string)
1417    link = base::UTF8ToUTF16(string->value());
1418  // Release the ref the plugin transfered to us.
1419  PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1420  return link;
1421}
1422
1423void PepperPluginInstanceImpl::RequestSurroundingText(
1424    size_t desired_number_of_characters) {
1425  // Keep a reference on the stack. See NOTE above.
1426  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1427  if (!LoadTextInputInterface())
1428    return;
1429  plugin_textinput_interface_->RequestSurroundingText(
1430      pp_instance(), desired_number_of_characters);
1431}
1432
1433void PepperPluginInstanceImpl::Zoom(double factor, bool text_only) {
1434  // Keep a reference on the stack. See NOTE above.
1435  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1436  if (!LoadZoomInterface())
1437    return;
1438  plugin_zoom_interface_->Zoom(pp_instance(), factor, PP_FromBool(text_only));
1439}
1440
1441bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1442                                         bool case_sensitive,
1443                                         int identifier) {
1444  // Keep a reference on the stack. See NOTE above.
1445  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1446  if (!LoadFindInterface())
1447    return false;
1448  find_identifier_ = identifier;
1449  return PP_ToBool(
1450      plugin_find_interface_->StartFind(pp_instance(),
1451                                        base::UTF16ToUTF8(search_text).c_str(),
1452                                        PP_FromBool(case_sensitive)));
1453}
1454
1455void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1456  // Keep a reference on the stack. See NOTE above.
1457  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1458  if (LoadFindInterface())
1459    plugin_find_interface_->SelectFindResult(pp_instance(),
1460                                             PP_FromBool(forward));
1461}
1462
1463void PepperPluginInstanceImpl::StopFind() {
1464  // Keep a reference on the stack. See NOTE above.
1465  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1466  if (!LoadFindInterface())
1467    return;
1468  find_identifier_ = -1;
1469  plugin_find_interface_->StopFind(pp_instance());
1470}
1471
1472bool PepperPluginInstanceImpl::LoadFindInterface() {
1473  if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1474    return false;
1475  if (!plugin_find_interface_) {
1476    plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1477        module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1478  }
1479
1480  return !!plugin_find_interface_;
1481}
1482
1483bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1484  if (!checked_for_plugin_input_event_interface_) {
1485    checked_for_plugin_input_event_interface_ = true;
1486    plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1487        module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1488  }
1489  return !!plugin_input_event_interface_;
1490}
1491
1492bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1493  if (!plugin_mouse_lock_interface_) {
1494    plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1495        module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1496  }
1497
1498  return !!plugin_mouse_lock_interface_;
1499}
1500
1501bool PepperPluginInstanceImpl::LoadPdfInterface() {
1502  if (!checked_for_plugin_pdf_interface_) {
1503    checked_for_plugin_pdf_interface_ = true;
1504    plugin_pdf_interface_ = static_cast<const PPP_Pdf_1*>(
1505        module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1506  }
1507
1508  return !!plugin_pdf_interface_;
1509}
1510
1511bool PepperPluginInstanceImpl::LoadPrintInterface() {
1512  // Only check for the interface if the plugin has dev permission.
1513  if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1514    return false;
1515  if (!plugin_print_interface_) {
1516    plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1517        module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1518  }
1519  return !!plugin_print_interface_;
1520}
1521
1522bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1523  // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1524  // call GetInstanceObject. This is necessary to ensure that the properties
1525  // the trusted plugin exposes (readyState and lastError) work properly. Note
1526  // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1527  // so it's correct to never look up PPP_InstancePrivate for them.
1528  //
1529  // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1530  // to the "real" module.
1531  scoped_refptr<PluginModule> module =
1532      original_module_ ? original_module_ : module_;
1533  // Only check for the interface if the plugin has private permission.
1534  if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1535    return false;
1536  if (!plugin_private_interface_) {
1537    plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1538        module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1539  }
1540
1541  return !!plugin_private_interface_;
1542}
1543
1544bool PepperPluginInstanceImpl::LoadSelectionInterface() {
1545  if (!plugin_selection_interface_) {
1546    plugin_selection_interface_ = static_cast<const PPP_Selection_Dev*>(
1547        module_->GetPluginInterface(PPP_SELECTION_DEV_INTERFACE));
1548  }
1549  return !!plugin_selection_interface_;
1550}
1551
1552bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1553  if (!plugin_textinput_interface_) {
1554    plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1555        module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1556  }
1557
1558  return !!plugin_textinput_interface_;
1559}
1560
1561bool PepperPluginInstanceImpl::LoadZoomInterface() {
1562  if (!plugin_zoom_interface_) {
1563    plugin_zoom_interface_ = static_cast<const PPP_Zoom_Dev*>(
1564        module_->GetPluginInterface(PPP_ZOOM_DEV_INTERFACE));
1565  }
1566
1567  return !!plugin_zoom_interface_;
1568}
1569
1570void PepperPluginInstanceImpl::UpdateLayerTransform() {
1571  if (!bound_graphics_2d_platform_ || !texture_layer_) {
1572    // Currently the transform is only applied for Graphics2D.
1573    return;
1574  }
1575  // Set the UV coordinates of the texture based on the size of the Graphics2D
1576  // context. By default a texture gets scaled to the size of the layer. But
1577  // if the size of the Graphics2D context doesn't match the size of the plugin
1578  // then it will be incorrectly stretched. This also affects how the plugin
1579  // is painted when it is being resized. If the Graphics2D contents are
1580  // stretched when a plugin is resized while waiting for a new frame from the
1581  // plugin to be rendered, then flickering behavior occurs as in
1582  // crbug.com/353453.
1583  gfx::SizeF graphics_2d_size_in_dip =
1584      gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1585                     bound_graphics_2d_platform_->GetScale());
1586  gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1587                               view_data_.rect.size.height);
1588
1589  texture_layer_->SetUV(
1590      gfx::PointF(0.0f, 0.0f),
1591      gfx::PointF(
1592          plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1593          plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1594}
1595
1596bool PepperPluginInstanceImpl::PluginHasFocus() const {
1597  return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1598}
1599
1600void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1601  // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1602  // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1603  // drop its reference, usually the last one. This is similar to possible
1604  // plugin behavior described at the NOTE above Delete().
1605  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1606
1607  if (!render_frame_)
1608    return;
1609
1610  bool has_focus = PluginHasFocus();
1611  render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1612
1613  // instance_interface_ may have been cleared in Delete() if the
1614  // PepperWebPluginImpl is destroyed.
1615  if (instance_interface_)
1616    instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1617}
1618
1619void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1620  bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1621                   (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1622  container_->requestTouchEventType(
1623      raw_touch
1624          ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1625          : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1626}
1627
1628bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1629  return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1630         (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1631}
1632
1633void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1634  if (view_change_weak_ptr_factory_.HasWeakPtrs())
1635    return;  // Already scheduled.
1636  base::MessageLoop::current()->PostTask(
1637      FROM_HERE,
1638      base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1639                 view_change_weak_ptr_factory_.GetWeakPtr()));
1640}
1641
1642void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1643  // The bound callback that owns the weak pointer is still valid until after
1644  // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1645  // invalidate them here.
1646  // NOTE: If we ever want to have more than one pending callback, it should
1647  // use a different factory, or we should have a different strategy here.
1648  view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1649  SendDidChangeView();
1650}
1651
1652void PepperPluginInstanceImpl::SendDidChangeView() {
1653  // Don't send DidChangeView to crashed plugins.
1654  if (module()->is_crashed())
1655    return;
1656
1657  if (view_change_weak_ptr_factory_.HasWeakPtrs() ||
1658      (sent_initial_did_change_view_ &&
1659       last_sent_view_data_.Equals(view_data_)))
1660    return;  // Nothing to update.
1661
1662  sent_initial_did_change_view_ = true;
1663  last_sent_view_data_ = view_data_;
1664  ScopedPPResource resource(
1665      ScopedPPResource::PassRef(),
1666      (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data_))
1667          ->GetReference());
1668
1669  UpdateLayerTransform();
1670
1671  // It's possible that Delete() has been called but the renderer hasn't
1672  // released its reference to this object yet.
1673  if (instance_interface_) {
1674    instance_interface_->DidChangeView(
1675        pp_instance(), resource, &view_data_.rect, &view_data_.clip_rect);
1676  }
1677}
1678
1679void PepperPluginInstanceImpl::ReportGeometry() {
1680  // If this call was delayed, we may have transitioned back to fullscreen in
1681  // the mean time, so only report the geometry if we are actually in normal
1682  // mode.
1683  if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1684    container_->reportGeometry();
1685}
1686
1687bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1688    PP_PrintOutputFormat_Dev* format) {
1689  // Keep a reference on the stack. See NOTE above.
1690  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1691  if (!LoadPrintInterface())
1692    return false;
1693  uint32_t supported_formats =
1694      plugin_print_interface_->QuerySupportedFormats(pp_instance());
1695  if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1696    *format = PP_PRINTOUTPUTFORMAT_PDF;
1697    return true;
1698  }
1699  return false;
1700}
1701
1702bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1703  PP_PrintOutputFormat_Dev format;
1704  return GetPreferredPrintOutputFormat(&format);
1705}
1706
1707bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1708  DCHECK(plugin_print_interface_);
1709  if (!plugin_print_interface_)
1710    return false;
1711  return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1712}
1713
1714int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1715  // Keep a reference on the stack. See NOTE above.
1716  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1717  PP_PrintOutputFormat_Dev format;
1718  if (!GetPreferredPrintOutputFormat(&format)) {
1719    // PrintBegin should not have been called since SupportsPrintInterface
1720    // would have returned false;
1721    NOTREACHED();
1722    return 0;
1723  }
1724  int num_pages = 0;
1725  PP_PrintSettings_Dev print_settings;
1726  print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1727  print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1728  print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1729  print_settings.dpi = print_params.printerDPI;
1730  print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1731  print_settings.grayscale = PP_FALSE;
1732  print_settings.print_scaling_option =
1733      static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1734  print_settings.format = format;
1735  num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1736  if (!num_pages)
1737    return 0;
1738  current_print_settings_ = print_settings;
1739  canvas_.clear();
1740  ranges_.clear();
1741  return num_pages;
1742}
1743
1744bool PepperPluginInstanceImpl::PrintPage(int page_number,
1745                                         blink::WebCanvas* canvas) {
1746#if defined(ENABLE_FULL_PRINTING)
1747  DCHECK(plugin_print_interface_);
1748  PP_PrintPageNumberRange_Dev page_range;
1749  page_range.first_page_number = page_range.last_page_number = page_number;
1750  // The canvas only has a metafile on it for print preview.
1751  bool save_for_later =
1752      (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1753#if defined(OS_MACOSX) || \
1754    (defined(OS_WIN) && !defined(WIN_PDF_METAFILE_FOR_PRINTING))
1755  save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1756#endif
1757  if (save_for_later) {
1758    ranges_.push_back(page_range);
1759    canvas_ = skia::SharePtr(canvas);
1760    return true;
1761  } else {
1762    return PrintPageHelper(&page_range, 1, canvas);
1763  }
1764#else  // defined(ENABLED_PRINTING)
1765  return false;
1766#endif
1767}
1768
1769bool PepperPluginInstanceImpl::PrintPageHelper(
1770    PP_PrintPageNumberRange_Dev* page_ranges,
1771    int num_ranges,
1772    blink::WebCanvas* canvas) {
1773  // Keep a reference on the stack. See NOTE above.
1774  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1775  DCHECK(plugin_print_interface_);
1776  if (!plugin_print_interface_)
1777    return false;
1778  PP_Resource print_output = plugin_print_interface_->PrintPages(
1779      pp_instance(), page_ranges, num_ranges);
1780  if (!print_output)
1781    return false;
1782
1783  bool ret = false;
1784
1785  if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1786    ret = PrintPDFOutput(print_output, canvas);
1787
1788  // Now we need to release the print output resource.
1789  PluginModule::GetCore()->ReleaseResource(print_output);
1790
1791  return ret;
1792}
1793
1794void PepperPluginInstanceImpl::PrintEnd() {
1795  // Keep a reference on the stack. See NOTE above.
1796  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1797  if (!ranges_.empty())
1798    PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1799  canvas_.clear();
1800  ranges_.clear();
1801
1802  DCHECK(plugin_print_interface_);
1803  if (plugin_print_interface_)
1804    plugin_print_interface_->End(pp_instance());
1805
1806  memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1807#if defined(OS_MACOSX)
1808  last_printed_page_ = NULL;
1809#endif  // defined(OS_MACOSX)
1810}
1811
1812bool PepperPluginInstanceImpl::CanRotateView() {
1813  if (!LoadPdfInterface())
1814    return false;
1815
1816  return true;
1817}
1818
1819void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1820  if (!LoadPdfInterface())
1821    return;
1822  PP_PrivatePageTransformType transform_type =
1823      type == WebPlugin::RotationType90Clockwise
1824          ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1825          : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1826  plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1827  // NOTE: plugin instance may have been deleted.
1828}
1829
1830bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1831  return fullscreen_container_ != NULL;
1832}
1833
1834bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1835  return desired_fullscreen_state_;
1836}
1837
1838bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1839  // Keep a reference on the stack. See NOTE above.
1840  scoped_refptr<PepperPluginInstanceImpl> ref(this);
1841
1842  // Check whether we are trying to switch to the state we're already going
1843  // to (i.e. if we're already switching to fullscreen but the fullscreen
1844  // container isn't ready yet, don't do anything more).
1845  if (fullscreen == IsFullscreenOrPending())
1846    return false;
1847
1848  if (!render_frame_)
1849    return false;
1850  if (fullscreen && !render_frame_->render_view()
1851                         ->renderer_preferences()
1852                         .plugin_fullscreen_allowed)
1853    return false;
1854
1855  // Check whether we are trying to switch while the state is in transition.
1856  // The 2nd request gets dropped while messing up the internal state, so
1857  // disallow this.
1858  if (view_data_.is_fullscreen != desired_fullscreen_state_)
1859    return false;
1860
1861  if (fullscreen && !IsProcessingUserGesture())
1862    return false;
1863
1864  VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1865  desired_fullscreen_state_ = fullscreen;
1866
1867  if (fullscreen) {
1868    // Create the user gesture in case we're processing one that's pending.
1869    WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1870    // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1871    // so we will tweak plugin's attributes to support the expected behavior.
1872    KeepSizeAttributesBeforeFullscreen();
1873    SetSizeAttributesForFullscreen();
1874    container_->element().requestFullScreen();
1875  } else {
1876    container_->element().document().cancelFullScreen();
1877  }
1878  return true;
1879}
1880
1881void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1882    bool flash_fullscreen) {
1883  bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1884
1885  if (flash_fullscreen == flash_fullscreen_) {
1886    // Manually clear callback when fullscreen fails with mouselock pending.
1887    if (!flash_fullscreen && is_mouselock_pending)
1888      lock_mouse_callback_->Run(PP_ERROR_FAILED);
1889    return;
1890  }
1891
1892  UpdateLayer(false);
1893
1894  bool old_plugin_focus = PluginHasFocus();
1895  flash_fullscreen_ = flash_fullscreen;
1896  if (is_mouselock_pending && !IsMouseLocked()) {
1897    if (!IsProcessingUserGesture() &&
1898        !module_->permissions().HasPermission(
1899            ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1900      lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1901    } else {
1902      // Open a user gesture here so the Webkit user gesture checks will succeed
1903      // for out-of-process plugins.
1904      WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1905      if (!LockMouse())
1906        lock_mouse_callback_->Run(PP_ERROR_FAILED);
1907    }
1908  }
1909
1910  if (PluginHasFocus() != old_plugin_focus)
1911    SendFocusChangeNotification();
1912}
1913
1914bool PepperPluginInstanceImpl::IsViewAccelerated() {
1915  if (!container_)
1916    return false;
1917
1918  WebDocument document = container_->element().document();
1919  WebLocalFrame* frame = document.frame();
1920  if (!frame)
1921    return false;
1922  WebView* view = frame->view();
1923  if (!view)
1924    return false;
1925
1926  return view->isAcceleratedCompositingActive();
1927}
1928
1929bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1930                                              blink::WebCanvas* canvas) {
1931#if defined(ENABLE_FULL_PRINTING)
1932  ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1933  if (enter.failed())
1934    return false;
1935
1936  BufferAutoMapper mapper(enter.object());
1937  if (!mapper.data() || !mapper.size()) {
1938    NOTREACHED();
1939    return false;
1940  }
1941#if defined(OS_WIN)
1942  // For Windows, we need the PDF DLL to render the output PDF to a DC.
1943  HMODULE pdf_module = GetModuleHandle(L"pdf.dll");
1944  if (!pdf_module)
1945    return false;
1946  RenderPDFPageToDCProc render_proc = reinterpret_cast<RenderPDFPageToDCProc>(
1947      GetProcAddress(pdf_module, "RenderPDFPageToDC"));
1948  if (!render_proc)
1949    return false;
1950#endif  // defined(OS_WIN)
1951
1952  bool ret = false;
1953#if defined(OS_POSIX) && !defined(OS_ANDROID)
1954  // On Linux we just set the final bits in the native metafile
1955  // (NativeMetafile and PreviewMetafile must have compatible formats,
1956  // i.e. both PDF for this to work).
1957  printing::Metafile* metafile =
1958      printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1959  DCHECK(metafile != NULL);
1960  if (metafile)
1961    ret = metafile->InitFromData(mapper.data(), mapper.size());
1962#elif defined(OS_WIN)
1963  printing::Metafile* metafile =
1964      printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1965  if (metafile) {
1966    // We only have a metafile when doing print preview, so we just want to
1967    // pass the PDF off to preview.
1968    ret = metafile->InitFromData(mapper.data(), mapper.size());
1969  } else {
1970    // On Windows, we now need to render the PDF to the DC that backs the
1971    // supplied canvas.
1972    HDC dc = skia::BeginPlatformPaint(canvas);
1973    DrawEmptyRectangle(dc);
1974    gfx::Size size_in_pixels;
1975    size_in_pixels.set_width(
1976        printing::ConvertUnit(current_print_settings_.printable_area.size.width,
1977                              static_cast<int>(printing::kPointsPerInch),
1978                              current_print_settings_.dpi));
1979    size_in_pixels.set_height(printing::ConvertUnit(
1980        current_print_settings_.printable_area.size.height,
1981        static_cast<int>(printing::kPointsPerInch),
1982        current_print_settings_.dpi));
1983    // We need to scale down DC to fit an entire page into DC available area.
1984    // First, we'll try to use default scaling based on the 72dpi that is
1985    // used in webkit for printing.
1986    // If default scaling is not enough to fit the entire PDF without
1987    // Current metafile is based on screen DC and have current screen size.
1988    // Writing outside of those boundaries will result in the cut-off output.
1989    // On metafiles (this is the case here), scaling down will still record
1990    // original coordinates and we'll be able to print in full resolution.
1991    // Before playback we'll need to counter the scaling up that will happen
1992    // in the browser (printed_document_win.cc).
1993    double dynamic_scale = gfx::CalculatePageScale(
1994        dc, size_in_pixels.width(), size_in_pixels.height());
1995    double page_scale = static_cast<double>(printing::kPointsPerInch) /
1996                        static_cast<double>(current_print_settings_.dpi);
1997
1998    if (dynamic_scale < page_scale) {
1999      page_scale = dynamic_scale;
2000      printing::MetafileSkiaWrapper::SetCustomScaleOnCanvas(*canvas,
2001                                                            page_scale);
2002    }
2003
2004    gfx::ScaleDC(dc, page_scale);
2005
2006    ret = render_proc(static_cast<unsigned char*>(mapper.data()),
2007                      mapper.size(),
2008                      0,
2009                      dc,
2010                      current_print_settings_.dpi,
2011                      current_print_settings_.dpi,
2012                      0,
2013                      0,
2014                      size_in_pixels.width(),
2015                      size_in_pixels.height(),
2016                      true,
2017                      false,
2018                      true,
2019                      true,
2020                      true);
2021    skia::EndPlatformPaint(canvas);
2022  }
2023#endif  // defined(OS_WIN)
2024
2025  return ret;
2026#else  // defined(ENABLE_FULL_PRINTING)
2027  return false;
2028#endif
2029}
2030
2031void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
2032  if (!container_)
2033    return;
2034
2035  gpu::Mailbox mailbox;
2036  uint32 sync_point = 0;
2037  if (bound_graphics_3d_.get()) {
2038    bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
2039    DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
2040  }
2041  bool want_3d_layer = !mailbox.IsZero();
2042  bool want_2d_layer = !!bound_graphics_2d_platform_;
2043  bool want_texture_layer = want_3d_layer || want_2d_layer;
2044  bool want_compositor_layer = !!bound_compositor_;
2045
2046  if (!device_changed &&
2047      (want_texture_layer == !!texture_layer_.get()) &&
2048      (want_3d_layer == layer_is_hardware_) &&
2049      (want_compositor_layer == !!compositor_layer_) &&
2050      layer_bound_to_fullscreen_ == !!fullscreen_container_) {
2051    UpdateLayerTransform();
2052    return;
2053  }
2054
2055  if (texture_layer_ || compositor_layer_) {
2056    if (!layer_bound_to_fullscreen_)
2057      container_->setWebLayer(NULL);
2058    else if (fullscreen_container_)
2059      fullscreen_container_->SetLayer(NULL);
2060    web_layer_.reset();
2061    texture_layer_ = NULL;
2062    compositor_layer_ = NULL;
2063  }
2064
2065  if (want_texture_layer) {
2066    bool opaque = false;
2067    if (want_3d_layer) {
2068      DCHECK(bound_graphics_3d_.get());
2069      texture_layer_ = cc::TextureLayer::CreateForMailbox(NULL);
2070      opaque = bound_graphics_3d_->IsOpaque();
2071      texture_layer_->SetTextureMailboxWithoutReleaseCallback(
2072          cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
2073    } else {
2074      DCHECK(bound_graphics_2d_platform_);
2075      texture_layer_ = cc::TextureLayer::CreateForMailbox(this);
2076      bound_graphics_2d_platform_->AttachedToNewLayer();
2077      opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2078      texture_layer_->SetFlipped(false);
2079    }
2080
2081    // Ignore transparency in fullscreen, since that's what Flash always
2082    // wants to do, and that lets it not recreate a context if
2083    // wmode=transparent was specified.
2084    opaque = opaque || fullscreen_container_;
2085    texture_layer_->SetContentsOpaque(opaque);
2086    web_layer_.reset(new WebLayerImpl(texture_layer_));
2087  } else if (want_compositor_layer) {
2088    compositor_layer_ = bound_compositor_->layer();
2089    web_layer_.reset(new WebLayerImpl(compositor_layer_));
2090  }
2091
2092  if (web_layer_) {
2093    if (fullscreen_container_) {
2094      fullscreen_container_->SetLayer(web_layer_.get());
2095    } else {
2096      container_->setWebLayer(web_layer_.get());
2097    }
2098  }
2099
2100  layer_bound_to_fullscreen_ = !!fullscreen_container_;
2101  layer_is_hardware_ = want_3d_layer;
2102  UpdateLayerTransform();
2103}
2104
2105bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2106    cc::TextureMailbox* mailbox,
2107    scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2108    bool use_shared_memory) {
2109  if (!bound_graphics_2d_platform_)
2110    return false;
2111  return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2112                                                            release_callback);
2113}
2114
2115void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2116
2117void PepperPluginInstanceImpl::AddLatencyInfo(
2118    const std::vector<ui::LatencyInfo>& latency_info) {
2119  if (render_frame_ && render_frame_->GetRenderWidget()) {
2120    RenderWidgetCompositor* compositor =
2121        render_frame_->GetRenderWidget()->compositor();
2122    if (compositor) {
2123      for (size_t i = 0; i < latency_info.size(); i++) {
2124        scoped_ptr<cc::SwapPromise> swap_promise(
2125            new cc::LatencyInfoSwapPromise(latency_info[i]));
2126        compositor->QueueSwapPromise(swap_promise.Pass());
2127      }
2128    }
2129  }
2130}
2131
2132void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2133  DCHECK(live_plugin_objects_.find(plugin_object) ==
2134         live_plugin_objects_.end());
2135  live_plugin_objects_.insert(plugin_object);
2136}
2137
2138void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2139  // Don't actually verify that the object is in the set since during module
2140  // deletion we'll be in the process of freeing them.
2141  live_plugin_objects_.erase(plugin_object);
2142}
2143
2144bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2145  PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2146  // Give a lot of slack so tests won't be flaky.
2147  const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2148  return pending_user_gesture_token_.hasGestures() &&
2149         (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2150}
2151
2152WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2153  if (!IsProcessingUserGesture())
2154    pending_user_gesture_token_ = WebUserGestureToken();
2155  return pending_user_gesture_token_;
2156}
2157
2158void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2159  if (TrackedCallback::IsPending(lock_mouse_callback_))
2160    lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2161}
2162
2163void PepperPluginInstanceImpl::OnMouseLockLost() {
2164  if (LoadMouseLockInterface())
2165    plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2166}
2167
2168void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2169    const blink::WebMouseEvent& event) {
2170  // |cursor_info| is ignored since it is hidden when the mouse is locked.
2171  blink::WebCursorInfo cursor_info;
2172  HandleInputEvent(event, &cursor_info);
2173}
2174
2175void PepperPluginInstanceImpl::SimulateInputEvent(
2176    const InputEventData& input_event) {
2177  WebView* web_view = container()->element().document().frame()->view();
2178  if (!web_view) {
2179    NOTREACHED();
2180    return;
2181  }
2182
2183  bool handled = SimulateIMEEvent(input_event);
2184  if (handled)
2185    return;
2186
2187  std::vector<linked_ptr<WebInputEvent> > events =
2188      CreateSimulatedWebInputEvents(
2189          input_event,
2190          view_data_.rect.point.x + view_data_.rect.size.width / 2,
2191          view_data_.rect.point.y + view_data_.rect.size.height / 2);
2192  for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2193       it != events.end();
2194       ++it) {
2195    web_view->handleInputEvent(*it->get());
2196  }
2197}
2198
2199bool PepperPluginInstanceImpl::SimulateIMEEvent(
2200    const InputEventData& input_event) {
2201  switch (input_event.event_type) {
2202    case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2203    case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2204      SimulateImeSetCompositionEvent(input_event);
2205      break;
2206    case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2207      DCHECK(input_event.character_text.empty());
2208      SimulateImeSetCompositionEvent(input_event);
2209      break;
2210    case PP_INPUTEVENT_TYPE_IME_TEXT:
2211      if (!render_frame_)
2212        return false;
2213      render_frame_->SimulateImeConfirmComposition(
2214          base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2215      break;
2216    default:
2217      return false;
2218  }
2219  return true;
2220}
2221
2222void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2223    const InputEventData& input_event) {
2224  if (!render_frame_)
2225    return;
2226
2227  std::vector<size_t> offsets;
2228  offsets.push_back(input_event.composition_selection_start);
2229  offsets.push_back(input_event.composition_selection_end);
2230  offsets.insert(offsets.end(),
2231                 input_event.composition_segment_offsets.begin(),
2232                 input_event.composition_segment_offsets.end());
2233
2234  base::string16 utf16_text =
2235      base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2236
2237  std::vector<blink::WebCompositionUnderline> underlines;
2238  for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2239    blink::WebCompositionUnderline underline;
2240    underline.startOffset = offsets[i];
2241    underline.endOffset = offsets[i + 1];
2242    if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2243      underline.thick = true;
2244    underlines.push_back(underline);
2245  }
2246
2247  render_frame_->SimulateImeSetComposition(
2248      utf16_text, underlines, offsets[0], offsets[1]);
2249}
2250
2251ContentDecryptorDelegate*
2252PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2253  if (content_decryptor_delegate_)
2254    return content_decryptor_delegate_.get();
2255
2256  const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2257      static_cast<const PPP_ContentDecryptor_Private*>(
2258          module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2259  if (!plugin_decryption_interface)
2260    return NULL;
2261
2262  content_decryptor_delegate_.reset(
2263      new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2264  return content_decryptor_delegate_.get();
2265}
2266
2267PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2268                                               PP_Resource device) {
2269  TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2270  // The Graphics3D instance can't be destroyed until we call
2271  // UpdateLayer().
2272  scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2273  if (bound_graphics_3d_.get()) {
2274    bound_graphics_3d_->BindToInstance(false);
2275    bound_graphics_3d_ = NULL;
2276  }
2277  if (bound_graphics_2d_platform_) {
2278    bound_graphics_2d_platform_->BindToInstance(NULL);
2279    bound_graphics_2d_platform_ = NULL;
2280  }
2281  if (bound_compositor_) {
2282    bound_compositor_->BindToInstance(NULL);
2283    bound_compositor_ = NULL;
2284  }
2285
2286  // Special-case clearing the current device.
2287  if (!device) {
2288    UpdateLayer(true);
2289    InvalidateRect(gfx::Rect());
2290    return PP_TRUE;
2291  }
2292
2293  // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2294  // to/from fullscreen with PPB_Fullscreen.
2295  if ((fullscreen_container_ && !flash_fullscreen_) ||
2296      desired_fullscreen_state_ != view_data_.is_fullscreen)
2297    return PP_FALSE;
2298
2299  const ppapi::host::PpapiHost* ppapi_host =
2300      RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2301  ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2302  PepperGraphics2DHost* graphics_2d = NULL;
2303  PepperCompositorHost* compositor = NULL;
2304  if (host) {
2305    if (host->IsGraphics2DHost()) {
2306      graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2307    } else if (host->IsCompositorHost()) {
2308      compositor = static_cast<PepperCompositorHost*>(host);
2309    } else {
2310      DLOG(ERROR) <<
2311          "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2312    }
2313  }
2314
2315  EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2316  PPB_Graphics3D_Impl* graphics_3d =
2317      enter_3d.succeeded()
2318          ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2319          : NULL;
2320
2321  if (compositor) {
2322    if (compositor->BindToInstance(this)) {
2323      bound_compositor_ = compositor;
2324      UpdateLayer(true);
2325      return PP_TRUE;
2326    }
2327  } else if (graphics_2d) {
2328    if (graphics_2d->BindToInstance(this)) {
2329      bound_graphics_2d_platform_ = graphics_2d;
2330      UpdateLayer(true);
2331      return PP_TRUE;
2332    }
2333  } else if (graphics_3d) {
2334    // Make sure graphics can only be bound to the instance it is
2335    // associated with.
2336    if (graphics_3d->pp_instance() == pp_instance() &&
2337        graphics_3d->BindToInstance(true)) {
2338      bound_graphics_3d_ = graphics_3d;
2339      UpdateLayer(true);
2340      return PP_TRUE;
2341    }
2342  }
2343
2344  // The instance cannot be bound or the device is not a valid resource type.
2345  return PP_FALSE;
2346}
2347
2348PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2349  return PP_FromBool(full_frame());
2350}
2351
2352const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2353  return &view_data_;
2354}
2355
2356PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2357  return PP_FromBool(flash_fullscreen_);
2358}
2359
2360PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2361  if (!container_)
2362    return PP_MakeUndefined();
2363
2364  WebLocalFrame* frame = container_->element().document().frame();
2365  if (!frame)
2366    return PP_MakeUndefined();
2367
2368  return NPObjectToPPVar(this, frame->windowObject());
2369}
2370
2371PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2372  if (!container_)
2373    return PP_MakeUndefined();
2374  return NPObjectToPPVar(this, container_->scriptableObjectForElement());
2375}
2376
2377PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2378                                               PP_Var script,
2379                                               PP_Var* exception) {
2380  // Executing the script may remove the plugin from the DOM, so we need to keep
2381  // a reference to ourselves so that we can still process the result after the
2382  // WebBindings::evaluate() below.
2383  scoped_refptr<PepperPluginInstanceImpl> ref(this);
2384  TryCatch try_catch(exception);
2385  if (try_catch.has_exception())
2386    return PP_MakeUndefined();
2387
2388  // Convert the script into an inconvenient NPString object.
2389  StringVar* script_string = StringVar::FromPPVar(script);
2390  if (!script_string) {
2391    try_catch.SetException("Script param to ExecuteScript must be a string.");
2392    return PP_MakeUndefined();
2393  }
2394  NPString np_script;
2395  np_script.UTF8Characters = script_string->value().c_str();
2396  np_script.UTF8Length = script_string->value().length();
2397
2398  // Get the current frame to pass to the evaluate function.
2399  WebLocalFrame* frame = NULL;
2400  if (container_)
2401    frame = container_->element().document().frame();
2402  if (!frame || !frame->windowObject()) {
2403    try_catch.SetException("No context in which to execute script.");
2404    return PP_MakeUndefined();
2405  }
2406
2407  NPVariant result;
2408  bool ok = false;
2409  if (IsProcessingUserGesture()) {
2410    blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2411    ok =
2412        WebBindings::evaluate(NULL, frame->windowObject(), &np_script, &result);
2413  } else {
2414    ok =
2415        WebBindings::evaluate(NULL, frame->windowObject(), &np_script, &result);
2416  }
2417  if (!ok) {
2418    // TryCatch doesn't catch the exceptions properly. Since this is only for
2419    // a trusted API, just set to a general exception message.
2420    try_catch.SetException("Exception caught");
2421    WebBindings::releaseVariantValue(&result);
2422    return PP_MakeUndefined();
2423  }
2424
2425  PP_Var ret = NPVariantToPPVar(this, &result);
2426  WebBindings::releaseVariantValue(&result);
2427  return ret;
2428}
2429
2430uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2431    PP_Instance instance) {
2432  RenderThreadImpl* thread = RenderThreadImpl::current();
2433  return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2434}
2435
2436uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2437    PP_Instance instance) {
2438  RenderThreadImpl* thread = RenderThreadImpl::current();
2439  return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2440}
2441
2442PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2443  if (!render_frame_)
2444    return PP_MakeUndefined();
2445  return StringVar::StringToPPVar(
2446      render_frame_->render_view()->webkit_preferences().default_encoding);
2447}
2448
2449// These PPB_ContentDecryptor_Private calls are responses to
2450// PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2451// Therefore, |content_decryptor_delegate_| must have been initialized when
2452// the following methods are called.
2453void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2454                                               uint32 promise_id) {
2455  content_decryptor_delegate_->OnPromiseResolved(promise_id);
2456}
2457
2458void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2459    PP_Instance instance,
2460    uint32 promise_id,
2461    PP_Var web_session_id_var) {
2462  content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2463                                                            web_session_id_var);
2464}
2465
2466void PepperPluginInstanceImpl::PromiseRejected(
2467    PP_Instance instance,
2468    uint32 promise_id,
2469    PP_CdmExceptionCode exception_code,
2470    uint32 system_code,
2471    PP_Var error_description_var) {
2472  content_decryptor_delegate_->OnPromiseRejected(
2473      promise_id, exception_code, system_code, error_description_var);
2474}
2475
2476void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2477                                              PP_Var web_session_id_var,
2478                                              PP_Var message_var,
2479                                              PP_Var destination_url_var) {
2480  content_decryptor_delegate_->OnSessionMessage(
2481      web_session_id_var, message_var, destination_url_var);
2482}
2483
2484void PepperPluginInstanceImpl::SessionReady(PP_Instance instance,
2485                                            PP_Var web_session_id_var) {
2486  content_decryptor_delegate_->OnSessionReady(web_session_id_var);
2487}
2488
2489void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2490                                             PP_Var web_session_id_var) {
2491  content_decryptor_delegate_->OnSessionClosed(web_session_id_var);
2492}
2493
2494void PepperPluginInstanceImpl::SessionError(PP_Instance instance,
2495                                            PP_Var web_session_id_var,
2496                                            PP_CdmExceptionCode exception_code,
2497                                            uint32 system_code,
2498                                            PP_Var error_description_var) {
2499  content_decryptor_delegate_->OnSessionError(
2500      web_session_id_var, exception_code, system_code, error_description_var);
2501}
2502
2503void PepperPluginInstanceImpl::DeliverBlock(
2504    PP_Instance instance,
2505    PP_Resource decrypted_block,
2506    const PP_DecryptedBlockInfo* block_info) {
2507  content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2508}
2509
2510void PepperPluginInstanceImpl::DecoderInitializeDone(
2511    PP_Instance instance,
2512    PP_DecryptorStreamType decoder_type,
2513    uint32_t request_id,
2514    PP_Bool success) {
2515  content_decryptor_delegate_->DecoderInitializeDone(
2516      decoder_type, request_id, success);
2517}
2518
2519void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2520    PP_Instance instance,
2521    PP_DecryptorStreamType decoder_type,
2522    uint32_t request_id) {
2523  content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2524                                                       request_id);
2525}
2526
2527void PepperPluginInstanceImpl::DecoderResetDone(
2528    PP_Instance instance,
2529    PP_DecryptorStreamType decoder_type,
2530    uint32_t request_id) {
2531  content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2532}
2533
2534void PepperPluginInstanceImpl::DeliverFrame(
2535    PP_Instance instance,
2536    PP_Resource decrypted_frame,
2537    const PP_DecryptedFrameInfo* frame_info) {
2538  content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2539}
2540
2541void PepperPluginInstanceImpl::DeliverSamples(
2542    PP_Instance instance,
2543    PP_Resource audio_frames,
2544    const PP_DecryptedSampleInfo* sample_info) {
2545  content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2546}
2547
2548void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2549    PP_Instance instance) {
2550  if (!LoadFindInterface())
2551    return;
2552  bool is_main_frame =
2553      render_frame_ &&
2554      render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2555  if (!is_main_frame)
2556    return;
2557  render_frame_->render_view()->set_plugin_find_handler(this);
2558}
2559
2560void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2561    PP_Instance instance,
2562    int32_t total,
2563    PP_Bool final_result) {
2564  DCHECK_NE(find_identifier_, -1);
2565  if (render_frame_) {
2566    render_frame_->reportFindInPageMatchCount(
2567        find_identifier_, total, PP_ToBool(final_result));
2568  }
2569}
2570
2571void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2572                                                         int32_t index) {
2573  DCHECK_NE(find_identifier_, -1);
2574  if (render_frame_) {
2575    render_frame_->reportFindInPageSelection(
2576        find_identifier_, index + 1, blink::WebRect());
2577  }
2578}
2579
2580void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2581                                            const PP_Rect* tickmarks,
2582                                            uint32_t count) {
2583  if (!render_frame_ || !render_frame_->GetWebFrame())
2584    return;
2585
2586  blink::WebVector<blink::WebRect> tickmarks_converted(
2587      static_cast<size_t>(count));
2588  for (uint32 i = 0; i < count; ++i) {
2589    tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2590                                            tickmarks[i].point.y,
2591                                            tickmarks[i].size.width,
2592                                            tickmarks[i].size.height);
2593    ;
2594  }
2595  blink::WebFrame* frame = render_frame_->GetWebFrame();
2596  frame->setTickmarks(tickmarks_converted);
2597}
2598
2599PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2600  return PP_FromBool(view_data_.is_fullscreen);
2601}
2602
2603PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2604                                                PP_Bool fullscreen) {
2605  return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2606}
2607
2608PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2609                                                PP_Size* size) {
2610  blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2611  *size = PP_MakeSize(info.rect.width, info.rect.height);
2612  return PP_TRUE;
2613}
2614
2615ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2616    PP_Instance instance,
2617    ppapi::SingletonResourceID id) {
2618  // Flash APIs and some others aren't implemented in-process.
2619  switch (id) {
2620    case ppapi::BROKER_SINGLETON_ID:
2621    case ppapi::BROWSER_FONT_SINGLETON_ID:
2622    case ppapi::FILE_MAPPING_SINGLETON_ID:
2623    case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2624    case ppapi::FLASH_FILE_SINGLETON_ID:
2625    case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2626    case ppapi::FLASH_SINGLETON_ID:
2627    case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2628    case ppapi::NETWORK_PROXY_SINGLETON_ID:
2629    case ppapi::PDF_SINGLETON_ID:
2630    case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2631      NOTIMPLEMENTED();
2632      return NULL;
2633    case ppapi::GAMEPAD_SINGLETON_ID:
2634      return gamepad_impl_.get();
2635    case ppapi::UMA_SINGLETON_ID: {
2636      if (!uma_private_impl_) {
2637        RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2638        if (host_impl->in_process_router()) {
2639          uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2640              host_impl->in_process_router()->GetPluginConnection(instance),
2641              instance);
2642        }
2643      }
2644      return uma_private_impl_.get();
2645    }
2646  }
2647
2648  NOTREACHED();
2649  return NULL;
2650}
2651
2652int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2653                                                     uint32_t event_classes) {
2654  input_event_mask_ |= event_classes;
2655  filtered_input_event_mask_ &= ~(event_classes);
2656  RequestInputEventsHelper(event_classes);
2657  return ValidateRequestInputEvents(false, event_classes);
2658}
2659
2660int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2661    PP_Instance instance,
2662    uint32_t event_classes) {
2663  filtered_input_event_mask_ |= event_classes;
2664  input_event_mask_ &= ~(event_classes);
2665  RequestInputEventsHelper(event_classes);
2666  return ValidateRequestInputEvents(true, event_classes);
2667}
2668
2669void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2670                                                      uint32_t event_classes) {
2671  input_event_mask_ &= ~(event_classes);
2672  filtered_input_event_mask_ &= ~(event_classes);
2673  RequestInputEventsHelper(event_classes);
2674}
2675
2676void PepperPluginInstanceImpl::StartTrackingLatency(PP_Instance instance) {
2677  if (module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
2678    is_tracking_latency_ = true;
2679}
2680
2681void PepperPluginInstanceImpl::ZoomChanged(PP_Instance instance,
2682                                           double factor) {
2683  // We only want to tell the page to change its zoom if the whole page is the
2684  // plugin.  If we're in an iframe, then don't do anything.
2685  if (!IsFullPagePlugin())
2686    return;
2687  container()->zoomLevelChanged(content::ZoomFactorToZoomLevel(factor));
2688}
2689
2690void PepperPluginInstanceImpl::ZoomLimitsChanged(PP_Instance instance,
2691                                                 double minimum_factor,
2692                                                 double maximum_factor) {
2693  if (!render_frame_)
2694    return;
2695  if (minimum_factor > maximum_factor) {
2696    NOTREACHED();
2697    return;
2698  }
2699  double minimum_level = ZoomFactorToZoomLevel(minimum_factor);
2700  double maximum_level = ZoomFactorToZoomLevel(maximum_factor);
2701  render_frame_->render_view()->webview()->zoomLimitsChanged(minimum_level,
2702                                                             maximum_level);
2703}
2704
2705void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2706                                           PP_Var message) {
2707  PostMessageToJavaScript(message);
2708}
2709
2710PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2711                                            PP_MouseCursor_Type type,
2712                                            PP_Resource image,
2713                                            const PP_Point* hot_spot) {
2714  if (!ValidateSetCursorParams(type, image, hot_spot))
2715    return PP_FALSE;
2716
2717  if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2718    DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2719    return PP_TRUE;
2720  }
2721
2722  EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2723  if (enter.failed())
2724    return PP_FALSE;
2725  PPB_ImageData_Impl* image_data =
2726      static_cast<PPB_ImageData_Impl*>(enter.object());
2727
2728  ImageDataAutoMapper auto_mapper(image_data);
2729  if (!auto_mapper.is_valid())
2730    return PP_FALSE;
2731
2732  scoped_ptr<WebCursorInfo> custom_cursor(
2733      new WebCursorInfo(WebCursorInfo::TypeCustom));
2734  custom_cursor->hotSpot.x = hot_spot->x;
2735  custom_cursor->hotSpot.y = hot_spot->y;
2736
2737  const SkBitmap* bitmap = image_data->GetMappedBitmap();
2738  // Make a deep copy, so that the cursor remains valid even after the original
2739  // image data gets freed.
2740  if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2741    return PP_FALSE;
2742  }
2743
2744  DoSetCursor(custom_cursor.release());
2745  return PP_TRUE;
2746}
2747
2748int32_t PepperPluginInstanceImpl::LockMouse(
2749    PP_Instance instance,
2750    scoped_refptr<TrackedCallback> callback) {
2751  if (TrackedCallback::IsPending(lock_mouse_callback_))
2752    return PP_ERROR_INPROGRESS;
2753
2754  if (IsMouseLocked())
2755    return PP_OK;
2756
2757  if (!CanAccessMainFrame())
2758    return PP_ERROR_NOACCESS;
2759
2760  if (!IsProcessingUserGesture())
2761    return PP_ERROR_NO_USER_GESTURE;
2762
2763  // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2764  // we wait and call LockMouse() in UpdateFlashFullscreenState().
2765  if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2766    // Open a user gesture here so the Webkit user gesture checks will succeed
2767    // for out-of-process plugins.
2768    WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2769    if (!LockMouse())
2770      return PP_ERROR_FAILED;
2771  }
2772
2773  // Either mouselock succeeded or a Flash fullscreen is pending.
2774  lock_mouse_callback_ = callback;
2775  return PP_OK_COMPLETIONPENDING;
2776}
2777
2778void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2779  GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2780}
2781
2782void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2783                                                PP_TextInput_Type type) {
2784  if (!render_frame_)
2785    return;
2786  int itype = type;
2787  if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2788    itype = ui::TEXT_INPUT_TYPE_NONE;
2789  SetTextInputType(static_cast<ui::TextInputType>(itype));
2790}
2791
2792void PepperPluginInstanceImpl::UpdateCaretPosition(
2793    PP_Instance instance,
2794    const PP_Rect& caret,
2795    const PP_Rect& bounding_box) {
2796  if (!render_frame_)
2797    return;
2798  text_input_caret_ = PP_ToGfxRect(caret);
2799  text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2800  text_input_caret_set_ = true;
2801  render_frame_->PepperCaretPositionChanged(this);
2802}
2803
2804void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2805  if (render_frame_)
2806    render_frame_->PepperCancelComposition(this);
2807}
2808
2809void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2810  // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2811  // It can be optimized so that it won't call it back until the information
2812  // is really needed.
2813
2814  // Avoid calling in nested context or else this will reenter the plugin. This
2815  // uses a weak pointer rather than exploiting the fact that this class is
2816  // refcounted because we don't actually want this operation to affect the
2817  // lifetime of the instance.
2818  base::MessageLoop::current()->PostTask(
2819      FROM_HERE,
2820      base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2821                 weak_factory_.GetWeakPtr(),
2822                 static_cast<size_t>(kExtraCharsForTextInput)));
2823}
2824
2825void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2826                                                     const char* text,
2827                                                     uint32_t caret,
2828                                                     uint32_t anchor) {
2829  if (!render_frame_)
2830    return;
2831  surrounding_text_ = text;
2832  selection_caret_ = caret;
2833  selection_anchor_ = anchor;
2834  render_frame_->PepperSelectionChanged(this);
2835}
2836
2837PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2838    PP_Instance instance,
2839    PP_Var relative,
2840    PP_URLComponents_Dev* components) {
2841  StringVar* relative_string = StringVar::FromPPVar(relative);
2842  if (!relative_string)
2843    return PP_MakeNull();
2844
2845  WebElement plugin_element = container()->element();
2846  GURL document_url = plugin_element.document().baseURL();
2847  return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2848      document_url.Resolve(relative_string->value()), components);
2849}
2850
2851PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2852                                                     PP_Var url) {
2853  StringVar* url_string = StringVar::FromPPVar(url);
2854  if (!url_string)
2855    return PP_FALSE;
2856
2857  blink::WebSecurityOrigin security_origin;
2858  if (!SecurityOriginForInstance(instance, &security_origin))
2859    return PP_FALSE;
2860
2861  GURL gurl(url_string->value());
2862  if (!gurl.is_valid())
2863    return PP_FALSE;
2864
2865  return PP_FromBool(security_origin.canRequest(gurl));
2866}
2867
2868PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2869    PP_Instance instance,
2870    PP_Instance target) {
2871  blink::WebSecurityOrigin our_origin;
2872  if (!SecurityOriginForInstance(instance, &our_origin))
2873    return PP_FALSE;
2874
2875  blink::WebSecurityOrigin target_origin;
2876  if (!SecurityOriginForInstance(instance, &target_origin))
2877    return PP_FALSE;
2878
2879  return PP_FromBool(our_origin.canAccess(target_origin));
2880}
2881
2882PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2883    PP_Instance instance,
2884    PP_URLComponents_Dev* components) {
2885  blink::WebDocument document = container()->element().document();
2886  return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2887                                                      components);
2888}
2889
2890PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2891    PP_Instance instance,
2892    PP_URLComponents_Dev* components) {
2893  return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2894}
2895
2896PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2897    PP_Instance instance,
2898    PP_URLComponents_Dev* components) {
2899  blink::WebDocument document = container()->element().document();
2900  if (!full_frame_)
2901    return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2902                                                        components);
2903  WebLocalFrame* frame = document.frame();
2904  if (!frame)
2905    return PP_MakeUndefined();
2906  const WebURLRequest& request = frame->dataSource()->originalRequest();
2907  WebString referer = request.httpHeaderField("Referer");
2908  if (referer.isEmpty())
2909    return PP_MakeUndefined();
2910  return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2911                                                      components);
2912}
2913
2914PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2915    scoped_refptr<PluginModule> module) {
2916  // Save the original module and switch over to the new one now that this
2917  // plugin is using the IPC-based proxy.
2918  original_module_ = module_;
2919  module_ = module;
2920
2921  // For NaCl instances, remember the NaCl plugin instance interface, so we
2922  // can shut it down by calling its DidDestroy in our Delete() method.
2923  original_instance_interface_.reset(instance_interface_.release());
2924
2925  base::Callback<const void*(const char*)> get_plugin_interface_func =
2926      base::Bind(&PluginModule::GetPluginInterface, module_.get());
2927  PPP_Instance_Combined* ppp_instance_combined =
2928      PPP_Instance_Combined::Create(get_plugin_interface_func);
2929  if (!ppp_instance_combined) {
2930    // The proxy must support at least one usable PPP_Instance interface.
2931    // While this could be a failure to implement the interface in the NaCl
2932    // module, it is more likely that the NaCl process has crashed. Either
2933    // way, report that module initialization failed.
2934    return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2935  }
2936
2937  instance_interface_.reset(ppp_instance_combined);
2938  // Clear all PPP interfaces we may have cached.
2939  plugin_find_interface_ = NULL;
2940  plugin_input_event_interface_ = NULL;
2941  checked_for_plugin_input_event_interface_ = false;
2942  plugin_mouse_lock_interface_ = NULL;
2943  plugin_pdf_interface_ = NULL;
2944  checked_for_plugin_pdf_interface_ = false;
2945  plugin_private_interface_ = NULL;
2946  plugin_selection_interface_ = NULL;
2947  plugin_textinput_interface_ = NULL;
2948  plugin_zoom_interface_ = NULL;
2949
2950  // Re-send the DidCreate event via the proxy.
2951  scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2952  scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2953  if (!instance_interface_->DidCreate(
2954          pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2955    return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2956  message_channel_->Start();
2957
2958  // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2959  // event. This way, SendDidChangeView will send the "current" view
2960  // immediately (before other events like HandleDocumentLoad).
2961  sent_initial_did_change_view_ = false;
2962  view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2963  SendDidChangeView();
2964
2965  DCHECK(external_document_load_);
2966  external_document_load_ = false;
2967  if (!external_document_response_.isNull()) {
2968    document_loader_ = NULL;
2969    // Pass the response to the new proxy.
2970    HandleDocumentLoad(external_document_response_);
2971    external_document_response_ = blink::WebURLResponse();
2972    // Replay any document load events we've received to the real loader.
2973    external_document_loader_->ReplayReceivedData(document_loader_);
2974    external_document_loader_.reset(NULL);
2975  }
2976
2977  return PP_EXTERNAL_PLUGIN_OK;
2978}
2979
2980bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2981  DCHECK(module);
2982  return module == module_.get() || module == original_module_.get();
2983}
2984
2985NPP PepperPluginInstanceImpl::instanceNPP() { return npp_.get(); }
2986
2987PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2988  return HostGlobals::Get()->GetInstance(instance_id);
2989}
2990
2991RenderView* PepperPluginInstanceImpl::GetRenderView() {
2992  return render_frame_ ? render_frame_->render_view() : NULL;
2993}
2994
2995blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2996  return container_;
2997}
2998
2999v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
3000
3001ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
3002  return HostGlobals::Get()->GetVarTracker();
3003}
3004
3005const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
3006
3007base::FilePath PepperPluginInstanceImpl::GetModulePath() {
3008  return module_->path();
3009}
3010
3011PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
3012                                                  float scale) {
3013  gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
3014
3015  if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
3016    return 0;
3017
3018  scoped_refptr<PPB_ImageData_Impl> image_data(
3019      new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
3020  if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
3021                        image_skia_rep.pixel_width(),
3022                        image_skia_rep.pixel_height(),
3023                        false)) {
3024    return 0;
3025  }
3026
3027  ImageDataAutoMapper mapper(image_data.get());
3028  if (!mapper.is_valid())
3029    return 0;
3030
3031  skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
3032  // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
3033  // ignore the allocated pixels in shared memory and re-allocate a new buffer.
3034  canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
3035
3036  return image_data->GetReference();
3037}
3038
3039PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
3040    const base::FilePath& file_path,
3041    ppapi::PpapiPermissions permissions,
3042    const IPC::ChannelHandle& channel_handle,
3043    base::ProcessId plugin_pid,
3044    int plugin_child_id) {
3045  // Create a new module for each instance of the external plugin that is using
3046  // the IPC based out-of-process proxy. We can't use the existing module,
3047  // because it is configured for the in-process plugin, and we must keep it
3048  // that way to allow the page to create other instances.
3049  scoped_refptr<PluginModule> external_plugin_module(
3050      module_->CreateModuleForExternalPluginInstance());
3051
3052  RendererPpapiHostImpl* renderer_ppapi_host =
3053      external_plugin_module->CreateOutOfProcessModule(render_frame_,
3054                                                       file_path,
3055                                                       permissions,
3056                                                       channel_handle,
3057                                                       plugin_pid,
3058                                                       plugin_child_id,
3059                                                       true);
3060  if (!renderer_ppapi_host) {
3061    DLOG(ERROR) << "CreateExternalPluginModule() failed";
3062    return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
3063  }
3064
3065  // Finally, switch the instance to the proxy.
3066  return external_plugin_module->InitAsProxiedExternalPlugin(this);
3067}
3068
3069void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3070  always_on_top_ = on_top;
3071}
3072
3073void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
3074  cursor_.reset(cursor);
3075  if (fullscreen_container_) {
3076    fullscreen_container_->DidChangeCursor(*cursor);
3077  } else if (render_frame_) {
3078    render_frame_->PepperDidChangeCursor(this, *cursor);
3079  }
3080}
3081
3082bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3083  WebLocalFrame* frame = container()->element().document().frame();
3084  return frame->view()->mainFrame()->document().isPluginDocument();
3085}
3086
3087bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3088                                                  bool delay_report) {
3089  TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3090  // Keep a reference on the stack. See NOTE above.
3091  scoped_refptr<PepperPluginInstanceImpl> ref(this);
3092
3093  // We check whether we are trying to switch to the state we're already going
3094  // to (i.e. if we're already switching to fullscreen but the fullscreen
3095  // container isn't ready yet, don't do anything more).
3096  if (fullscreen == FlashIsFullscreenOrPending())
3097    return true;
3098
3099  if (!render_frame_)
3100    return false;
3101  if (fullscreen && !render_frame_->render_view()
3102                         ->renderer_preferences()
3103                         .plugin_fullscreen_allowed)
3104    return false;
3105
3106  // Unbind current 2D or 3D graphics context.
3107  VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3108  if (fullscreen) {
3109    DCHECK(!fullscreen_container_);
3110    fullscreen_container_ =
3111        render_frame_->CreatePepperFullscreenContainer(this);
3112    UpdateLayer(false);
3113  } else {
3114    DCHECK(fullscreen_container_);
3115    fullscreen_container_->Destroy();
3116    fullscreen_container_ = NULL;
3117    UpdateFlashFullscreenState(false);
3118    if (!delay_report) {
3119      ReportGeometry();
3120    } else {
3121      base::MessageLoop::current()->PostTask(
3122          FROM_HERE,
3123          base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3124    }
3125  }
3126
3127  return true;
3128}
3129
3130bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3131  if (flash_fullscreen_)
3132    return true;
3133
3134  return container_->isRectTopmost(rect);
3135}
3136
3137int32_t PepperPluginInstanceImpl::Navigate(
3138    const ppapi::URLRequestInfoData& request,
3139    const char* target,
3140    bool from_user_action) {
3141  if (!container_)
3142    return PP_ERROR_FAILED;
3143
3144  WebDocument document = container_->element().document();
3145  WebLocalFrame* frame = document.frame();
3146  if (!frame)
3147    return PP_ERROR_FAILED;
3148
3149  ppapi::URLRequestInfoData completed_request = request;
3150
3151  WebURLRequest web_request;
3152  if (!CreateWebURLRequest(
3153          pp_instance_, &completed_request, frame, &web_request)) {
3154    return PP_ERROR_FAILED;
3155  }
3156  web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3157  web_request.setHasUserGesture(from_user_action);
3158
3159  GURL gurl(web_request.url());
3160  if (gurl.SchemeIs("javascript")) {
3161    // In imitation of the NPAPI implementation, only |target_frame == frame| is
3162    // allowed for security reasons.
3163    WebFrame* target_frame =
3164        frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3165    if (target_frame != frame)
3166      return PP_ERROR_NOACCESS;
3167
3168    // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3169    // need that?
3170    WebString result = container_->executeScriptURL(gurl, from_user_action);
3171    return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3172  }
3173
3174  // Only GETs and POSTs are supported.
3175  if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3176    return PP_ERROR_BADARGUMENT;
3177
3178  WebString target_str = WebString::fromUTF8(target);
3179  container_->loadFrameRequest(web_request, target_str, false, NULL);
3180  return PP_OK;
3181}
3182
3183int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3184    const base::FilePath& path) {
3185  RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3186  PepperFileRefRendererHost* file_ref_host(
3187      new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3188  return host_impl->GetPpapiHost()->AddPendingResourceHost(
3189      scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3190}
3191
3192void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3193  message_channel_->SetReadOnlyProperty(key, value);
3194}
3195
3196bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3197  if (!container_)
3198    return false;
3199  blink::WebDocument containing_document = container_->element().document();
3200
3201  if (!containing_document.frame() || !containing_document.frame()->view() ||
3202      !containing_document.frame()->view()->mainFrame()) {
3203    return false;
3204  }
3205  blink::WebDocument main_document =
3206      containing_document.frame()->view()->mainFrame()->document();
3207
3208  return containing_document.securityOrigin().canAccess(
3209      main_document.securityOrigin());
3210}
3211
3212void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3213  WebElement element = container_->element();
3214  width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3215  height_before_fullscreen_ =
3216      element.getAttribute(WebString::fromUTF8(kHeight));
3217  border_before_fullscreen_ =
3218      element.getAttribute(WebString::fromUTF8(kBorder));
3219  style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3220}
3221
3222void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3223  if (!render_frame_)
3224    return;
3225  blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3226  screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3227  std::string width = StringPrintf("%d", screen_size_for_fullscreen_.width());
3228  std::string height = StringPrintf("%d", screen_size_for_fullscreen_.height());
3229
3230  WebElement element = container_->element();
3231  element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3232  element.setAttribute(WebString::fromUTF8(kHeight),
3233                       WebString::fromUTF8(height));
3234  element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3235
3236  // There should be no style settings that matter in fullscreen mode,
3237  // so just replace them instead of appending.
3238  // NOTE: "position: fixed" and "display: block" reset the plugin and
3239  // using %% settings might not work without them (e.g. if the plugin is a
3240  // child of a container element).
3241  std::string style;
3242  style += StringPrintf("width: %s !important; ", width.c_str());
3243  style += StringPrintf("height: %s !important; ", height.c_str());
3244  style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3245  container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3246}
3247
3248void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3249  screen_size_for_fullscreen_ = gfx::Size();
3250  WebElement element = container_->element();
3251  element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3252  element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3253  element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3254  element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3255}
3256
3257bool PepperPluginInstanceImpl::IsMouseLocked() {
3258  return GetMouseLockDispatcher()->IsMouseLockedTo(
3259      GetOrCreateLockTargetAdapter());
3260}
3261
3262bool PepperPluginInstanceImpl::LockMouse() {
3263  return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3264}
3265
3266MouseLockDispatcher::LockTarget*
3267PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3268  if (!lock_target_.get()) {
3269    lock_target_.reset(new PluginInstanceLockTarget(this));
3270  }
3271  return lock_target_.get();
3272}
3273
3274MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3275  if (flash_fullscreen_) {
3276    RenderWidgetFullscreenPepper* container =
3277        static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3278    return container->mouse_lock_dispatcher();
3279  } else if (render_frame_) {
3280    return render_frame_->render_view()->mouse_lock_dispatcher();
3281  }
3282  return NULL;
3283}
3284
3285void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3286  if (lock_target_.get()) {
3287    GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3288    lock_target_.reset();
3289  }
3290}
3291
3292void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3293    const blink::WebURLResponse& response,
3294    int pending_host_id,
3295    const ppapi::URLResponseInfoData& data) {
3296  if (is_deleted_)
3297    return;
3298
3299  RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3300
3301  if (host_impl->in_process_router()) {
3302    // Running in-process, we can just create the resource and call the
3303    // PPP_Instance function directly.
3304    scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3305        new ppapi::proxy::URLLoaderResource(
3306            host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3307            pp_instance(),
3308            pending_host_id,
3309            data));
3310
3311    PP_Resource loader_pp_resource = loader_resource->GetReference();
3312    if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3313                                                 loader_pp_resource))
3314      loader_resource->Close();
3315    // We don't pass a ref into the plugin, if it wants one, it will have taken
3316    // an additional one.
3317    ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3318        loader_pp_resource);
3319  } else {
3320    // Running out-of-process. Initiate an IPC call to notify the plugin
3321    // process.
3322    ppapi::proxy::HostDispatcher* dispatcher =
3323        ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3324    dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3325        ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3326  }
3327}
3328
3329}  // namespace content
3330