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