Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / renderer / pepper / pepper_plugin_instance_impl.cc
blob8a9d98553abea982d104307b179400b6c3c3990e
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.
5 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
7 #include "base/bind.h"
8 #include "base/callback_helpers.h"
9 #include "base/location.h"
10 #include "base/logging.h"
11 #include "base/memory/linked_ptr.h"
12 #include "base/metrics/histogram.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_offset_string_conversions.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/time/time.h"
21 #include "base/trace_event/trace_event.h"
22 #include "cc/blink/web_layer_impl.h"
23 #include "cc/layers/texture_layer.h"
24 #include "content/common/content_constants_internal.h"
25 #include "content/common/frame_messages.h"
26 #include "content/public/common/content_constants.h"
27 #include "content/public/renderer/content_renderer_client.h"
28 #include "content/renderer/pepper/content_decryptor_delegate.h"
29 #include "content/renderer/pepper/event_conversion.h"
30 #include "content/renderer/pepper/fullscreen_container.h"
31 #include "content/renderer/pepper/gfx_conversion.h"
32 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
33 #include "content/renderer/pepper/host_globals.h"
34 #include "content/renderer/pepper/message_channel.h"
35 #include "content/renderer/pepper/pepper_browser_connection.h"
36 #include "content/renderer/pepper/pepper_compositor_host.h"
37 #include "content/renderer/pepper/pepper_file_ref_renderer_host.h"
38 #include "content/renderer/pepper/pepper_graphics_2d_host.h"
39 #include "content/renderer/pepper/pepper_in_process_router.h"
40 #include "content/renderer/pepper/pepper_plugin_instance_metrics.h"
41 #include "content/renderer/pepper/pepper_try_catch.h"
42 #include "content/renderer/pepper/pepper_url_loader_host.h"
43 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
44 #include "content/renderer/pepper/plugin_module.h"
45 #include "content/renderer/pepper/plugin_object.h"
46 #include "content/renderer/pepper/ppapi_preferences_builder.h"
47 #include "content/renderer/pepper/ppb_buffer_impl.h"
48 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
49 #include "content/renderer/pepper/ppb_image_data_impl.h"
50 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
51 #include "content/renderer/pepper/url_request_info_util.h"
52 #include "content/renderer/pepper/url_response_info_util.h"
53 #include "content/renderer/render_frame_impl.h"
54 #include "content/renderer/render_thread_impl.h"
55 #include "content/renderer/render_view_impl.h"
56 #include "content/renderer/render_widget.h"
57 #include "content/renderer/render_widget_fullscreen_pepper.h"
58 #include "content/renderer/sad_plugin.h"
59 #include "media/base/audio_hardware_config.h"
60 #include "ppapi/c/dev/ppp_text_input_dev.h"
61 #include "ppapi/c/pp_rect.h"
62 #include "ppapi/c/ppb_audio_config.h"
63 #include "ppapi/c/ppb_core.h"
64 #include "ppapi/c/ppb_gamepad.h"
65 #include "ppapi/c/ppp_input_event.h"
66 #include "ppapi/c/ppp_instance.h"
67 #include "ppapi/c/ppp_messaging.h"
68 #include "ppapi/c/ppp_mouse_lock.h"
69 #include "ppapi/c/private/ppb_find_private.h"
70 #include "ppapi/c/private/ppp_find_private.h"
71 #include "ppapi/c/private/ppp_instance_private.h"
72 #include "ppapi/c/private/ppp_pdf.h"
73 #include "ppapi/host/ppapi_host.h"
74 #include "ppapi/proxy/ppapi_messages.h"
75 #include "ppapi/proxy/serialized_var.h"
76 #include "ppapi/proxy/uma_private_resource.h"
77 #include "ppapi/proxy/url_loader_resource.h"
78 #include "ppapi/shared_impl/ppapi_permissions.h"
79 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
80 #include "ppapi/shared_impl/ppb_input_event_shared.h"
81 #include "ppapi/shared_impl/ppb_url_util_shared.h"
82 #include "ppapi/shared_impl/ppb_view_shared.h"
83 #include "ppapi/shared_impl/ppp_instance_combined.h"
84 #include "ppapi/shared_impl/resource.h"
85 #include "ppapi/shared_impl/scoped_pp_resource.h"
86 #include "ppapi/shared_impl/scoped_pp_var.h"
87 #include "ppapi/shared_impl/time_conversion.h"
88 #include "ppapi/shared_impl/url_request_info_data.h"
89 #include "ppapi/shared_impl/var.h"
90 #include "ppapi/thunk/enter.h"
91 #include "ppapi/thunk/ppb_buffer_api.h"
92 #include "printing/metafile_skia_wrapper.h"
93 #include "printing/pdf_metafile_skia.h"
94 #include "skia/ext/platform_canvas.h"
95 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
96 #include "third_party/WebKit/public/platform/WebGamepads.h"
97 #include "third_party/WebKit/public/platform/WebRect.h"
98 #include "third_party/WebKit/public/platform/WebString.h"
99 #include "third_party/WebKit/public/platform/WebURL.h"
100 #include "third_party/WebKit/public/platform/WebURLError.h"
101 #include "third_party/WebKit/public/platform/WebURLRequest.h"
102 #include "third_party/WebKit/public/web/WebBindings.h"
103 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
104 #include "third_party/WebKit/public/web/WebDataSource.h"
105 #include "third_party/WebKit/public/web/WebDocument.h"
106 #include "third_party/WebKit/public/web/WebInputEvent.h"
107 #include "third_party/WebKit/public/web/WebLocalFrame.h"
108 #include "third_party/WebKit/public/web/WebPluginContainer.h"
109 #include "third_party/WebKit/public/web/WebPluginScriptForbiddenScope.h"
110 #include "third_party/WebKit/public/web/WebPrintParams.h"
111 #include "third_party/WebKit/public/web/WebPrintPresetOptions.h"
112 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
113 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
114 #include "third_party/WebKit/public/web/WebScriptSource.h"
115 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
116 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
117 #include "third_party/WebKit/public/web/WebView.h"
118 #include "third_party/khronos/GLES2/gl2.h"
119 #include "ui/gfx/image/image_skia.h"
120 #include "ui/gfx/image/image_skia_rep.h"
121 #include "ui/gfx/range/range.h"
122 #include "url/origin.h"
123 #include "v8/include/v8.h"
125 #if defined(OS_CHROMEOS)
126 #include "ui/events/keycodes/keyboard_codes_posix.h"
127 #endif
129 using base::StringPrintf;
130 using ppapi::InputEventData;
131 using ppapi::PpapiGlobals;
132 using ppapi::PPB_InputEvent_Shared;
133 using ppapi::PPB_View_Shared;
134 using ppapi::PPP_Instance_Combined;
135 using ppapi::Resource;
136 using ppapi::ScopedPPResource;
137 using ppapi::ScopedPPVar;
138 using ppapi::StringVar;
139 using ppapi::TrackedCallback;
140 using ppapi::thunk::EnterResourceNoLock;
141 using ppapi::thunk::PPB_Buffer_API;
142 using ppapi::thunk::PPB_Gamepad_API;
143 using ppapi::thunk::PPB_Graphics2D_API;
144 using ppapi::thunk::PPB_Graphics3D_API;
145 using ppapi::thunk::PPB_ImageData_API;
146 using ppapi::Var;
147 using ppapi::ArrayBufferVar;
148 using ppapi::ViewData;
149 using blink::WebBindings;
150 using blink::WebCanvas;
151 using blink::WebCursorInfo;
152 using blink::WebDocument;
153 using blink::WebElement;
154 using blink::WebFrame;
155 using blink::WebInputEvent;
156 using blink::WebLocalFrame;
157 using blink::WebPlugin;
158 using blink::WebPluginContainer;
159 using blink::WebPrintParams;
160 using blink::WebPrintScalingOption;
161 using blink::WebScopedUserGesture;
162 using blink::WebString;
163 using blink::WebURLError;
164 using blink::WebURLLoader;
165 using blink::WebURLLoaderClient;
166 using blink::WebURLRequest;
167 using blink::WebURLResponse;
168 using blink::WebUserGestureIndicator;
169 using blink::WebUserGestureToken;
170 using blink::WebView;
172 namespace content {
174 namespace {
176 #define STATIC_ASSERT_PP_MATCHING_ENUM(a, b) \
177 static_assert(static_cast<int>(a) == static_cast<int>(b), \
178 "mismatching enums: " #a)
180 // Check PP_TextInput_Type and ui::TextInputType are kept in sync.
181 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_NONE,
182 PP_TEXTINPUT_TYPE_NONE);
183 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_TEXT,
184 PP_TEXTINPUT_TYPE_TEXT);
185 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_PASSWORD,
186 PP_TEXTINPUT_TYPE_PASSWORD);
187 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_SEARCH,
188 PP_TEXTINPUT_TYPE_SEARCH);
189 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_EMAIL,
190 PP_TEXTINPUT_TYPE_EMAIL);
191 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_NUMBER,
192 PP_TEXTINPUT_TYPE_NUMBER);
193 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_TELEPHONE,
194 PP_TEXTINPUT_TYPE_TELEPHONE);
195 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_URL,
196 PP_TEXTINPUT_TYPE_URL);
198 // The default text input type is to regard the plugin always accept text input.
199 // This is for allowing users to use input methods even on completely-IME-
200 // unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
201 // Plugins need to explicitly opt out the text input mode if they know
202 // that they don't accept texts.
203 const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
205 // <embed>/<object> attributes.
206 const char kWidth[] = "width";
207 const char kHeight[] = "height";
208 const char kBorder[] = "border"; // According to w3c, deprecated.
209 const char kStyle[] = "style";
211 #define STATIC_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
212 static_assert(static_cast<int>(WebCursorInfo::webkit_name) == \
213 static_cast<int>(np_name), \
214 "mismatching enums: " #webkit_name)
216 STATIC_ASSERT_MATCHING_ENUM(TypePointer, PP_MOUSECURSOR_TYPE_POINTER);
217 STATIC_ASSERT_MATCHING_ENUM(TypeCross, PP_MOUSECURSOR_TYPE_CROSS);
218 STATIC_ASSERT_MATCHING_ENUM(TypeHand, PP_MOUSECURSOR_TYPE_HAND);
219 STATIC_ASSERT_MATCHING_ENUM(TypeIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
220 STATIC_ASSERT_MATCHING_ENUM(TypeWait, PP_MOUSECURSOR_TYPE_WAIT);
221 STATIC_ASSERT_MATCHING_ENUM(TypeHelp, PP_MOUSECURSOR_TYPE_HELP);
222 STATIC_ASSERT_MATCHING_ENUM(TypeEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
223 STATIC_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
224 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastResize,
225 PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
226 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestResize,
227 PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
228 STATIC_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
229 STATIC_ASSERT_MATCHING_ENUM(TypeSouthEastResize,
230 PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
231 STATIC_ASSERT_MATCHING_ENUM(TypeSouthWestResize,
232 PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
233 STATIC_ASSERT_MATCHING_ENUM(TypeWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
234 STATIC_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
235 PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
236 STATIC_ASSERT_MATCHING_ENUM(TypeEastWestResize,
237 PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
238 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
239 PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
240 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
241 PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
242 STATIC_ASSERT_MATCHING_ENUM(TypeColumnResize,
243 PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
244 STATIC_ASSERT_MATCHING_ENUM(TypeRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
245 STATIC_ASSERT_MATCHING_ENUM(TypeMiddlePanning,
246 PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
247 STATIC_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
248 STATIC_ASSERT_MATCHING_ENUM(TypeNorthPanning,
249 PP_MOUSECURSOR_TYPE_NORTHPANNING);
250 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
251 PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
252 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
253 PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
254 STATIC_ASSERT_MATCHING_ENUM(TypeSouthPanning,
255 PP_MOUSECURSOR_TYPE_SOUTHPANNING);
256 STATIC_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
257 PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
258 STATIC_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
259 PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
260 STATIC_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
261 STATIC_ASSERT_MATCHING_ENUM(TypeMove, PP_MOUSECURSOR_TYPE_MOVE);
262 STATIC_ASSERT_MATCHING_ENUM(TypeVerticalText,
263 PP_MOUSECURSOR_TYPE_VERTICALTEXT);
264 STATIC_ASSERT_MATCHING_ENUM(TypeCell, PP_MOUSECURSOR_TYPE_CELL);
265 STATIC_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
266 STATIC_ASSERT_MATCHING_ENUM(TypeAlias, PP_MOUSECURSOR_TYPE_ALIAS);
267 STATIC_ASSERT_MATCHING_ENUM(TypeProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
268 STATIC_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
269 STATIC_ASSERT_MATCHING_ENUM(TypeCopy, PP_MOUSECURSOR_TYPE_COPY);
270 STATIC_ASSERT_MATCHING_ENUM(TypeNone, PP_MOUSECURSOR_TYPE_NONE);
271 STATIC_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
272 STATIC_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
273 STATIC_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
274 STATIC_ASSERT_MATCHING_ENUM(TypeGrab, PP_MOUSECURSOR_TYPE_GRAB);
275 STATIC_ASSERT_MATCHING_ENUM(TypeGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
276 // Do not assert WebCursorInfo::TypeCustom == PP_CURSORTYPE_CUSTOM;
277 // PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
279 STATIC_ASSERT_PP_MATCHING_ENUM(blink::WebPrintScalingOptionNone,
280 PP_PRINTSCALINGOPTION_NONE);
281 STATIC_ASSERT_PP_MATCHING_ENUM(
282 blink::WebPrintScalingOptionFitToPrintableArea,
283 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
284 STATIC_ASSERT_PP_MATCHING_ENUM(
285 blink::WebPrintScalingOptionSourceSize,
286 PP_PRINTSCALINGOPTION_SOURCE_SIZE);
288 // Sets |*security_origin| to be the WebKit security origin associated with the
289 // document containing the given plugin instance. On success, returns true. If
290 // the instance is invalid, returns false and |*security_origin| will be
291 // unchanged.
292 bool SecurityOriginForInstance(PP_Instance instance_id,
293 blink::WebSecurityOrigin* security_origin) {
294 PepperPluginInstanceImpl* instance =
295 HostGlobals::Get()->GetInstance(instance_id);
296 if (!instance)
297 return false;
299 WebElement plugin_element = instance->container()->element();
300 *security_origin = plugin_element.document().securityOrigin();
301 return true;
304 // Convert the given vector to an array of C-strings. The strings in the
305 // returned vector are only guaranteed valid so long as the vector of strings
306 // is not modified.
307 scoped_ptr<const char* []> StringVectorToArgArray(
308 const std::vector<std::string>& vector) {
309 scoped_ptr<const char * []> array(new const char* [vector.size()]);
310 for (size_t i = 0; i < vector.size(); ++i)
311 array[i] = vector[i].c_str();
312 return array.Pass();
315 // Returns true if this is a "system reserved" key which should not be sent to
316 // a plugin. Some poorly behaving plugins (like Flash) incorrectly report that
317 // they handle all keys sent to them. This can prevent keystrokes from working
318 // for things like screen brightness and volume control.
319 bool IsReservedSystemInputEvent(const blink::WebInputEvent& event) {
320 #if defined(OS_CHROMEOS)
321 if (event.type != WebInputEvent::KeyDown &&
322 event.type != WebInputEvent::KeyUp)
323 return false;
324 const blink::WebKeyboardEvent& key_event =
325 static_cast<const blink::WebKeyboardEvent&>(event);
326 switch (key_event.windowsKeyCode) {
327 case ui::VKEY_BRIGHTNESS_DOWN:
328 case ui::VKEY_BRIGHTNESS_UP:
329 case ui::VKEY_KBD_BRIGHTNESS_DOWN:
330 case ui::VKEY_KBD_BRIGHTNESS_UP:
331 case ui::VKEY_VOLUME_MUTE:
332 case ui::VKEY_VOLUME_DOWN:
333 case ui::VKEY_VOLUME_UP:
334 return true;
335 default:
336 return false;
338 #endif // defined(OS_CHROMEOS)
339 return false;
342 class PluginInstanceLockTarget : public MouseLockDispatcher::LockTarget {
343 public:
344 explicit PluginInstanceLockTarget(PepperPluginInstanceImpl* plugin)
345 : plugin_(plugin) {}
347 void OnLockMouseACK(bool succeeded) override {
348 plugin_->OnLockMouseACK(succeeded);
351 void OnMouseLockLost() override { plugin_->OnMouseLockLost(); }
353 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
354 plugin_->HandleMouseLockedInputEvent(event);
355 return true;
358 private:
359 PepperPluginInstanceImpl* plugin_;
362 } // namespace
364 // static
365 PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
366 RenderFrameImpl* render_frame,
367 PluginModule* module,
368 WebPluginContainer* container,
369 const GURL& plugin_url) {
370 base::Callback<const void*(const char*)> get_plugin_interface_func =
371 base::Bind(&PluginModule::GetPluginInterface, module);
372 PPP_Instance_Combined* ppp_instance_combined =
373 PPP_Instance_Combined::Create(get_plugin_interface_func);
374 if (!ppp_instance_combined)
375 return NULL;
377 return new PepperPluginInstanceImpl(render_frame,
378 module,
379 ppp_instance_combined,
380 container,
381 plugin_url);
384 PepperPluginInstanceImpl::ExternalDocumentLoader::ExternalDocumentLoader()
385 : finished_loading_(false) {}
387 PepperPluginInstanceImpl::ExternalDocumentLoader::~ExternalDocumentLoader() {}
389 void PepperPluginInstanceImpl::ExternalDocumentLoader::ReplayReceivedData(
390 WebURLLoaderClient* document_loader) {
391 for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
392 ++it) {
393 document_loader->didReceiveData(
394 NULL, it->c_str(), it->length(), 0 /* encoded_data_length */);
396 if (finished_loading_) {
397 document_loader->didFinishLoading(
398 NULL,
399 0 /* finish_time */,
400 blink::WebURLLoaderClient::kUnknownEncodedDataLength);
401 } else if (error_.get()) {
402 DCHECK(!finished_loading_);
403 document_loader->didFail(NULL, *error_);
407 void PepperPluginInstanceImpl::ExternalDocumentLoader::didReceiveData(
408 WebURLLoader* loader,
409 const char* data,
410 int data_length,
411 int encoded_data_length) {
412 data_.push_back(std::string(data, data_length));
415 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFinishLoading(
416 WebURLLoader* loader,
417 double finish_time,
418 int64_t total_encoded_data_length) {
419 DCHECK(!finished_loading_);
421 if (error_.get())
422 return;
424 finished_loading_ = true;
427 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFail(
428 WebURLLoader* loader,
429 const WebURLError& error) {
430 DCHECK(!error_.get());
432 if (finished_loading_)
433 return;
435 error_.reset(new WebURLError(error));
438 PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
439 : Resource(ppapi::Resource::Untracked()) {}
441 PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
443 PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
444 return this;
447 void PepperPluginInstanceImpl::GamepadImpl::Sample(
448 PP_Instance instance,
449 PP_GamepadsSampleData* data) {
450 blink::WebGamepads webkit_data;
451 RenderThreadImpl::current()->SampleGamepads(&webkit_data);
452 ConvertWebKitGamepadData(bit_cast<ppapi::WebKitGamepads>(webkit_data), data);
455 PepperPluginInstanceImpl::PepperPluginInstanceImpl(
456 RenderFrameImpl* render_frame,
457 PluginModule* module,
458 ppapi::PPP_Instance_Combined* instance_interface,
459 WebPluginContainer* container,
460 const GURL& plugin_url)
461 : RenderFrameObserver(render_frame),
462 render_frame_(render_frame),
463 module_(module),
464 instance_interface_(instance_interface),
465 pp_instance_(0),
466 container_(container),
467 layer_bound_to_fullscreen_(false),
468 layer_is_hardware_(false),
469 plugin_url_(plugin_url),
470 document_url_(container ? GURL(container->element().document().url())
471 : GURL()),
472 is_flash_plugin_(module->name() == kFlashPluginName),
473 has_been_clicked_(false),
474 javascript_used_(false),
475 full_frame_(false),
476 sent_initial_did_change_view_(false),
477 bound_graphics_2d_platform_(NULL),
478 bound_compositor_(NULL),
479 has_webkit_focus_(false),
480 has_content_area_focus_(false),
481 find_identifier_(-1),
482 plugin_find_interface_(NULL),
483 plugin_input_event_interface_(NULL),
484 plugin_mouse_lock_interface_(NULL),
485 plugin_pdf_interface_(NULL),
486 plugin_private_interface_(NULL),
487 plugin_textinput_interface_(NULL),
488 checked_for_plugin_input_event_interface_(false),
489 checked_for_plugin_pdf_interface_(false),
490 gamepad_impl_(new GamepadImpl()),
491 uma_private_impl_(NULL),
492 plugin_print_interface_(NULL),
493 plugin_graphics_3d_interface_(NULL),
494 always_on_top_(false),
495 fullscreen_container_(NULL),
496 flash_fullscreen_(false),
497 desired_fullscreen_state_(false),
498 message_channel_(NULL),
499 sad_plugin_(NULL),
500 input_event_mask_(0),
501 filtered_input_event_mask_(0),
502 text_input_type_(kPluginDefaultTextInputType),
503 text_input_caret_(0, 0, 0, 0),
504 text_input_caret_bounds_(0, 0, 0, 0),
505 text_input_caret_set_(false),
506 selection_caret_(0),
507 selection_anchor_(0),
508 pending_user_gesture_(0.0),
509 document_loader_(NULL),
510 external_document_load_(false),
511 isolate_(v8::Isolate::GetCurrent()),
512 is_deleted_(false),
513 initialized_(false),
514 view_change_weak_ptr_factory_(this),
515 weak_factory_(this) {
516 pp_instance_ = HostGlobals::Get()->AddInstance(this);
518 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
519 module_->InstanceCreated(this);
521 if (render_frame) { // NULL in tests
522 render_frame->render_view()->PepperInstanceCreated(this);
523 // Bind a callback now so that we can inform the RenderViewImpl when we are
524 // destroyed. This works around a temporary problem stemming from work to
525 // move parts of RenderViewImpl in to RenderFrameImpl (see
526 // crbug.com/245126). If destruction happens in this order:
527 // 1) RenderFrameImpl
528 // 2) PepperPluginInstanceImpl
529 // 3) RenderViewImpl
530 // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
531 // to the RenderViewImpl. But when the instance is destroyed, it still
532 // needs to inform the RenderViewImpl that it has gone away, otherwise
533 // between (2) and (3), the RenderViewImpl will still have the dead
534 // instance in its active set, and so might make calls on the deleted
535 // instance. See crbug.com/343576 for more information. Once the plugin
536 // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
537 // can be a little bit simplified by instead making a direct call on
538 // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
539 instance_deleted_callback_ =
540 base::Bind(&RenderViewImpl::PepperInstanceDeleted,
541 render_frame->render_view()->AsWeakPtr(),
542 base::Unretained(this));
543 view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
545 // Set the initial focus.
546 SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
548 if (!module_->IsProxied()) {
549 PepperBrowserConnection* browser_connection =
550 PepperBrowserConnection::Get(render_frame_);
551 browser_connection->DidCreateInProcessInstance(
552 pp_instance(),
553 render_frame_->GetRoutingID(),
554 document_url_,
555 GetPluginURL());
559 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
560 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
562 if (GetContentClient()->renderer() && // NULL in unit tests.
563 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
564 external_document_load_ = true;
567 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
568 DCHECK(!fullscreen_container_);
570 // Notify all the plugin objects of deletion. This will prevent blink from
571 // calling into the plugin any more.
573 // Swap out the set so we can delete from it (the objects will try to
574 // unregister themselves inside the delete call).
575 PluginObjectSet plugin_object_copy;
576 live_plugin_objects_.swap(plugin_object_copy);
577 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
578 i != plugin_object_copy.end();
579 ++i) {
580 (*i)->InstanceDeleted();
583 if (message_channel_)
584 message_channel_->InstanceDeleted();
585 message_channel_object_.Reset();
587 if (TrackedCallback::IsPending(lock_mouse_callback_))
588 lock_mouse_callback_->Abort();
590 if (!instance_deleted_callback_.is_null())
591 instance_deleted_callback_.Run();
593 if (!module_->IsProxied() && render_frame_) {
594 PepperBrowserConnection* browser_connection =
595 PepperBrowserConnection::Get(render_frame_);
596 browser_connection->DidDeleteInProcessInstance(pp_instance());
599 UnSetAndDeleteLockTargetAdapter();
600 module_->InstanceDeleted(this);
601 // If we switched from the NaCl plugin module, notify it too.
602 if (original_module_.get())
603 original_module_->InstanceDeleted(this);
605 // This should be last since some of the above "instance deleted" calls will
606 // want to look up in the global map to get info off of our object.
607 HostGlobals::Get()->InstanceDeleted(pp_instance_);
609 if (throttler_)
610 throttler_->RemoveObserver(this);
613 // NOTE: Any of these methods that calls into the plugin needs to take into
614 // account that the plugin may use Var to remove the <embed> from the DOM, which
615 // will make the PepperWebPluginImpl drop its reference, usually the last one.
616 // If a method needs to access a member of the instance after the call has
617 // returned, then it needs to keep its own reference on the stack.
619 v8::Local<v8::Object> PepperPluginInstanceImpl::GetMessageChannelObject() {
620 return v8::Local<v8::Object>::New(isolate_, message_channel_object_);
623 void PepperPluginInstanceImpl::MessageChannelDestroyed() {
624 message_channel_ = NULL;
625 message_channel_object_.Reset();
628 v8::Local<v8::Context> PepperPluginInstanceImpl::GetMainWorldContext() {
629 if (!container_)
630 return v8::Local<v8::Context>();
632 if (container_->element().isNull())
633 return v8::Local<v8::Context>();
635 if (container_->element().document().isNull())
636 return v8::Local<v8::Context>();
638 if (!container_->element().document().frame())
639 return v8::Local<v8::Context>();
641 v8::Local<v8::Context> context =
642 container_->element().document().frame()->mainWorldScriptContext();
643 DCHECK(context->GetIsolate() == isolate_);
644 return context;
647 void PepperPluginInstanceImpl::Delete() {
648 is_deleted_ = true;
650 if (render_frame_ && render_frame_->render_view() &&
651 render_frame_->render_view()->plugin_find_handler() == this) {
652 render_frame_->render_view()->set_plugin_find_handler(NULL);
655 // Keep a reference on the stack. See NOTE above.
656 scoped_refptr<PepperPluginInstanceImpl> ref(this);
658 // It is important to destroy the throttler before anything else.
659 // The plugin instance may flush its graphics pipeline during its postmortem
660 // spasm, causing the throttler to engage and obtain new dangling reference
661 // to the plugin container being destroyed.
662 throttler_.reset();
664 // Force the MessageChannel to release its "passthrough object" which should
665 // release our last reference to the "InstanceObject" and will probably
666 // destroy it. We want to do this prior to calling DidDestroy in case the
667 // destructor of the instance object tries to use the instance.
668 if (message_channel_)
669 message_channel_->SetPassthroughObject(v8::Local<v8::Object>());
670 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
671 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
672 // since there is little that it can do at this point.
673 if (original_instance_interface_) {
674 base::TimeTicks start = base::TimeTicks::Now();
675 original_instance_interface_->DidDestroy(pp_instance());
676 UMA_HISTOGRAM_CUSTOM_TIMES("NaCl.Perf.ShutdownTime.Total",
677 base::TimeTicks::Now() - start,
678 base::TimeDelta::FromMilliseconds(1),
679 base::TimeDelta::FromSeconds(20),
680 100);
681 } else {
682 instance_interface_->DidDestroy(pp_instance());
684 // Ensure we don't attempt to call functions on the destroyed instance.
685 original_instance_interface_.reset();
686 instance_interface_.reset();
688 if (fullscreen_container_) {
689 fullscreen_container_->Destroy();
690 fullscreen_container_ = NULL;
693 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
694 // leaks the graphics 2D, it may actually get cleaned up after our
695 // destruction, so we need its pointers to be up-to-date.
696 BindGraphics(pp_instance(), 0);
697 container_ = NULL;
700 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
702 void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
703 const gfx::Rect& plugin_rect,
704 const gfx::Rect& paint_rect) {
705 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
706 if (module()->is_crashed()) {
707 // Crashed plugin painting.
708 if (!sad_plugin_) // Lazily initialize bitmap.
709 sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
710 if (sad_plugin_)
711 PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
712 return;
715 if (bound_graphics_2d_platform_)
716 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
719 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
720 if (fullscreen_container_) {
721 if (rect.IsEmpty())
722 fullscreen_container_->Invalidate();
723 else
724 fullscreen_container_->InvalidateRect(rect);
725 } else {
726 if (!container_ || view_data_.rect.size.width == 0 ||
727 view_data_.rect.size.height == 0)
728 return; // Nothing to do.
729 if (rect.IsEmpty())
730 container_->invalidate();
731 else
732 container_->invalidateRect(rect);
735 cc::Layer* layer =
736 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
737 if (layer) {
738 if (rect.IsEmpty()) {
739 layer->SetNeedsDisplay();
740 } else {
741 layer->SetNeedsDisplayRect(rect);
746 void PepperPluginInstanceImpl::ScrollRect(int dx,
747 int dy,
748 const gfx::Rect& rect) {
749 cc::Layer* layer =
750 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
751 if (layer) {
752 InvalidateRect(rect);
753 } else if (fullscreen_container_) {
754 fullscreen_container_->ScrollRect(dx, dy, rect);
755 } else {
756 if (full_frame_ && !IsViewAccelerated()) {
757 container_->scrollRect(rect);
758 } else {
759 // Can't do optimized scrolling since there could be other elements on top
760 // of us or the view renders via the accelerated compositor which is
761 // incompatible with the move and backfill scrolling model.
762 InvalidateRect(rect);
767 void PepperPluginInstanceImpl::CommitBackingTexture() {
768 if (!texture_layer_.get())
769 return;
770 gpu::Mailbox mailbox;
771 uint32 sync_point = 0;
772 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
773 DCHECK(!mailbox.IsZero());
774 DCHECK_NE(sync_point, 0u);
775 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
776 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
777 texture_layer_->SetNeedsDisplay();
780 void PepperPluginInstanceImpl::InstanceCrashed() {
781 // Force free all resources and vars.
782 HostGlobals::Get()->InstanceCrashed(pp_instance());
784 // Free any associated graphics.
785 SetFullscreen(false);
786 FlashSetFullscreen(false, false);
787 // Unbind current 2D or 3D graphics context.
788 BindGraphics(pp_instance(), 0);
789 InvalidateRect(gfx::Rect());
791 if (content_decryptor_delegate_) {
792 content_decryptor_delegate_->InstanceCrashed();
793 content_decryptor_delegate_.reset();
796 if (render_frame_)
797 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
798 UnSetAndDeleteLockTargetAdapter();
801 bool PepperPluginInstanceImpl::Initialize(
802 const std::vector<std::string>& arg_names,
803 const std::vector<std::string>& arg_values,
804 bool full_frame,
805 scoped_ptr<PluginInstanceThrottlerImpl> throttler) {
806 DCHECK(!throttler_);
808 if (!render_frame_)
809 return false;
811 if (throttler) {
812 throttler_ = throttler.Pass();
813 throttler_->AddObserver(this);
816 message_channel_ = MessageChannel::Create(this, &message_channel_object_);
818 full_frame_ = full_frame;
820 UpdateTouchEventRequest();
821 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
823 SetGPUHistogram(ppapi::Preferences(PpapiPreferencesBuilder::Build(
824 render_frame_->render_view()->webkit_preferences())),
825 arg_names,
826 arg_values);
828 argn_ = arg_names;
829 argv_ = arg_values;
830 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
831 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
832 auto weak_this = weak_factory_.GetWeakPtr();
833 bool success = PP_ToBool(instance_interface_->DidCreate(
834 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
835 if (!weak_this) {
836 // The plugin may do synchronous scripting during "DidCreate", so |this|
837 // may be deleted. In that case, return failure and don't touch any
838 // member variables.
839 return false;
841 // If this is a plugin that hosts external plugins, we should delay messages
842 // so that the child plugin that's created later will receive all the
843 // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
845 // A host for external plugins will call ResetAsProxied later, at which point
846 // we can Start() the MessageChannel.
847 if (success && (!module_->renderer_ppapi_host()->IsExternalPluginHost())) {
848 if (message_channel_)
849 message_channel_->Start();
851 initialized_ = success;
852 return success;
855 bool PepperPluginInstanceImpl::HandleDocumentLoad(
856 const blink::WebURLResponse& response) {
857 DCHECK(!document_loader_);
858 if (external_document_load_) {
859 // The external proxy isn't available, so save the response and record
860 // document load notifications for later replay.
861 external_document_response_ = response;
862 external_document_loader_.reset(new ExternalDocumentLoader());
863 document_loader_ = external_document_loader_.get();
864 return true;
867 if (module()->is_crashed()) {
868 // Don't create a resource for a crashed plugin.
869 container()->element().document().frame()->stopLoading();
870 return false;
873 DCHECK(!document_loader_);
875 // Create a loader resource host for this load. Note that we have to set
876 // the document_loader before issuing the in-process
877 // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
878 // call into the instance and expect it to be valid.
879 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
880 PepperURLLoaderHost* loader_host =
881 new PepperURLLoaderHost(host_impl, true, pp_instance(), 0);
882 // TODO(teravest): Remove set_document_loader() from instance and clean up
883 // this relationship.
884 set_document_loader(loader_host);
885 loader_host->didReceiveResponse(NULL, response);
887 // This host will be pending until the resource object attaches to it.
889 // PpapiHost now owns the pointer to loader_host, so we don't have to worry
890 // about managing it.
891 int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
892 scoped_ptr<ppapi::host::ResourceHost>(loader_host));
893 DCHECK(pending_host_id);
895 DataFromWebURLResponse(
896 host_impl,
897 pp_instance(),
898 response,
899 base::Bind(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
900 weak_factory_.GetWeakPtr(),
901 response,
902 pending_host_id));
904 // If the load was not abandoned, document_loader_ will now be set. It's
905 // possible that the load was canceled by now and document_loader_ was
906 // already nulled out.
907 return true;
910 bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
911 PP_InputEvent_Type type,
912 const base::string16& text) {
913 std::vector<blink::WebCompositionUnderline> empty;
914 return SendCompositionEventWithUnderlineInformationToPlugin(
915 type,
916 text,
917 empty,
918 static_cast<int>(text.size()),
919 static_cast<int>(text.size()));
922 bool
923 PepperPluginInstanceImpl::SendCompositionEventWithUnderlineInformationToPlugin(
924 PP_InputEvent_Type type,
925 const base::string16& text,
926 const std::vector<blink::WebCompositionUnderline>& underlines,
927 int selection_start,
928 int selection_end) {
929 // Keep a reference on the stack. See NOTE above.
930 scoped_refptr<PepperPluginInstanceImpl> ref(this);
932 if (!LoadInputEventInterface())
933 return false;
935 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
936 if (!(filtered_input_event_mask_ & event_class) &&
937 !(input_event_mask_ & event_class))
938 return false;
940 ppapi::InputEventData event;
941 event.event_type = type;
942 event.event_time_stamp =
943 ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
945 // Convert UTF16 text to UTF8 with offset conversion.
946 std::vector<size_t> utf16_offsets;
947 utf16_offsets.push_back(selection_start);
948 utf16_offsets.push_back(selection_end);
949 for (size_t i = 0; i < underlines.size(); ++i) {
950 utf16_offsets.push_back(underlines[i].startOffset);
951 utf16_offsets.push_back(underlines[i].endOffset);
953 std::vector<size_t> utf8_offsets(utf16_offsets);
954 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
956 // Set the converted selection range.
957 event.composition_selection_start =
958 (utf8_offsets[0] == std::string::npos ? event.character_text.size()
959 : utf8_offsets[0]);
960 event.composition_selection_end =
961 (utf8_offsets[1] == std::string::npos ? event.character_text.size()
962 : utf8_offsets[1]);
964 // Set the converted segmentation points.
965 // Be sure to add 0 and size(), and remove duplication or errors.
966 std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
967 offset_set.insert(0);
968 offset_set.insert(event.character_text.size());
969 offset_set.erase(std::string::npos);
970 event.composition_segment_offsets.assign(offset_set.begin(),
971 offset_set.end());
973 // Set the composition target.
974 for (size_t i = 0; i < underlines.size(); ++i) {
975 if (underlines[i].thick) {
976 std::vector<uint32_t>::iterator it =
977 std::find(event.composition_segment_offsets.begin(),
978 event.composition_segment_offsets.end(),
979 utf8_offsets[2 * i + 2]);
980 if (it != event.composition_segment_offsets.end()) {
981 event.composition_target_segment =
982 it - event.composition_segment_offsets.begin();
983 break;
988 // Send the event.
989 bool handled = false;
990 if (filtered_input_event_mask_ & event_class)
991 event.is_filtered = true;
992 else
993 handled = true; // Unfiltered events are assumed to be handled.
994 scoped_refptr<PPB_InputEvent_Shared> event_resource(
995 new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
996 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
997 pp_instance(), event_resource->pp_resource()));
998 return handled;
1001 void PepperPluginInstanceImpl::RequestInputEventsHelper(
1002 uint32_t event_classes) {
1003 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
1004 UpdateTouchEventRequest();
1005 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
1006 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
1009 bool PepperPluginInstanceImpl::HandleCompositionStart(
1010 const base::string16& text) {
1011 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1012 text);
1015 bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1016 const base::string16& text,
1017 const std::vector<blink::WebCompositionUnderline>& underlines,
1018 int selection_start,
1019 int selection_end) {
1020 return SendCompositionEventWithUnderlineInformationToPlugin(
1021 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
1022 text,
1023 underlines,
1024 selection_start,
1025 selection_end);
1028 bool PepperPluginInstanceImpl::HandleCompositionEnd(
1029 const base::string16& text) {
1030 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1031 text);
1034 bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1035 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1038 void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1039 gfx::Range* range) const {
1040 std::vector<size_t> offsets;
1041 offsets.push_back(selection_anchor_);
1042 offsets.push_back(selection_caret_);
1043 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1044 range->set_start(offsets[0] == base::string16::npos ? text->size()
1045 : offsets[0]);
1046 range->set_end(offsets[1] == base::string16::npos ? text->size()
1047 : offsets[1]);
1050 bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1051 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1052 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1055 gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1056 if (!text_input_caret_set_) {
1057 // If it is never set by the plugin, use the bottom left corner.
1058 return gfx::Rect(view_data_.rect.point.x,
1059 view_data_.rect.point.y + view_data_.rect.size.height,
1064 // TODO(kinaba) Take CSS transformation into accont.
1065 // TODO(kinaba) Take bounding_box into account. On some platforms, an
1066 // "exclude rectangle" where candidate window must avoid the region can be
1067 // passed to IME. Currently, we pass only the caret rectangle because
1068 // it is the only information supported uniformly in Chromium.
1069 gfx::Rect caret(text_input_caret_);
1070 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1071 return caret;
1074 bool PepperPluginInstanceImpl::HandleInputEvent(
1075 const blink::WebInputEvent& event,
1076 WebCursorInfo* cursor_info) {
1077 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1079 if (!has_been_clicked_ && is_flash_plugin_ &&
1080 event.type == blink::WebInputEvent::MouseDown &&
1081 (event.modifiers & blink::WebInputEvent::LeftButtonDown)) {
1082 has_been_clicked_ = true;
1083 blink::WebRect bounds = container()->element().boundsInViewportSpace();
1084 RecordFlashClickSizeMetric(bounds.width, bounds.height);
1087 if (throttler_ && throttler_->ConsumeInputEvent(event))
1088 return true;
1090 if (!render_frame_)
1091 return false;
1092 if (WebInputEvent::isMouseEventType(event.type)) {
1093 render_frame_->PepperDidReceiveMouseEvent(this);
1096 // Don't dispatch input events to crashed plugins.
1097 if (module()->is_crashed())
1098 return false;
1100 // Don't send reserved system key events to plugins.
1101 if (IsReservedSystemInputEvent(event))
1102 return false;
1104 // Keep a reference on the stack. See NOTE above.
1105 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1107 bool rv = false;
1108 if (LoadInputEventInterface()) {
1109 PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
1110 if (!event_class)
1111 return false;
1113 if ((filtered_input_event_mask_ & event_class) ||
1114 (input_event_mask_ & event_class)) {
1115 // Actually send the event.
1116 std::vector<ppapi::InputEventData> events;
1117 CreateInputEventData(event, &events);
1119 // Allow the user gesture to be pending after the plugin handles the
1120 // event. This allows out-of-process plugins to respond to the user
1121 // gesture after processing has finished here.
1122 if (WebUserGestureIndicator::isProcessingUserGesture()) {
1123 pending_user_gesture_ =
1124 ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
1125 pending_user_gesture_token_ =
1126 WebUserGestureIndicator::currentUserGestureToken();
1127 pending_user_gesture_token_.setOutOfProcess();
1130 // Each input event may generate more than one PP_InputEvent.
1131 for (size_t i = 0; i < events.size(); i++) {
1132 if (filtered_input_event_mask_ & event_class)
1133 events[i].is_filtered = true;
1134 else
1135 rv = true; // Unfiltered events are assumed to be handled.
1136 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1137 new PPB_InputEvent_Shared(
1138 ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1140 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1141 pp_instance(), event_resource->pp_resource()));
1146 if (cursor_)
1147 *cursor_info = *cursor_;
1148 return rv;
1151 void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1152 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1153 if (is_deleted_)
1154 return;
1155 ppapi::proxy::HostDispatcher* dispatcher =
1156 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1157 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1158 // The dispatcher should always be valid, and MessageChannel should never
1159 // send an 'object' var over PPP_Messaging.
1160 NOTREACHED();
1161 return;
1163 dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1164 ppapi::API_ID_PPP_MESSAGING,
1165 pp_instance(),
1166 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1167 pp_instance())));
1170 bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1171 ScopedPPVar* result) {
1172 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
1173 if (is_deleted_)
1174 return false;
1175 ppapi::proxy::HostDispatcher* dispatcher =
1176 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1177 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1178 // The dispatcher should always be valid, and MessageChannel should never
1179 // send an 'object' var over PPP_Messaging.
1180 NOTREACHED();
1181 return false;
1183 ppapi::proxy::ReceiveSerializedVarReturnValue msg_reply;
1184 bool was_handled = false;
1185 dispatcher->Send(new PpapiMsg_PPPMessageHandler_HandleBlockingMessage(
1186 ppapi::API_ID_PPP_MESSAGING,
1187 pp_instance(),
1188 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1189 pp_instance()),
1190 &msg_reply,
1191 &was_handled));
1192 *result = ScopedPPVar(ScopedPPVar::PassRef(), msg_reply.Return(dispatcher));
1193 TRACE_EVENT0("ppapi",
1194 "PepperPluginInstanceImpl::HandleBlockingMessage return.");
1195 return was_handled;
1198 PP_Var PepperPluginInstanceImpl::GetInstanceObject(v8::Isolate* isolate) {
1199 // Keep a reference on the stack. See NOTE above.
1200 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1202 DCHECK_EQ(isolate, isolate_);
1203 RecordFlashJavaScriptUse();
1205 // If the plugin supports the private instance interface, try to retrieve its
1206 // instance object.
1207 if (LoadPrivateInterface())
1208 return plugin_private_interface_->GetInstanceObject(pp_instance());
1209 return PP_MakeUndefined();
1212 void PepperPluginInstanceImpl::ViewChanged(
1213 const gfx::Rect& window,
1214 const gfx::Rect& clip,
1215 const gfx::Rect& unobscured,
1216 const std::vector<gfx::Rect>& cut_outs_rects) {
1217 // WebKit can give weird (x,y) positions for empty clip rects (since the
1218 // position technically doesn't matter). But we want to make these
1219 // consistent since this is given to the plugin, so force everything to 0
1220 // in the "everything is clipped" case.
1221 gfx::Rect new_clip;
1222 if (!clip.IsEmpty())
1223 new_clip = clip;
1225 unobscured_rect_ = unobscured;
1227 cut_outs_rects_ = cut_outs_rects;
1229 view_data_.rect = PP_FromGfxRect(window);
1230 view_data_.clip_rect = PP_FromGfxRect(clip);
1231 view_data_.device_scale = container_->deviceScaleFactor();
1232 view_data_.css_scale =
1233 container_->pageZoomFactor() * container_->pageScaleFactor();
1235 gfx::Size scroll_offset =
1236 container_->element().document().frame()->scrollOffset();
1237 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1238 scroll_offset.height());
1240 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1241 WebElement element = container_->element();
1242 WebDocument document = element.document();
1243 bool is_fullscreen_element = (element == document.fullScreenElement());
1244 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1245 render_frame()->GetRenderWidget()->is_fullscreen_granted() &&
1246 is_fullscreen_element) {
1247 // Entered fullscreen. Only possible via SetFullscreen().
1248 view_data_.is_fullscreen = true;
1249 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1250 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1251 // so desired_fullscreen_state might be out-of-date.
1252 desired_fullscreen_state_ = false;
1253 view_data_.is_fullscreen = false;
1255 // This operation will cause the plugin to re-layout which will send more
1256 // DidChangeView updates. Schedule an asynchronous update and suppress
1257 // notifications until that completes to avoid sending intermediate sizes
1258 // to the plugins.
1259 ScheduleAsyncDidChangeView();
1261 // Reset the size attributes that we hacked to fill in the screen and
1262 // retrigger ViewChanged. Make sure we don't forward duplicates of
1263 // this view to the plugin.
1264 ResetSizeAttributesAfterFullscreen();
1265 return;
1269 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1271 // During plugin initialization, there are often re-layouts. Avoid sending
1272 // intermediate sizes the plugin and throttler.
1273 if (sent_initial_did_change_view_)
1274 SendDidChangeView();
1275 else
1276 ScheduleAsyncDidChangeView();
1279 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1280 if (has_webkit_focus_ == has_focus)
1281 return;
1283 bool old_plugin_focus = PluginHasFocus();
1284 has_webkit_focus_ = has_focus;
1285 if (PluginHasFocus() != old_plugin_focus)
1286 SendFocusChangeNotification();
1289 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1290 if (has_content_area_focus_ == has_focus)
1291 return;
1293 bool old_plugin_focus = PluginHasFocus();
1294 has_content_area_focus_ = has_focus;
1295 if (PluginHasFocus() != old_plugin_focus)
1296 SendFocusChangeNotification();
1299 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1300 if (is_visible == view_data_.is_page_visible)
1301 return; // Nothing to do.
1302 view_data_.is_page_visible = is_visible;
1304 // If the initial DidChangeView notification hasn't been sent to the plugin,
1305 // let it pass the visibility state for us, instead of sending a notification
1306 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1307 // hasn't been called for the first time. In that case, most of the fields in
1308 // |view_data_| haven't been properly initialized.
1309 if (sent_initial_did_change_view_)
1310 SendDidChangeView();
1313 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1314 if (bound_graphics_2d_platform_)
1315 bound_graphics_2d_platform_->ViewInitiatedPaint();
1316 else if (bound_graphics_3d_.get())
1317 bound_graphics_3d_->ViewInitiatedPaint();
1318 else if (bound_compositor_)
1319 bound_compositor_->ViewInitiatedPaint();
1322 void PepperPluginInstanceImpl::SetSelectedText(
1323 const base::string16& selected_text) {
1324 selected_text_ = selected_text;
1325 gfx::Range range(0, selected_text.length());
1326 render_frame_->SetSelectedText(selected_text, 0, range);
1329 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1330 link_under_cursor_ = base::UTF8ToUTF16(url);
1333 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1334 text_input_type_ = type;
1335 render_frame_->PepperTextInputTypeChanged(this);
1338 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1339 if (message_channel_)
1340 message_channel_->PostMessageToJavaScript(message);
1343 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1344 PP_Instance instance,
1345 void* user_data,
1346 const PPP_MessageHandler_0_2* handler,
1347 PP_Resource message_loop) {
1348 // Not supported in-process.
1349 NOTIMPLEMENTED();
1350 return PP_ERROR_FAILED;
1353 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1354 // Not supported in-process.
1355 NOTIMPLEMENTED();
1358 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1359 return selected_text_;
1362 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1363 const gfx::Point& point) {
1364 // Keep a reference on the stack. See NOTE above.
1365 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1366 if (!LoadPdfInterface()) {
1367 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1368 // return |link_under_cursor_| here because this is only ever called with
1369 // the current mouse coordinates.
1370 return link_under_cursor_;
1373 PP_Point p;
1374 p.x = point.x();
1375 p.y = point.y();
1376 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1377 // If the plugin returns undefined for this function it has switched to
1378 // providing us with the link under the cursor eagerly.
1379 if (rv.type == PP_VARTYPE_UNDEFINED)
1380 return link_under_cursor_;
1381 StringVar* string = StringVar::FromPPVar(rv);
1382 base::string16 link;
1383 if (string)
1384 link = base::UTF8ToUTF16(string->value());
1385 // Release the ref the plugin transfered to us.
1386 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1387 return link;
1390 void PepperPluginInstanceImpl::RequestSurroundingText(
1391 size_t desired_number_of_characters) {
1392 // Keep a reference on the stack. See NOTE above.
1393 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1394 if (!LoadTextInputInterface())
1395 return;
1396 plugin_textinput_interface_->RequestSurroundingText(
1397 pp_instance(), desired_number_of_characters);
1400 bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1401 bool case_sensitive,
1402 int identifier) {
1403 // Keep a reference on the stack. See NOTE above.
1404 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1405 if (!LoadFindInterface())
1406 return false;
1407 find_identifier_ = identifier;
1408 return PP_ToBool(
1409 plugin_find_interface_->StartFind(pp_instance(),
1410 base::UTF16ToUTF8(search_text).c_str(),
1411 PP_FromBool(case_sensitive)));
1414 void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1415 // Keep a reference on the stack. See NOTE above.
1416 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1417 if (LoadFindInterface())
1418 plugin_find_interface_->SelectFindResult(pp_instance(),
1419 PP_FromBool(forward));
1422 void PepperPluginInstanceImpl::StopFind() {
1423 // Keep a reference on the stack. See NOTE above.
1424 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1425 if (!LoadFindInterface())
1426 return;
1427 find_identifier_ = -1;
1428 plugin_find_interface_->StopFind(pp_instance());
1431 bool PepperPluginInstanceImpl::LoadFindInterface() {
1432 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1433 return false;
1434 if (!plugin_find_interface_) {
1435 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1436 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1439 return !!plugin_find_interface_;
1442 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1443 if (!checked_for_plugin_input_event_interface_) {
1444 checked_for_plugin_input_event_interface_ = true;
1445 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1446 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1448 return !!plugin_input_event_interface_;
1451 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1452 if (!plugin_mouse_lock_interface_) {
1453 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1454 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1457 return !!plugin_mouse_lock_interface_;
1460 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1461 if (!checked_for_plugin_pdf_interface_) {
1462 checked_for_plugin_pdf_interface_ = true;
1463 plugin_pdf_interface_ = static_cast<const PPP_Pdf*>(
1464 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1467 return !!plugin_pdf_interface_;
1470 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1471 // Only check for the interface if the plugin has dev permission.
1472 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1473 return false;
1474 if (!plugin_print_interface_) {
1475 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1476 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1478 return !!plugin_print_interface_;
1481 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1482 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1483 // call GetInstanceObject. This is necessary to ensure that the properties
1484 // the trusted plugin exposes (readyState and lastError) work properly. Note
1485 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1486 // so it's correct to never look up PPP_InstancePrivate for them.
1488 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1489 // to the "real" module.
1490 scoped_refptr<PluginModule> module =
1491 original_module_.get() ? original_module_ : module_;
1492 // Only check for the interface if the plugin has private permission.
1493 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1494 return false;
1495 if (!plugin_private_interface_) {
1496 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1497 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1500 return !!plugin_private_interface_;
1503 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1504 if (!plugin_textinput_interface_) {
1505 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1506 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1509 return !!plugin_textinput_interface_;
1512 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1513 if (!bound_graphics_2d_platform_ || !texture_layer_.get()) {
1514 // Currently the transform is only applied for Graphics2D.
1515 return;
1517 // Set the UV coordinates of the texture based on the size of the Graphics2D
1518 // context. By default a texture gets scaled to the size of the layer. But
1519 // if the size of the Graphics2D context doesn't match the size of the plugin
1520 // then it will be incorrectly stretched. This also affects how the plugin
1521 // is painted when it is being resized. If the Graphics2D contents are
1522 // stretched when a plugin is resized while waiting for a new frame from the
1523 // plugin to be rendered, then flickering behavior occurs as in
1524 // crbug.com/353453.
1525 gfx::SizeF graphics_2d_size_in_dip =
1526 gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1527 bound_graphics_2d_platform_->GetScale());
1528 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1529 view_data_.rect.size.height);
1531 texture_layer_->SetUV(
1532 gfx::PointF(0.0f, 0.0f),
1533 gfx::PointF(
1534 plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1535 plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1538 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1539 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1542 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1543 // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1544 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1545 // drop its reference, usually the last one. This is similar to possible
1546 // plugin behavior described at the NOTE above Delete().
1547 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1549 if (!render_frame_)
1550 return;
1552 bool has_focus = PluginHasFocus();
1553 render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1555 // instance_interface_ may have been cleared in Delete() if the
1556 // PepperWebPluginImpl is destroyed.
1557 if (instance_interface_)
1558 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1561 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1562 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1563 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1564 container_->requestTouchEventType(
1565 raw_touch
1566 ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1567 : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1570 bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1571 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1572 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1575 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1576 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1577 return; // Already scheduled.
1578 base::ThreadTaskRunnerHandle::Get()->PostTask(
1579 FROM_HERE, base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1580 view_change_weak_ptr_factory_.GetWeakPtr()));
1583 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1584 // The bound callback that owns the weak pointer is still valid until after
1585 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1586 // invalidate them here.
1587 // NOTE: If we ever want to have more than one pending callback, it should
1588 // use a different factory, or we should have a different strategy here.
1589 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1590 SendDidChangeView();
1593 void PepperPluginInstanceImpl::SendDidChangeView() {
1594 // An asynchronous view update is scheduled. Skip sending this update.
1595 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1596 return;
1598 // Don't send DidChangeView to crashed plugins.
1599 if (module()->is_crashed())
1600 return;
1602 // During the first view update, initialize the throttler.
1603 if (!sent_initial_did_change_view_) {
1604 if (is_flash_plugin_ && RenderThread::Get()) {
1605 RenderThread::Get()->RecordAction(
1606 base::UserMetricsAction("Flash.PluginInstanceCreated"));
1607 RecordFlashSizeMetric(unobscured_rect_.width(),
1608 unobscured_rect_.height());
1611 if (throttler_) {
1612 throttler_->Initialize(render_frame_, url::Origin(plugin_url_),
1613 module()->name(), unobscured_rect_.size());
1617 ppapi::ViewData view_data = view_data_;
1619 // When plugin content is throttled, fake the page being offscreen. We cannot
1620 // send empty view data here, as some plugins rely on accurate view data.
1621 if (throttler_ && throttler_->IsThrottled()) {
1622 view_data.is_page_visible = false;
1623 view_data.clip_rect.point.x = 0;
1624 view_data.clip_rect.point.y = 0;
1625 view_data.clip_rect.size.width = 0;
1626 view_data.clip_rect.size.height = 0;
1629 if (sent_initial_did_change_view_ && last_sent_view_data_.Equals(view_data))
1630 return; // Nothing to update.
1632 sent_initial_did_change_view_ = true;
1633 last_sent_view_data_ = view_data;
1634 ScopedPPResource resource(
1635 ScopedPPResource::PassRef(),
1636 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data))
1637 ->GetReference());
1639 UpdateLayerTransform();
1641 if (bound_graphics_2d_platform_ &&
1642 (!view_data.is_page_visible ||
1643 PP_ToGfxRect(view_data.clip_rect).IsEmpty())) {
1644 bound_graphics_2d_platform_->ClearCache();
1647 // It's possible that Delete() has been called but the renderer hasn't
1648 // released its reference to this object yet.
1649 if (instance_interface_) {
1650 instance_interface_->DidChangeView(
1651 pp_instance(), resource, &view_data.rect, &view_data.clip_rect);
1655 void PepperPluginInstanceImpl::ReportGeometry() {
1656 // If this call was delayed, we may have transitioned back to fullscreen in
1657 // the mean time, so only report the geometry if we are actually in normal
1658 // mode.
1659 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1660 container_->reportGeometry();
1663 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1664 PP_PrintOutputFormat_Dev* format) {
1665 // Keep a reference on the stack. See NOTE above.
1666 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1667 if (!LoadPrintInterface())
1668 return false;
1669 uint32_t supported_formats =
1670 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1671 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1672 *format = PP_PRINTOUTPUTFORMAT_PDF;
1673 return true;
1675 return false;
1678 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1679 PP_PrintOutputFormat_Dev format;
1680 return GetPreferredPrintOutputFormat(&format);
1683 bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1684 DCHECK(plugin_print_interface_);
1685 if (!plugin_print_interface_)
1686 return false;
1687 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1690 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1691 // Keep a reference on the stack. See NOTE above.
1692 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1693 PP_PrintOutputFormat_Dev format;
1694 if (!GetPreferredPrintOutputFormat(&format)) {
1695 // PrintBegin should not have been called since SupportsPrintInterface
1696 // would have returned false;
1697 NOTREACHED();
1698 return 0;
1700 int num_pages = 0;
1701 PP_PrintSettings_Dev print_settings;
1702 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1703 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1704 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1705 print_settings.dpi = print_params.printerDPI;
1706 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1707 print_settings.grayscale = PP_FALSE;
1708 print_settings.print_scaling_option =
1709 static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1710 print_settings.format = format;
1711 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1712 if (!num_pages)
1713 return 0;
1714 current_print_settings_ = print_settings;
1715 canvas_.clear();
1716 ranges_.clear();
1717 return num_pages;
1720 void PepperPluginInstanceImpl::PrintPage(int page_number,
1721 blink::WebCanvas* canvas) {
1722 #if defined(ENABLE_PRINTING)
1723 DCHECK(plugin_print_interface_);
1724 PP_PrintPageNumberRange_Dev page_range;
1725 page_range.first_page_number = page_range.last_page_number = page_number;
1726 // The canvas only has a metafile on it for print preview.
1727 bool save_for_later =
1728 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1729 #if defined(OS_MACOSX)
1730 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1731 #endif // defined(OS_MACOSX)
1732 if (save_for_later) {
1733 ranges_.push_back(page_range);
1734 canvas_ = skia::SharePtr(canvas);
1735 } else {
1736 PrintPageHelper(&page_range, 1, canvas);
1738 #endif
1741 void PepperPluginInstanceImpl::PrintPageHelper(
1742 PP_PrintPageNumberRange_Dev* page_ranges,
1743 int num_ranges,
1744 blink::WebCanvas* canvas) {
1745 // Keep a reference on the stack. See NOTE above.
1746 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1747 DCHECK(plugin_print_interface_);
1748 if (!plugin_print_interface_)
1749 return;
1750 PP_Resource print_output = plugin_print_interface_->PrintPages(
1751 pp_instance(), page_ranges, num_ranges);
1752 if (!print_output)
1753 return;
1755 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1756 PrintPDFOutput(print_output, canvas);
1758 // Now we need to release the print output resource.
1759 PluginModule::GetCore()->ReleaseResource(print_output);
1762 void PepperPluginInstanceImpl::PrintEnd() {
1763 // Keep a reference on the stack. See NOTE above.
1764 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1765 if (!ranges_.empty())
1766 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1767 canvas_.clear();
1768 ranges_.clear();
1770 DCHECK(plugin_print_interface_);
1771 if (plugin_print_interface_)
1772 plugin_print_interface_->End(pp_instance());
1774 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1775 #if defined(OS_MACOSX)
1776 last_printed_page_ = NULL;
1777 #endif // defined(OS_MACOSX)
1780 bool PepperPluginInstanceImpl::GetPrintPresetOptionsFromDocument(
1781 blink::WebPrintPresetOptions* preset_options) {
1782 // Keep a reference on the stack. See NOTE above.
1783 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1784 if (!LoadPdfInterface())
1785 return false;
1787 PP_PdfPrintPresetOptions_Dev options;
1788 if (!plugin_pdf_interface_->GetPrintPresetOptionsFromDocument(pp_instance(),
1789 &options)) {
1790 return false;
1793 preset_options->isScalingDisabled = PP_ToBool(options.is_scaling_disabled);
1794 switch (options.duplex) {
1795 case PP_PRIVATEDUPLEXMODE_SIMPLEX:
1796 preset_options->duplexMode = blink::WebSimplex;
1797 break;
1798 case PP_PRIVATEDUPLEXMODE_SHORT_EDGE:
1799 preset_options->duplexMode = blink::WebShortEdge;
1800 break;
1801 case PP_PRIVATEDUPLEXMODE_LONG_EDGE:
1802 preset_options->duplexMode = blink::WebLongEdge;
1803 break;
1804 default:
1805 preset_options->duplexMode = blink::WebUnknownDuplexMode;
1806 break;
1808 preset_options->copies = options.copies;
1809 preset_options->isPageSizeUniform = PP_ToBool(options.is_page_size_uniform);
1810 preset_options->uniformPageSize =
1811 blink::WebSize(options.uniform_page_size.width,
1812 options.uniform_page_size.height);
1814 return true;
1817 bool PepperPluginInstanceImpl::CanRotateView() {
1818 if (!LoadPdfInterface() || module()->is_crashed())
1819 return false;
1821 return true;
1824 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1825 if (!LoadPdfInterface())
1826 return;
1827 PP_PrivatePageTransformType transform_type =
1828 type == WebPlugin::RotationType90Clockwise
1829 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1830 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1831 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1832 // NOTE: plugin instance may have been deleted.
1835 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1836 return fullscreen_container_ != NULL;
1839 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1840 return desired_fullscreen_state_;
1843 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1844 // Keep a reference on the stack. See NOTE above.
1845 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1847 // Check whether we are trying to switch to the state we're already going
1848 // to (i.e. if we're already switching to fullscreen but the fullscreen
1849 // container isn't ready yet, don't do anything more).
1850 if (fullscreen == IsFullscreenOrPending())
1851 return false;
1853 if (!render_frame_)
1854 return false;
1855 if (fullscreen && !render_frame_->render_view()
1856 ->renderer_preferences()
1857 .plugin_fullscreen_allowed)
1858 return false;
1860 // Check whether we are trying to switch while the state is in transition.
1861 // The 2nd request gets dropped while messing up the internal state, so
1862 // disallow this.
1863 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1864 return false;
1866 if (fullscreen && !IsProcessingUserGesture())
1867 return false;
1869 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1870 desired_fullscreen_state_ = fullscreen;
1872 if (fullscreen) {
1873 // Create the user gesture in case we're processing one that's pending.
1874 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1875 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1876 // so we will tweak plugin's attributes to support the expected behavior.
1877 KeepSizeAttributesBeforeFullscreen();
1878 SetSizeAttributesForFullscreen();
1879 container_->element().requestFullScreen();
1880 } else {
1881 container_->element().document().cancelFullScreen();
1883 return true;
1886 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1887 bool flash_fullscreen) {
1888 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1890 if (flash_fullscreen == flash_fullscreen_) {
1891 // Manually clear callback when fullscreen fails with mouselock pending.
1892 if (!flash_fullscreen && is_mouselock_pending)
1893 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1894 return;
1897 UpdateLayer(false);
1899 bool old_plugin_focus = PluginHasFocus();
1900 flash_fullscreen_ = flash_fullscreen;
1901 if (is_mouselock_pending && !IsMouseLocked()) {
1902 if (!IsProcessingUserGesture() &&
1903 !module_->permissions().HasPermission(
1904 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1905 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1906 } else {
1907 // Open a user gesture here so the Webkit user gesture checks will succeed
1908 // for out-of-process plugins.
1909 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1910 if (!LockMouse())
1911 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1915 if (PluginHasFocus() != old_plugin_focus)
1916 SendFocusChangeNotification();
1919 bool PepperPluginInstanceImpl::IsViewAccelerated() {
1920 if (!container_)
1921 return false;
1923 WebDocument document = container_->element().document();
1924 WebLocalFrame* frame = document.frame();
1925 if (!frame)
1926 return false;
1927 WebView* view = frame->view();
1928 if (!view)
1929 return false;
1931 return view->isAcceleratedCompositingActive();
1934 bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1935 blink::WebCanvas* canvas) {
1936 #if defined(ENABLE_PRINTING)
1937 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1938 if (enter.failed())
1939 return false;
1941 BufferAutoMapper mapper(enter.object());
1942 if (!mapper.data() || !mapper.size()) {
1943 NOTREACHED();
1944 return false;
1947 printing::PdfMetafileSkia* metafile =
1948 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1949 if (metafile)
1950 return metafile->InitFromData(mapper.data(), mapper.size());
1952 NOTREACHED();
1953 #endif // ENABLE_PRINTING
1954 return false;
1957 void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
1958 if (!container_)
1959 return;
1961 gpu::Mailbox mailbox;
1962 uint32 sync_point = 0;
1963 if (bound_graphics_3d_.get()) {
1964 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
1965 DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
1967 bool want_3d_layer = !mailbox.IsZero();
1968 bool want_2d_layer = !!bound_graphics_2d_platform_;
1969 bool want_texture_layer = want_3d_layer || want_2d_layer;
1970 bool want_compositor_layer = !!bound_compositor_;
1972 if (throttler_ && throttler_->IsHiddenForPlaceholder()) {
1973 want_3d_layer = false;
1974 want_2d_layer = false;
1975 want_texture_layer = false;
1976 want_compositor_layer = false;
1979 if (!device_changed && (want_texture_layer == !!texture_layer_.get()) &&
1980 (want_3d_layer == layer_is_hardware_) &&
1981 (want_compositor_layer == !!compositor_layer_.get()) &&
1982 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
1983 UpdateLayerTransform();
1984 return;
1987 if (texture_layer_.get() || compositor_layer_.get()) {
1988 if (!layer_bound_to_fullscreen_)
1989 container_->setWebLayer(NULL);
1990 else if (fullscreen_container_)
1991 fullscreen_container_->SetLayer(NULL);
1992 web_layer_.reset();
1993 if (texture_layer_) {
1994 texture_layer_->ClearClient();
1995 texture_layer_ = NULL;
1997 compositor_layer_ = NULL;
2000 if (want_texture_layer) {
2001 bool opaque = false;
2002 if (want_3d_layer) {
2003 DCHECK(bound_graphics_3d_.get());
2004 texture_layer_ = cc::TextureLayer::CreateForMailbox(
2005 cc_blink::WebLayerImpl::LayerSettings(), NULL);
2006 opaque = bound_graphics_3d_->IsOpaque();
2007 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
2008 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
2009 } else {
2010 DCHECK(bound_graphics_2d_platform_);
2011 texture_layer_ = cc::TextureLayer::CreateForMailbox(
2012 cc_blink::WebLayerImpl::LayerSettings(), this);
2013 bound_graphics_2d_platform_->AttachedToNewLayer();
2014 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2015 texture_layer_->SetFlipped(false);
2018 // Ignore transparency in fullscreen, since that's what Flash always
2019 // wants to do, and that lets it not recreate a context if
2020 // wmode=transparent was specified.
2021 opaque = opaque || fullscreen_container_;
2022 texture_layer_->SetContentsOpaque(opaque);
2023 web_layer_.reset(new cc_blink::WebLayerImpl(texture_layer_));
2024 } else if (want_compositor_layer) {
2025 compositor_layer_ = bound_compositor_->layer();
2026 web_layer_.reset(new cc_blink::WebLayerImpl(compositor_layer_));
2029 if (web_layer_) {
2030 if (fullscreen_container_) {
2031 fullscreen_container_->SetLayer(web_layer_.get());
2032 } else {
2033 container_->setWebLayer(web_layer_.get());
2037 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2038 layer_is_hardware_ = want_3d_layer;
2039 UpdateLayerTransform();
2042 bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2043 cc::TextureMailbox* mailbox,
2044 scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2045 bool use_shared_memory) {
2046 if (!bound_graphics_2d_platform_)
2047 return false;
2048 return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2049 release_callback);
2052 void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2054 void PepperPluginInstanceImpl::OnThrottleStateChange() {
2055 SendDidChangeView();
2057 bool is_throttled = throttler_->IsThrottled();
2058 render_frame()->Send(new FrameHostMsg_PluginInstanceThrottleStateChange(
2059 module_->GetPluginChildId(), pp_instance_, is_throttled));
2062 void PepperPluginInstanceImpl::OnHiddenForPlaceholder(bool hidden) {
2063 UpdateLayer(false /* device_changed */);
2066 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2067 DCHECK(live_plugin_objects_.find(plugin_object) ==
2068 live_plugin_objects_.end());
2069 live_plugin_objects_.insert(plugin_object);
2072 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2073 // Don't actually verify that the object is in the set since during module
2074 // deletion we'll be in the process of freeing them.
2075 live_plugin_objects_.erase(plugin_object);
2078 bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2079 PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2080 // Give a lot of slack so tests won't be flaky.
2081 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2082 return pending_user_gesture_token_.hasGestures() &&
2083 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2086 WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2087 if (!IsProcessingUserGesture())
2088 pending_user_gesture_token_ = WebUserGestureToken();
2089 return pending_user_gesture_token_;
2092 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2093 if (TrackedCallback::IsPending(lock_mouse_callback_))
2094 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2097 void PepperPluginInstanceImpl::OnMouseLockLost() {
2098 if (LoadMouseLockInterface())
2099 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2102 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2103 const blink::WebMouseEvent& event) {
2104 // |cursor_info| is ignored since it is hidden when the mouse is locked.
2105 blink::WebCursorInfo cursor_info;
2106 HandleInputEvent(event, &cursor_info);
2109 void PepperPluginInstanceImpl::SimulateInputEvent(
2110 const InputEventData& input_event) {
2111 WebView* web_view = container()->element().document().frame()->view();
2112 if (!web_view) {
2113 NOTREACHED();
2114 return;
2117 bool handled = SimulateIMEEvent(input_event);
2118 if (handled)
2119 return;
2121 std::vector<linked_ptr<WebInputEvent> > events =
2122 CreateSimulatedWebInputEvents(
2123 input_event,
2124 view_data_.rect.point.x + view_data_.rect.size.width / 2,
2125 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2126 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2127 it != events.end();
2128 ++it) {
2129 web_view->handleInputEvent(*it->get());
2133 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2134 const InputEventData& input_event) {
2135 switch (input_event.event_type) {
2136 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2137 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2138 SimulateImeSetCompositionEvent(input_event);
2139 break;
2140 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2141 DCHECK(input_event.character_text.empty());
2142 SimulateImeSetCompositionEvent(input_event);
2143 break;
2144 case PP_INPUTEVENT_TYPE_IME_TEXT:
2145 if (!render_frame_)
2146 return false;
2147 render_frame_->SimulateImeConfirmComposition(
2148 base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2149 break;
2150 default:
2151 return false;
2153 return true;
2156 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2157 const InputEventData& input_event) {
2158 if (!render_frame_)
2159 return;
2161 std::vector<size_t> offsets;
2162 offsets.push_back(input_event.composition_selection_start);
2163 offsets.push_back(input_event.composition_selection_end);
2164 offsets.insert(offsets.end(),
2165 input_event.composition_segment_offsets.begin(),
2166 input_event.composition_segment_offsets.end());
2168 base::string16 utf16_text =
2169 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2171 std::vector<blink::WebCompositionUnderline> underlines;
2172 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2173 blink::WebCompositionUnderline underline;
2174 underline.startOffset = offsets[i];
2175 underline.endOffset = offsets[i + 1];
2176 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2177 underline.thick = true;
2178 underlines.push_back(underline);
2181 render_frame_->SimulateImeSetComposition(
2182 utf16_text, underlines, offsets[0], offsets[1]);
2185 ContentDecryptorDelegate*
2186 PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2187 if (content_decryptor_delegate_)
2188 return content_decryptor_delegate_.get();
2190 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2191 static_cast<const PPP_ContentDecryptor_Private*>(
2192 module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2193 if (!plugin_decryption_interface)
2194 return NULL;
2196 content_decryptor_delegate_.reset(
2197 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2198 return content_decryptor_delegate_.get();
2201 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2202 PP_Resource device) {
2203 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2204 // The Graphics3D instance can't be destroyed until we call
2205 // UpdateLayer().
2206 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2207 if (bound_graphics_3d_.get()) {
2208 bound_graphics_3d_->BindToInstance(false);
2209 bound_graphics_3d_ = NULL;
2211 if (bound_graphics_2d_platform_) {
2212 bound_graphics_2d_platform_->BindToInstance(NULL);
2213 bound_graphics_2d_platform_ = NULL;
2215 if (bound_compositor_) {
2216 bound_compositor_->BindToInstance(NULL);
2217 bound_compositor_ = NULL;
2220 // Special-case clearing the current device.
2221 if (!device) {
2222 UpdateLayer(true);
2223 InvalidateRect(gfx::Rect());
2224 return PP_TRUE;
2227 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2228 // to/from fullscreen with PPB_Fullscreen.
2229 if ((fullscreen_container_ && !flash_fullscreen_) ||
2230 desired_fullscreen_state_ != view_data_.is_fullscreen)
2231 return PP_FALSE;
2233 const ppapi::host::PpapiHost* ppapi_host =
2234 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2235 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2236 PepperGraphics2DHost* graphics_2d = NULL;
2237 PepperCompositorHost* compositor = NULL;
2238 if (host) {
2239 if (host->IsGraphics2DHost()) {
2240 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2241 } else if (host->IsCompositorHost()) {
2242 compositor = static_cast<PepperCompositorHost*>(host);
2243 } else {
2244 DLOG(ERROR) <<
2245 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2249 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2250 PPB_Graphics3D_Impl* graphics_3d =
2251 enter_3d.succeeded()
2252 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2253 : NULL;
2255 if (compositor) {
2256 if (compositor->BindToInstance(this)) {
2257 bound_compositor_ = compositor;
2258 UpdateLayer(true);
2259 return PP_TRUE;
2261 } else if (graphics_2d) {
2262 if (graphics_2d->BindToInstance(this)) {
2263 bound_graphics_2d_platform_ = graphics_2d;
2264 UpdateLayer(true);
2265 return PP_TRUE;
2267 } else if (graphics_3d) {
2268 // Make sure graphics can only be bound to the instance it is
2269 // associated with.
2270 if (graphics_3d->pp_instance() == pp_instance() &&
2271 graphics_3d->BindToInstance(true)) {
2272 bound_graphics_3d_ = graphics_3d;
2273 UpdateLayer(true);
2274 return PP_TRUE;
2278 // The instance cannot be bound or the device is not a valid resource type.
2279 return PP_FALSE;
2282 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2283 return PP_FromBool(full_frame());
2286 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2287 return &view_data_;
2290 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2291 return PP_FromBool(flash_fullscreen_);
2294 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2295 if (!container_)
2296 return PP_MakeUndefined();
2297 RecordFlashJavaScriptUse();
2298 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2299 PepperTryCatchVar try_catch(this, &converter, NULL);
2300 WebLocalFrame* frame = container_->element().document().frame();
2301 if (!frame) {
2302 try_catch.SetException("No frame exists for window object.");
2303 return PP_MakeUndefined();
2306 ScopedPPVar result =
2307 try_catch.FromV8(frame->mainWorldScriptContext()->Global());
2308 DCHECK(!try_catch.HasException());
2309 return result.Release();
2312 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2313 if (!container_)
2314 return PP_MakeUndefined();
2315 RecordFlashJavaScriptUse();
2316 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2317 PepperTryCatchVar try_catch(this, &converter, NULL);
2318 ScopedPPVar result = try_catch.FromV8(container_->v8ObjectForElement());
2319 DCHECK(!try_catch.HasException());
2320 return result.Release();
2323 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2324 PP_Var script_var,
2325 PP_Var* exception) {
2326 if (!container_)
2327 return PP_MakeUndefined();
2328 if (is_deleted_ && blink::WebPluginScriptForbiddenScope::isForbidden())
2329 return PP_MakeUndefined();
2330 RecordFlashJavaScriptUse();
2332 // Executing the script may remove the plugin from the DOM, so we need to keep
2333 // a reference to ourselves so that we can still process the result after the
2334 // WebBindings::evaluate() below.
2335 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2336 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2337 PepperTryCatchVar try_catch(this, &converter, exception);
2339 // Check for an exception due to the context being destroyed.
2340 if (try_catch.HasException())
2341 return PP_MakeUndefined();
2343 WebLocalFrame* frame = container_->element().document().frame();
2344 if (!frame) {
2345 try_catch.SetException("No frame to execute script in.");
2346 return PP_MakeUndefined();
2349 StringVar* script_string_var = StringVar::FromPPVar(script_var);
2350 if (!script_string_var) {
2351 try_catch.SetException("Script param to ExecuteScript must be a string.");
2352 return PP_MakeUndefined();
2355 std::string script_string = script_string_var->value();
2356 blink::WebScriptSource script(
2357 blink::WebString::fromUTF8(script_string.c_str()));
2358 v8::Local<v8::Value> result;
2359 if (IsProcessingUserGesture()) {
2360 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2361 result = frame->executeScriptAndReturnValue(script);
2362 } else {
2363 result = frame->executeScriptAndReturnValue(script);
2366 ScopedPPVar var_result = try_catch.FromV8(result);
2367 if (try_catch.HasException())
2368 return PP_MakeUndefined();
2370 return var_result.Release();
2373 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2374 PP_Instance instance) {
2375 RenderThreadImpl* thread = RenderThreadImpl::current();
2376 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2379 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2380 PP_Instance instance) {
2381 RenderThreadImpl* thread = RenderThreadImpl::current();
2382 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2385 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2386 if (!render_frame_)
2387 return PP_MakeUndefined();
2388 return StringVar::StringToPPVar(
2389 render_frame_->render_view()->webkit_preferences().default_encoding);
2392 // These PPB_ContentDecryptor_Private calls are responses to
2393 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2394 // Therefore, |content_decryptor_delegate_| must have been initialized when
2395 // the following methods are called.
2396 void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2397 uint32 promise_id) {
2398 content_decryptor_delegate_->OnPromiseResolved(promise_id);
2401 void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2402 PP_Instance instance,
2403 uint32 promise_id,
2404 PP_Var session_id_var) {
2405 content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2406 session_id_var);
2409 void PepperPluginInstanceImpl::PromiseRejected(
2410 PP_Instance instance,
2411 uint32 promise_id,
2412 PP_CdmExceptionCode exception_code,
2413 uint32 system_code,
2414 PP_Var error_description_var) {
2415 content_decryptor_delegate_->OnPromiseRejected(
2416 promise_id, exception_code, system_code, error_description_var);
2419 void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2420 PP_Var session_id_var,
2421 PP_CdmMessageType message_type,
2422 PP_Var message_var,
2423 PP_Var legacy_destination_url) {
2424 content_decryptor_delegate_->OnSessionMessage(
2425 session_id_var, message_type, message_var, legacy_destination_url);
2428 void PepperPluginInstanceImpl::SessionKeysChange(
2429 PP_Instance instance,
2430 PP_Var session_id_var,
2431 PP_Bool has_additional_usable_key,
2432 uint32_t key_count,
2433 const struct PP_KeyInformation key_information[]) {
2434 content_decryptor_delegate_->OnSessionKeysChange(
2435 session_id_var, has_additional_usable_key, key_count, key_information);
2438 void PepperPluginInstanceImpl::SessionExpirationChange(
2439 PP_Instance instance,
2440 PP_Var session_id_var,
2441 PP_Time new_expiry_time) {
2442 content_decryptor_delegate_->OnSessionExpirationChange(session_id_var,
2443 new_expiry_time);
2446 void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2447 PP_Var session_id_var) {
2448 content_decryptor_delegate_->OnSessionClosed(session_id_var);
2451 void PepperPluginInstanceImpl::LegacySessionError(
2452 PP_Instance instance,
2453 PP_Var session_id_var,
2454 PP_CdmExceptionCode exception_code,
2455 uint32 system_code,
2456 PP_Var error_description_var) {
2457 content_decryptor_delegate_->OnLegacySessionError(
2458 session_id_var, exception_code, system_code, error_description_var);
2461 void PepperPluginInstanceImpl::DeliverBlock(
2462 PP_Instance instance,
2463 PP_Resource decrypted_block,
2464 const PP_DecryptedBlockInfo* block_info) {
2465 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2468 void PepperPluginInstanceImpl::DecoderInitializeDone(
2469 PP_Instance instance,
2470 PP_DecryptorStreamType decoder_type,
2471 uint32_t request_id,
2472 PP_Bool success) {
2473 content_decryptor_delegate_->DecoderInitializeDone(
2474 decoder_type, request_id, success);
2477 void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2478 PP_Instance instance,
2479 PP_DecryptorStreamType decoder_type,
2480 uint32_t request_id) {
2481 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2482 request_id);
2485 void PepperPluginInstanceImpl::DecoderResetDone(
2486 PP_Instance instance,
2487 PP_DecryptorStreamType decoder_type,
2488 uint32_t request_id) {
2489 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2492 void PepperPluginInstanceImpl::DeliverFrame(
2493 PP_Instance instance,
2494 PP_Resource decrypted_frame,
2495 const PP_DecryptedFrameInfo* frame_info) {
2496 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2499 void PepperPluginInstanceImpl::DeliverSamples(
2500 PP_Instance instance,
2501 PP_Resource audio_frames,
2502 const PP_DecryptedSampleInfo* sample_info) {
2503 content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2506 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2507 PP_Instance instance) {
2508 if (!LoadFindInterface())
2509 return;
2510 bool is_main_frame =
2511 render_frame_ &&
2512 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2513 if (!is_main_frame)
2514 return;
2515 render_frame_->render_view()->set_plugin_find_handler(this);
2518 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2519 PP_Instance instance,
2520 int32_t total,
2521 PP_Bool final_result) {
2522 DCHECK_NE(find_identifier_, -1);
2523 if (render_frame_) {
2524 render_frame_->reportFindInPageMatchCount(
2525 find_identifier_, total, PP_ToBool(final_result));
2529 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2530 int32_t index) {
2531 DCHECK_NE(find_identifier_, -1);
2532 if (render_frame_) {
2533 render_frame_->reportFindInPageSelection(
2534 find_identifier_, index + 1, blink::WebRect());
2538 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2539 const PP_Rect* tickmarks,
2540 uint32_t count) {
2541 if (!render_frame_ || !render_frame_->GetWebFrame())
2542 return;
2544 blink::WebVector<blink::WebRect> tickmarks_converted(
2545 static_cast<size_t>(count));
2546 for (uint32 i = 0; i < count; ++i) {
2547 tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2548 tickmarks[i].point.y,
2549 tickmarks[i].size.width,
2550 tickmarks[i].size.height);
2552 blink::WebFrame* frame = render_frame_->GetWebFrame();
2553 frame->setTickmarks(tickmarks_converted);
2556 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2557 return PP_FromBool(view_data_.is_fullscreen);
2560 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2561 PP_Bool fullscreen) {
2562 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2565 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2566 PP_Size* size) {
2567 if (flash_fullscreen_) {
2568 // Workaround for Flash rendering bug: Flash is assuming the fullscreen view
2569 // size will be equal to the physical screen size. However, the fullscreen
2570 // view is sized by the browser UI, and may not be the same size as the
2571 // screen or the desktop. Therefore, report the view size as the screen
2572 // size when in fullscreen mode. http://crbug.com/506016
2573 // TODO(miu): Remove this workaround once Flash has been fixed.
2574 *size = view_data_.rect.size;
2575 } else {
2576 // All other cases: Report the screen size.
2577 blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2578 *size = PP_MakeSize(info.rect.width, info.rect.height);
2580 return PP_TRUE;
2583 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2584 PP_Instance instance,
2585 ppapi::SingletonResourceID id) {
2586 // Flash APIs and some others aren't implemented in-process.
2587 switch (id) {
2588 case ppapi::BROKER_SINGLETON_ID:
2589 case ppapi::BROWSER_FONT_SINGLETON_ID:
2590 case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2591 case ppapi::FLASH_FILE_SINGLETON_ID:
2592 case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2593 case ppapi::FLASH_SINGLETON_ID:
2594 case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2595 case ppapi::NETWORK_PROXY_SINGLETON_ID:
2596 case ppapi::PDF_SINGLETON_ID:
2597 case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2598 NOTIMPLEMENTED();
2599 return NULL;
2600 case ppapi::GAMEPAD_SINGLETON_ID:
2601 return gamepad_impl_.get();
2602 case ppapi::UMA_SINGLETON_ID: {
2603 if (!uma_private_impl_.get()) {
2604 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2605 if (host_impl->in_process_router()) {
2606 uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2607 host_impl->in_process_router()->GetPluginConnection(instance),
2608 instance);
2611 return uma_private_impl_.get();
2615 NOTREACHED();
2616 return NULL;
2619 int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2620 uint32_t event_classes) {
2621 input_event_mask_ |= event_classes;
2622 filtered_input_event_mask_ &= ~(event_classes);
2623 RequestInputEventsHelper(event_classes);
2624 return ValidateRequestInputEvents(false, event_classes);
2627 int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2628 PP_Instance instance,
2629 uint32_t event_classes) {
2630 filtered_input_event_mask_ |= event_classes;
2631 input_event_mask_ &= ~(event_classes);
2632 RequestInputEventsHelper(event_classes);
2633 return ValidateRequestInputEvents(true, event_classes);
2636 void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2637 uint32_t event_classes) {
2638 input_event_mask_ &= ~(event_classes);
2639 filtered_input_event_mask_ &= ~(event_classes);
2640 RequestInputEventsHelper(event_classes);
2643 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2644 PP_Var message) {
2645 PostMessageToJavaScript(message);
2648 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2649 PP_MouseCursor_Type type,
2650 PP_Resource image,
2651 const PP_Point* hot_spot) {
2652 if (!ValidateSetCursorParams(type, image, hot_spot))
2653 return PP_FALSE;
2655 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2656 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2657 return PP_TRUE;
2660 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2661 if (enter.failed())
2662 return PP_FALSE;
2663 PPB_ImageData_Impl* image_data =
2664 static_cast<PPB_ImageData_Impl*>(enter.object());
2666 ImageDataAutoMapper auto_mapper(image_data);
2667 if (!auto_mapper.is_valid())
2668 return PP_FALSE;
2670 scoped_ptr<WebCursorInfo> custom_cursor(
2671 new WebCursorInfo(WebCursorInfo::TypeCustom));
2672 custom_cursor->hotSpot.x = hot_spot->x;
2673 custom_cursor->hotSpot.y = hot_spot->y;
2675 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2676 // Make a deep copy, so that the cursor remains valid even after the original
2677 // image data gets freed.
2678 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2679 return PP_FALSE;
2682 DoSetCursor(custom_cursor.release());
2683 return PP_TRUE;
2686 int32_t PepperPluginInstanceImpl::LockMouse(
2687 PP_Instance instance,
2688 scoped_refptr<TrackedCallback> callback) {
2689 if (TrackedCallback::IsPending(lock_mouse_callback_))
2690 return PP_ERROR_INPROGRESS;
2692 if (IsMouseLocked())
2693 return PP_OK;
2695 if (!CanAccessMainFrame())
2696 return PP_ERROR_NOACCESS;
2698 if (!IsProcessingUserGesture())
2699 return PP_ERROR_NO_USER_GESTURE;
2701 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2702 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2703 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2704 // Open a user gesture here so the Webkit user gesture checks will succeed
2705 // for out-of-process plugins.
2706 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2707 if (!LockMouse())
2708 return PP_ERROR_FAILED;
2711 // Either mouselock succeeded or a Flash fullscreen is pending.
2712 lock_mouse_callback_ = callback;
2713 return PP_OK_COMPLETIONPENDING;
2716 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2717 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2720 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2721 PP_TextInput_Type type) {
2722 if (!render_frame_)
2723 return;
2724 int itype = type;
2725 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2726 itype = ui::TEXT_INPUT_TYPE_NONE;
2727 SetTextInputType(static_cast<ui::TextInputType>(itype));
2730 void PepperPluginInstanceImpl::UpdateCaretPosition(
2731 PP_Instance instance,
2732 const PP_Rect& caret,
2733 const PP_Rect& bounding_box) {
2734 if (!render_frame_)
2735 return;
2736 text_input_caret_ = PP_ToGfxRect(caret);
2737 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2738 text_input_caret_set_ = true;
2739 render_frame_->PepperCaretPositionChanged(this);
2742 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2743 if (render_frame_)
2744 render_frame_->PepperCancelComposition(this);
2747 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2748 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2749 // It can be optimized so that it won't call it back until the information
2750 // is really needed.
2752 // Avoid calling in nested context or else this will reenter the plugin. This
2753 // uses a weak pointer rather than exploiting the fact that this class is
2754 // refcounted because we don't actually want this operation to affect the
2755 // lifetime of the instance.
2756 base::ThreadTaskRunnerHandle::Get()->PostTask(
2757 FROM_HERE, base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2758 weak_factory_.GetWeakPtr(),
2759 static_cast<size_t>(kExtraCharsForTextInput)));
2762 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2763 const char* text,
2764 uint32_t caret,
2765 uint32_t anchor) {
2766 if (!render_frame_)
2767 return;
2768 surrounding_text_ = text;
2769 selection_caret_ = caret;
2770 selection_anchor_ = anchor;
2771 render_frame_->PepperSelectionChanged(this);
2774 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2775 PP_Instance instance,
2776 PP_Var relative,
2777 PP_URLComponents_Dev* components) {
2778 StringVar* relative_string = StringVar::FromPPVar(relative);
2779 if (!relative_string)
2780 return PP_MakeNull();
2782 WebElement plugin_element = container()->element();
2783 GURL document_url = plugin_element.document().baseURL();
2784 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2785 document_url.Resolve(relative_string->value()), components);
2788 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2789 PP_Var url) {
2790 StringVar* url_string = StringVar::FromPPVar(url);
2791 if (!url_string)
2792 return PP_FALSE;
2794 blink::WebSecurityOrigin security_origin;
2795 if (!SecurityOriginForInstance(instance, &security_origin))
2796 return PP_FALSE;
2798 GURL gurl(url_string->value());
2799 if (!gurl.is_valid())
2800 return PP_FALSE;
2802 return PP_FromBool(security_origin.canRequest(gurl));
2805 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2806 PP_Instance instance,
2807 PP_Instance target) {
2808 blink::WebSecurityOrigin our_origin;
2809 if (!SecurityOriginForInstance(instance, &our_origin))
2810 return PP_FALSE;
2812 blink::WebSecurityOrigin target_origin;
2813 if (!SecurityOriginForInstance(instance, &target_origin))
2814 return PP_FALSE;
2816 return PP_FromBool(our_origin.canAccess(target_origin));
2819 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2820 PP_Instance instance,
2821 PP_URLComponents_Dev* components) {
2822 blink::WebDocument document = container()->element().document();
2823 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2824 components);
2827 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2828 PP_Instance instance,
2829 PP_URLComponents_Dev* components) {
2830 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2833 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2834 PP_Instance instance,
2835 PP_URLComponents_Dev* components) {
2836 blink::WebDocument document = container()->element().document();
2837 if (!full_frame_)
2838 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2839 components);
2840 WebLocalFrame* frame = document.frame();
2841 if (!frame)
2842 return PP_MakeUndefined();
2843 const WebURLRequest& request = frame->dataSource()->originalRequest();
2844 WebString referer = request.httpHeaderField("Referer");
2845 if (referer.isEmpty())
2846 return PP_MakeUndefined();
2847 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2848 components);
2851 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2852 scoped_refptr<PluginModule> module) {
2853 // Save the original module and switch over to the new one now that this
2854 // plugin is using the IPC-based proxy.
2855 original_module_ = module_;
2856 module_ = module;
2858 // For NaCl instances, remember the NaCl plugin instance interface, so we
2859 // can shut it down by calling its DidDestroy in our Delete() method.
2860 original_instance_interface_.reset(instance_interface_.release());
2862 base::Callback<const void*(const char*)> get_plugin_interface_func =
2863 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2864 PPP_Instance_Combined* ppp_instance_combined =
2865 PPP_Instance_Combined::Create(get_plugin_interface_func);
2866 if (!ppp_instance_combined) {
2867 // The proxy must support at least one usable PPP_Instance interface.
2868 // While this could be a failure to implement the interface in the NaCl
2869 // module, it is more likely that the NaCl process has crashed. Either
2870 // way, report that module initialization failed.
2871 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2874 instance_interface_.reset(ppp_instance_combined);
2875 // Clear all PPP interfaces we may have cached.
2876 plugin_find_interface_ = NULL;
2877 plugin_input_event_interface_ = NULL;
2878 checked_for_plugin_input_event_interface_ = false;
2879 plugin_mouse_lock_interface_ = NULL;
2880 plugin_pdf_interface_ = NULL;
2881 checked_for_plugin_pdf_interface_ = false;
2882 plugin_private_interface_ = NULL;
2883 plugin_textinput_interface_ = NULL;
2885 // Re-send the DidCreate event via the proxy.
2886 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2887 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2888 if (!instance_interface_->DidCreate(
2889 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2890 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2891 if (message_channel_)
2892 message_channel_->Start();
2894 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2895 // event. This way, SendDidChangeView will send the "current" view
2896 // immediately (before other events like HandleDocumentLoad).
2897 sent_initial_did_change_view_ = false;
2898 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2899 SendDidChangeView();
2901 DCHECK(external_document_load_);
2902 external_document_load_ = false;
2903 if (!external_document_response_.isNull()) {
2904 document_loader_ = NULL;
2905 // Pass the response to the new proxy.
2906 HandleDocumentLoad(external_document_response_);
2907 external_document_response_ = blink::WebURLResponse();
2908 // Replay any document load events we've received to the real loader.
2909 external_document_loader_->ReplayReceivedData(document_loader_);
2910 external_document_loader_.reset(NULL);
2913 return PP_EXTERNAL_PLUGIN_OK;
2916 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2917 DCHECK(module);
2918 return module == module_.get() || module == original_module_.get();
2921 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2922 return HostGlobals::Get()->GetInstance(instance_id);
2925 RenderView* PepperPluginInstanceImpl::GetRenderView() {
2926 return render_frame_ ? render_frame_->render_view() : NULL;
2929 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2930 return container_;
2933 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
2935 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
2936 return HostGlobals::Get()->GetVarTracker();
2939 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
2941 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
2942 return module_->path();
2945 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
2946 float scale) {
2947 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
2949 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
2950 return 0;
2952 scoped_refptr<PPB_ImageData_Impl> image_data(
2953 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
2954 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
2955 image_skia_rep.pixel_width(),
2956 image_skia_rep.pixel_height(),
2957 false)) {
2958 return 0;
2961 ImageDataAutoMapper mapper(image_data.get());
2962 if (!mapper.is_valid())
2963 return 0;
2965 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
2966 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
2967 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
2968 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
2970 return image_data->GetReference();
2973 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
2974 const base::FilePath& file_path,
2975 ppapi::PpapiPermissions permissions,
2976 const IPC::ChannelHandle& channel_handle,
2977 base::ProcessId plugin_pid,
2978 int plugin_child_id) {
2979 // Create a new module for each instance of the external plugin that is using
2980 // the IPC based out-of-process proxy. We can't use the existing module,
2981 // because it is configured for the in-process plugin, and we must keep it
2982 // that way to allow the page to create other instances.
2983 scoped_refptr<PluginModule> external_plugin_module(
2984 module_->CreateModuleForExternalPluginInstance());
2986 RendererPpapiHostImpl* renderer_ppapi_host =
2987 external_plugin_module->CreateOutOfProcessModule(render_frame_,
2988 file_path,
2989 permissions,
2990 channel_handle,
2991 plugin_pid,
2992 plugin_child_id,
2993 true);
2994 if (!renderer_ppapi_host) {
2995 DLOG(ERROR) << "CreateExternalPluginModule() failed";
2996 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2999 // Finally, switch the instance to the proxy.
3000 return external_plugin_module->InitAsProxiedExternalPlugin(this);
3003 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3004 always_on_top_ = on_top;
3007 void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
3008 cursor_.reset(cursor);
3009 if (fullscreen_container_) {
3010 fullscreen_container_->DidChangeCursor(*cursor);
3011 } else if (render_frame_) {
3012 render_frame_->PepperDidChangeCursor(this, *cursor);
3016 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3017 WebLocalFrame* frame = container()->element().document().frame();
3018 return frame->view()->mainFrame()->isWebLocalFrame() &&
3019 frame->view()->mainFrame()->document().isPluginDocument();
3022 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3023 bool delay_report) {
3024 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3025 // Keep a reference on the stack. See NOTE above.
3026 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3028 // We check whether we are trying to switch to the state we're already going
3029 // to (i.e. if we're already switching to fullscreen but the fullscreen
3030 // container isn't ready yet, don't do anything more).
3031 if (fullscreen == FlashIsFullscreenOrPending())
3032 return true;
3034 if (!render_frame_)
3035 return false;
3036 if (fullscreen && !render_frame_->render_view()
3037 ->renderer_preferences()
3038 .plugin_fullscreen_allowed)
3039 return false;
3041 // Unbind current 2D or 3D graphics context.
3042 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3043 if (fullscreen) {
3044 DCHECK(!fullscreen_container_);
3045 fullscreen_container_ =
3046 render_frame_->CreatePepperFullscreenContainer(this);
3047 UpdateLayer(false);
3048 } else {
3049 DCHECK(fullscreen_container_);
3050 fullscreen_container_->Destroy();
3051 fullscreen_container_ = NULL;
3052 UpdateFlashFullscreenState(false);
3053 if (!delay_report) {
3054 ReportGeometry();
3055 } else {
3056 base::ThreadTaskRunnerHandle::Get()->PostTask(
3057 FROM_HERE,
3058 base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3062 return true;
3065 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3066 if (flash_fullscreen_)
3067 return true;
3069 return container_->isRectTopmost(rect);
3072 int32_t PepperPluginInstanceImpl::Navigate(
3073 const ppapi::URLRequestInfoData& request,
3074 const char* target,
3075 bool from_user_action) {
3076 if (!container_)
3077 return PP_ERROR_FAILED;
3079 WebDocument document = container_->element().document();
3080 WebLocalFrame* frame = document.frame();
3081 if (!frame)
3082 return PP_ERROR_FAILED;
3084 ppapi::URLRequestInfoData completed_request = request;
3086 WebURLRequest web_request;
3087 if (!CreateWebURLRequest(
3088 pp_instance_, &completed_request, frame, &web_request)) {
3089 return PP_ERROR_FAILED;
3091 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3092 if (IsProcessingUserGesture())
3093 web_request.setHasUserGesture(true);
3095 GURL gurl(web_request.url());
3096 if (gurl.SchemeIs(url::kJavaScriptScheme)) {
3097 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3098 // allowed for security reasons.
3099 WebFrame* target_frame =
3100 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3101 if (target_frame != frame)
3102 return PP_ERROR_NOACCESS;
3104 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3105 // need that?
3106 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
3107 WebString result = container_->executeScriptURL(gurl, false);
3108 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3111 // Only GETs and POSTs are supported.
3112 if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3113 return PP_ERROR_BADARGUMENT;
3115 WebString target_str = WebString::fromUTF8(target);
3116 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
3117 container_->loadFrameRequest(web_request, target_str, false, NULL);
3118 return PP_OK;
3121 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3122 const base::FilePath& path) {
3123 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3124 PepperFileRefRendererHost* file_ref_host(
3125 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3126 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3127 scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3130 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3131 if (message_channel_)
3132 message_channel_->SetReadOnlyProperty(key, value);
3135 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3136 if (!container_)
3137 return false;
3138 blink::WebDocument containing_document = container_->element().document();
3140 if (!containing_document.frame() || !containing_document.frame()->view() ||
3141 !containing_document.frame()->view()->mainFrame()) {
3142 return false;
3144 blink::WebDocument main_document =
3145 containing_document.frame()->view()->mainFrame()->document();
3147 return containing_document.securityOrigin().canAccess(
3148 main_document.securityOrigin());
3151 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3152 WebElement element = container_->element();
3153 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3154 height_before_fullscreen_ =
3155 element.getAttribute(WebString::fromUTF8(kHeight));
3156 border_before_fullscreen_ =
3157 element.getAttribute(WebString::fromUTF8(kBorder));
3158 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3161 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3162 if (!render_frame_)
3163 return;
3165 // TODO(miu): Revisit this logic. If the style must be modified for correct
3166 // behavior, the width and height should probably be set to 100%, rather than
3167 // a fixed screen size.
3169 blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3170 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3171 std::string width = base::IntToString(screen_size_for_fullscreen_.width());
3172 std::string height = base::IntToString(screen_size_for_fullscreen_.height());
3174 WebElement element = container_->element();
3175 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3176 element.setAttribute(WebString::fromUTF8(kHeight),
3177 WebString::fromUTF8(height));
3178 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3180 // There should be no style settings that matter in fullscreen mode,
3181 // so just replace them instead of appending.
3182 // NOTE: "position: fixed" and "display: block" reset the plugin and
3183 // using %% settings might not work without them (e.g. if the plugin is a
3184 // child of a container element).
3185 std::string style;
3186 style += StringPrintf("width: %s !important; ", width.c_str());
3187 style += StringPrintf("height: %s !important; ", height.c_str());
3188 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3189 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3192 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3193 screen_size_for_fullscreen_ = gfx::Size();
3194 WebElement element = container_->element();
3195 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3196 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3197 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3198 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3201 bool PepperPluginInstanceImpl::IsMouseLocked() {
3202 return GetMouseLockDispatcher()->IsMouseLockedTo(
3203 GetOrCreateLockTargetAdapter());
3206 bool PepperPluginInstanceImpl::LockMouse() {
3207 return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3210 MouseLockDispatcher::LockTarget*
3211 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3212 if (!lock_target_.get()) {
3213 lock_target_.reset(new PluginInstanceLockTarget(this));
3215 return lock_target_.get();
3218 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3219 if (flash_fullscreen_) {
3220 RenderWidgetFullscreenPepper* container =
3221 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3222 return container->mouse_lock_dispatcher();
3223 } else if (render_frame_) {
3224 return render_frame_->render_view()->mouse_lock_dispatcher();
3226 return NULL;
3229 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3230 if (lock_target_.get()) {
3231 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3232 lock_target_.reset();
3236 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3237 const blink::WebURLResponse& response,
3238 int pending_host_id,
3239 const ppapi::URLResponseInfoData& data) {
3240 if (is_deleted_)
3241 return;
3243 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3245 if (host_impl->in_process_router()) {
3246 // Running in-process, we can just create the resource and call the
3247 // PPP_Instance function directly.
3248 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3249 new ppapi::proxy::URLLoaderResource(
3250 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3251 pp_instance(),
3252 pending_host_id,
3253 data));
3255 PP_Resource loader_pp_resource = loader_resource->GetReference();
3256 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3257 loader_pp_resource))
3258 loader_resource->Close();
3259 // We don't pass a ref into the plugin, if it wants one, it will have taken
3260 // an additional one.
3261 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3262 loader_pp_resource);
3263 } else {
3264 // Running out-of-process. Initiate an IPC call to notify the plugin
3265 // process.
3266 ppapi::proxy::HostDispatcher* dispatcher =
3267 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3268 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3269 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3273 void PepperPluginInstanceImpl::RecordFlashJavaScriptUse() {
3274 if (initialized_ && !javascript_used_ && is_flash_plugin_) {
3275 javascript_used_ = true;
3276 RenderThread::Get()->RecordAction(
3277 base::UserMetricsAction("Flash.JavaScriptUsed"));
3281 } // namespace content