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