Process Alt-Svc headers.
[chromium-blink-merge.git] / content / renderer / pepper / pepper_plugin_instance_impl.cc
blob10477fff949c13079ebc76b3ef5faa27a4d1889c
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/common/view_messages.h"
27 #include "content/public/common/content_constants.h"
28 #include "content/public/renderer/content_renderer_client.h"
29 #include "content/renderer/pepper/content_decryptor_delegate.h"
30 #include "content/renderer/pepper/event_conversion.h"
31 #include "content/renderer/pepper/fullscreen_container.h"
32 #include "content/renderer/pepper/gfx_conversion.h"
33 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
34 #include "content/renderer/pepper/host_globals.h"
35 #include "content/renderer/pepper/message_channel.h"
36 #include "content/renderer/pepper/pepper_browser_connection.h"
37 #include "content/renderer/pepper/pepper_compositor_host.h"
38 #include "content/renderer/pepper/pepper_file_ref_renderer_host.h"
39 #include "content/renderer/pepper/pepper_graphics_2d_host.h"
40 #include "content/renderer/pepper/pepper_in_process_router.h"
41 #include "content/renderer/pepper/pepper_plugin_instance_metrics.h"
42 #include "content/renderer/pepper/pepper_try_catch.h"
43 #include "content/renderer/pepper/pepper_url_loader_host.h"
44 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
45 #include "content/renderer/pepper/plugin_module.h"
46 #include "content/renderer/pepper/plugin_object.h"
47 #include "content/renderer/pepper/ppapi_preferences_builder.h"
48 #include "content/renderer/pepper/ppb_buffer_impl.h"
49 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
50 #include "content/renderer/pepper/ppb_image_data_impl.h"
51 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
52 #include "content/renderer/pepper/url_request_info_util.h"
53 #include "content/renderer/pepper/url_response_info_util.h"
54 #include "content/renderer/render_frame_impl.h"
55 #include "content/renderer/render_thread_impl.h"
56 #include "content/renderer/render_view_impl.h"
57 #include "content/renderer/render_widget.h"
58 #include "content/renderer/render_widget_fullscreen_pepper.h"
59 #include "content/renderer/sad_plugin.h"
60 #include "media/base/audio_hardware_config.h"
61 #include "ppapi/c/dev/ppp_text_input_dev.h"
62 #include "ppapi/c/pp_rect.h"
63 #include "ppapi/c/ppb_audio_config.h"
64 #include "ppapi/c/ppb_core.h"
65 #include "ppapi/c/ppb_gamepad.h"
66 #include "ppapi/c/ppp_input_event.h"
67 #include "ppapi/c/ppp_instance.h"
68 #include "ppapi/c/ppp_messaging.h"
69 #include "ppapi/c/ppp_mouse_lock.h"
70 #include "ppapi/c/private/ppb_find_private.h"
71 #include "ppapi/c/private/ppp_find_private.h"
72 #include "ppapi/c/private/ppp_instance_private.h"
73 #include "ppapi/c/private/ppp_pdf.h"
74 #include "ppapi/host/ppapi_host.h"
75 #include "ppapi/proxy/ppapi_messages.h"
76 #include "ppapi/proxy/serialized_var.h"
77 #include "ppapi/proxy/uma_private_resource.h"
78 #include "ppapi/proxy/url_loader_resource.h"
79 #include "ppapi/shared_impl/ppapi_permissions.h"
80 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
81 #include "ppapi/shared_impl/ppb_input_event_shared.h"
82 #include "ppapi/shared_impl/ppb_url_util_shared.h"
83 #include "ppapi/shared_impl/ppb_view_shared.h"
84 #include "ppapi/shared_impl/ppp_instance_combined.h"
85 #include "ppapi/shared_impl/resource.h"
86 #include "ppapi/shared_impl/scoped_pp_resource.h"
87 #include "ppapi/shared_impl/scoped_pp_var.h"
88 #include "ppapi/shared_impl/time_conversion.h"
89 #include "ppapi/shared_impl/url_request_info_data.h"
90 #include "ppapi/shared_impl/var.h"
91 #include "ppapi/thunk/enter.h"
92 #include "ppapi/thunk/ppb_buffer_api.h"
93 #include "printing/metafile_skia_wrapper.h"
94 #include "printing/pdf_metafile_skia.h"
95 #include "skia/ext/platform_canvas.h"
96 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
97 #include "third_party/WebKit/public/platform/WebGamepads.h"
98 #include "third_party/WebKit/public/platform/WebRect.h"
99 #include "third_party/WebKit/public/platform/WebString.h"
100 #include "third_party/WebKit/public/platform/WebURL.h"
101 #include "third_party/WebKit/public/platform/WebURLError.h"
102 #include "third_party/WebKit/public/platform/WebURLRequest.h"
103 #include "third_party/WebKit/public/web/WebBindings.h"
104 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
105 #include "third_party/WebKit/public/web/WebDataSource.h"
106 #include "third_party/WebKit/public/web/WebDocument.h"
107 #include "third_party/WebKit/public/web/WebInputEvent.h"
108 #include "third_party/WebKit/public/web/WebLocalFrame.h"
109 #include "third_party/WebKit/public/web/WebPluginContainer.h"
110 #include "third_party/WebKit/public/web/WebPluginScriptForbiddenScope.h"
111 #include "third_party/WebKit/public/web/WebPrintParams.h"
112 #include "third_party/WebKit/public/web/WebPrintPresetOptions.h"
113 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
114 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
115 #include "third_party/WebKit/public/web/WebScriptSource.h"
116 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
117 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
118 #include "third_party/WebKit/public/web/WebView.h"
119 #include "third_party/khronos/GLES2/gl2.h"
120 #include "ui/gfx/image/image_skia.h"
121 #include "ui/gfx/image/image_skia_rep.h"
122 #include "ui/gfx/range/range.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);
402 if (error_.get()) {
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_);
420 finished_loading_ = true;
423 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFail(
424 WebURLLoader* loader,
425 const WebURLError& error) {
426 DCHECK(!error_.get());
427 error_.reset(new WebURLError(error));
430 PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
431 : Resource(ppapi::Resource::Untracked()) {}
433 PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
435 PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
436 return this;
439 void PepperPluginInstanceImpl::GamepadImpl::Sample(
440 PP_Instance instance,
441 PP_GamepadsSampleData* data) {
442 blink::WebGamepads webkit_data;
443 RenderThreadImpl::current()->SampleGamepads(&webkit_data);
444 ConvertWebKitGamepadData(bit_cast<ppapi::WebKitGamepads>(webkit_data), data);
447 PepperPluginInstanceImpl::PepperPluginInstanceImpl(
448 RenderFrameImpl* render_frame,
449 PluginModule* module,
450 ppapi::PPP_Instance_Combined* instance_interface,
451 WebPluginContainer* container,
452 const GURL& plugin_url)
453 : RenderFrameObserver(render_frame),
454 render_frame_(render_frame),
455 module_(module),
456 instance_interface_(instance_interface),
457 pp_instance_(0),
458 container_(container),
459 layer_bound_to_fullscreen_(false),
460 layer_is_hardware_(false),
461 plugin_url_(plugin_url),
462 document_url_(container ? GURL(container->element().document().url())
463 : GURL()),
464 is_flash_plugin_(module->name() == kFlashPluginName),
465 has_been_clicked_(false),
466 javascript_used_(false),
467 full_frame_(false),
468 sent_initial_did_change_view_(false),
469 bound_graphics_2d_platform_(NULL),
470 bound_compositor_(NULL),
471 has_webkit_focus_(false),
472 has_content_area_focus_(false),
473 find_identifier_(-1),
474 plugin_find_interface_(NULL),
475 plugin_input_event_interface_(NULL),
476 plugin_mouse_lock_interface_(NULL),
477 plugin_pdf_interface_(NULL),
478 plugin_private_interface_(NULL),
479 plugin_textinput_interface_(NULL),
480 checked_for_plugin_input_event_interface_(false),
481 checked_for_plugin_pdf_interface_(false),
482 gamepad_impl_(new GamepadImpl()),
483 uma_private_impl_(NULL),
484 plugin_print_interface_(NULL),
485 plugin_graphics_3d_interface_(NULL),
486 always_on_top_(false),
487 fullscreen_container_(NULL),
488 flash_fullscreen_(false),
489 desired_fullscreen_state_(false),
490 message_channel_(NULL),
491 sad_plugin_(NULL),
492 input_event_mask_(0),
493 filtered_input_event_mask_(0),
494 text_input_type_(kPluginDefaultTextInputType),
495 text_input_caret_(0, 0, 0, 0),
496 text_input_caret_bounds_(0, 0, 0, 0),
497 text_input_caret_set_(false),
498 selection_caret_(0),
499 selection_anchor_(0),
500 pending_user_gesture_(0.0),
501 document_loader_(NULL),
502 external_document_load_(false),
503 isolate_(v8::Isolate::GetCurrent()),
504 is_deleted_(false),
505 initialized_(false),
506 view_change_weak_ptr_factory_(this),
507 weak_factory_(this) {
508 pp_instance_ = HostGlobals::Get()->AddInstance(this);
510 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
511 module_->InstanceCreated(this);
513 if (render_frame) { // NULL in tests
514 render_frame->render_view()->PepperInstanceCreated(this);
515 // Bind a callback now so that we can inform the RenderViewImpl when we are
516 // destroyed. This works around a temporary problem stemming from work to
517 // move parts of RenderViewImpl in to RenderFrameImpl (see
518 // crbug.com/245126). If destruction happens in this order:
519 // 1) RenderFrameImpl
520 // 2) PepperPluginInstanceImpl
521 // 3) RenderViewImpl
522 // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
523 // to the RenderViewImpl. But when the instance is destroyed, it still
524 // needs to inform the RenderViewImpl that it has gone away, otherwise
525 // between (2) and (3), the RenderViewImpl will still have the dead
526 // instance in its active set, and so might make calls on the deleted
527 // instance. See crbug.com/343576 for more information. Once the plugin
528 // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
529 // can be a little bit simplified by instead making a direct call on
530 // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
531 instance_deleted_callback_ =
532 base::Bind(&RenderViewImpl::PepperInstanceDeleted,
533 render_frame->render_view()->AsWeakPtr(),
534 base::Unretained(this));
535 view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
537 // Set the initial focus.
538 SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
540 if (!module_->IsProxied()) {
541 PepperBrowserConnection* browser_connection =
542 PepperBrowserConnection::Get(render_frame_);
543 browser_connection->DidCreateInProcessInstance(
544 pp_instance(),
545 render_frame_->GetRoutingID(),
546 document_url_,
547 GetPluginURL());
551 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
552 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
554 if (GetContentClient()->renderer() && // NULL in unit tests.
555 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
556 external_document_load_ = true;
559 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
560 DCHECK(!fullscreen_container_);
562 // Notify all the plugin objects of deletion. This will prevent blink from
563 // calling into the plugin any more.
565 // Swap out the set so we can delete from it (the objects will try to
566 // unregister themselves inside the delete call).
567 PluginObjectSet plugin_object_copy;
568 live_plugin_objects_.swap(plugin_object_copy);
569 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
570 i != plugin_object_copy.end();
571 ++i) {
572 (*i)->InstanceDeleted();
575 if (message_channel_)
576 message_channel_->InstanceDeleted();
577 message_channel_object_.Reset();
579 if (TrackedCallback::IsPending(lock_mouse_callback_))
580 lock_mouse_callback_->Abort();
582 if (!instance_deleted_callback_.is_null())
583 instance_deleted_callback_.Run();
585 if (!module_->IsProxied() && render_frame_) {
586 PepperBrowserConnection* browser_connection =
587 PepperBrowserConnection::Get(render_frame_);
588 browser_connection->DidDeleteInProcessInstance(pp_instance());
591 UnSetAndDeleteLockTargetAdapter();
592 module_->InstanceDeleted(this);
593 // If we switched from the NaCl plugin module, notify it too.
594 if (original_module_.get())
595 original_module_->InstanceDeleted(this);
597 // This should be last since some of the above "instance deleted" calls will
598 // want to look up in the global map to get info off of our object.
599 HostGlobals::Get()->InstanceDeleted(pp_instance_);
601 if (throttler_)
602 throttler_->RemoveObserver(this);
605 // NOTE: Any of these methods that calls into the plugin needs to take into
606 // account that the plugin may use Var to remove the <embed> from the DOM, which
607 // will make the PepperWebPluginImpl drop its reference, usually the last one.
608 // If a method needs to access a member of the instance after the call has
609 // returned, then it needs to keep its own reference on the stack.
611 v8::Local<v8::Object> PepperPluginInstanceImpl::GetMessageChannelObject() {
612 return v8::Local<v8::Object>::New(isolate_, message_channel_object_);
615 void PepperPluginInstanceImpl::MessageChannelDestroyed() {
616 message_channel_ = NULL;
617 message_channel_object_.Reset();
620 v8::Local<v8::Context> PepperPluginInstanceImpl::GetMainWorldContext() {
621 if (!container_)
622 return v8::Local<v8::Context>();
624 if (container_->element().isNull())
625 return v8::Local<v8::Context>();
627 if (container_->element().document().isNull())
628 return v8::Local<v8::Context>();
630 if (!container_->element().document().frame())
631 return v8::Local<v8::Context>();
633 v8::Local<v8::Context> context =
634 container_->element().document().frame()->mainWorldScriptContext();
635 DCHECK(context->GetIsolate() == isolate_);
636 return context;
639 void PepperPluginInstanceImpl::Delete() {
640 is_deleted_ = true;
642 if (render_frame_ && render_frame_->render_view() &&
643 render_frame_->render_view()->plugin_find_handler() == this) {
644 render_frame_->render_view()->set_plugin_find_handler(NULL);
647 // Keep a reference on the stack. See NOTE above.
648 scoped_refptr<PepperPluginInstanceImpl> ref(this);
650 // It is important to destroy the throttler before anything else.
651 // The plugin instance may flush its graphics pipeline during its postmortem
652 // spasm, causing the throttler to engage and obtain new dangling reference
653 // to the plugin container being destroyed.
654 throttler_.reset();
656 // Force the MessageChannel to release its "passthrough object" which should
657 // release our last reference to the "InstanceObject" and will probably
658 // destroy it. We want to do this prior to calling DidDestroy in case the
659 // destructor of the instance object tries to use the instance.
660 if (message_channel_)
661 message_channel_->SetPassthroughObject(v8::Local<v8::Object>());
662 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
663 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
664 // since there is little that it can do at this point.
665 if (original_instance_interface_) {
666 base::TimeTicks start = base::TimeTicks::Now();
667 original_instance_interface_->DidDestroy(pp_instance());
668 UMA_HISTOGRAM_CUSTOM_TIMES("NaCl.Perf.ShutdownTime.Total",
669 base::TimeTicks::Now() - start,
670 base::TimeDelta::FromMilliseconds(1),
671 base::TimeDelta::FromSeconds(20),
672 100);
673 } else {
674 instance_interface_->DidDestroy(pp_instance());
676 // Ensure we don't attempt to call functions on the destroyed instance.
677 original_instance_interface_.reset();
678 instance_interface_.reset();
680 if (fullscreen_container_) {
681 fullscreen_container_->Destroy();
682 fullscreen_container_ = NULL;
685 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
686 // leaks the graphics 2D, it may actually get cleaned up after our
687 // destruction, so we need its pointers to be up-to-date.
688 BindGraphics(pp_instance(), 0);
689 container_ = NULL;
692 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
694 void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
695 const gfx::Rect& plugin_rect,
696 const gfx::Rect& paint_rect) {
697 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
698 if (module()->is_crashed()) {
699 // Crashed plugin painting.
700 if (!sad_plugin_) // Lazily initialize bitmap.
701 sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
702 if (sad_plugin_)
703 PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
704 return;
707 if (bound_graphics_2d_platform_)
708 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
711 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
712 if (fullscreen_container_) {
713 if (rect.IsEmpty())
714 fullscreen_container_->Invalidate();
715 else
716 fullscreen_container_->InvalidateRect(rect);
717 } else {
718 if (!container_ || view_data_.rect.size.width == 0 ||
719 view_data_.rect.size.height == 0)
720 return; // Nothing to do.
721 if (rect.IsEmpty())
722 container_->invalidate();
723 else
724 container_->invalidateRect(rect);
727 cc::Layer* layer =
728 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
729 if (layer) {
730 if (rect.IsEmpty()) {
731 layer->SetNeedsDisplay();
732 } else {
733 layer->SetNeedsDisplayRect(rect);
738 void PepperPluginInstanceImpl::ScrollRect(int dx,
739 int dy,
740 const gfx::Rect& rect) {
741 cc::Layer* layer =
742 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
743 if (layer) {
744 InvalidateRect(rect);
745 } else if (fullscreen_container_) {
746 fullscreen_container_->ScrollRect(dx, dy, rect);
747 } else {
748 if (full_frame_ && !IsViewAccelerated()) {
749 container_->scrollRect(rect);
750 } else {
751 // Can't do optimized scrolling since there could be other elements on top
752 // of us or the view renders via the accelerated compositor which is
753 // incompatible with the move and backfill scrolling model.
754 InvalidateRect(rect);
759 void PepperPluginInstanceImpl::CommitBackingTexture() {
760 if (!texture_layer_.get())
761 return;
762 gpu::Mailbox mailbox;
763 uint32 sync_point = 0;
764 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
765 DCHECK(!mailbox.IsZero());
766 DCHECK_NE(sync_point, 0u);
767 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
768 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
769 texture_layer_->SetNeedsDisplay();
772 void PepperPluginInstanceImpl::InstanceCrashed() {
773 // Force free all resources and vars.
774 HostGlobals::Get()->InstanceCrashed(pp_instance());
776 // Free any associated graphics.
777 SetFullscreen(false);
778 FlashSetFullscreen(false, false);
779 // Unbind current 2D or 3D graphics context.
780 BindGraphics(pp_instance(), 0);
781 InvalidateRect(gfx::Rect());
783 if (content_decryptor_delegate_) {
784 content_decryptor_delegate_->InstanceCrashed();
785 content_decryptor_delegate_.reset();
788 if (render_frame_)
789 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
790 UnSetAndDeleteLockTargetAdapter();
793 bool PepperPluginInstanceImpl::Initialize(
794 const std::vector<std::string>& arg_names,
795 const std::vector<std::string>& arg_values,
796 bool full_frame,
797 scoped_ptr<PluginInstanceThrottlerImpl> throttler) {
798 DCHECK(!throttler_);
800 if (!render_frame_)
801 return false;
803 if (throttler) {
804 throttler_ = throttler.Pass();
805 throttler_->AddObserver(this);
808 message_channel_ = MessageChannel::Create(this, &message_channel_object_);
810 full_frame_ = full_frame;
812 UpdateTouchEventRequest();
813 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
815 SetGPUHistogram(ppapi::Preferences(PpapiPreferencesBuilder::Build(
816 render_frame_->render_view()->webkit_preferences())),
817 arg_names,
818 arg_values);
820 argn_ = arg_names;
821 argv_ = arg_values;
822 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
823 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
824 auto weak_this = weak_factory_.GetWeakPtr();
825 bool success = PP_ToBool(instance_interface_->DidCreate(
826 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
827 if (!weak_this) {
828 // The plugin may do synchronous scripting during "DidCreate", so |this|
829 // may be deleted. In that case, return failure and don't touch any
830 // member variables.
831 return false;
833 // If this is a plugin that hosts external plugins, we should delay messages
834 // so that the child plugin that's created later will receive all the
835 // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
837 // A host for external plugins will call ResetAsProxied later, at which point
838 // we can Start() the MessageChannel.
839 if (success && (!module_->renderer_ppapi_host()->IsExternalPluginHost())) {
840 if (message_channel_)
841 message_channel_->Start();
843 initialized_ = success;
844 return success;
847 bool PepperPluginInstanceImpl::HandleDocumentLoad(
848 const blink::WebURLResponse& response) {
849 DCHECK(!document_loader_);
850 if (external_document_load_) {
851 // The external proxy isn't available, so save the response and record
852 // document load notifications for later replay.
853 external_document_response_ = response;
854 external_document_loader_.reset(new ExternalDocumentLoader());
855 document_loader_ = external_document_loader_.get();
856 return true;
859 if (module()->is_crashed()) {
860 // Don't create a resource for a crashed plugin.
861 container()->element().document().frame()->stopLoading();
862 return false;
865 DCHECK(!document_loader_);
867 // Create a loader resource host for this load. Note that we have to set
868 // the document_loader before issuing the in-process
869 // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
870 // call into the instance and expect it to be valid.
871 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
872 PepperURLLoaderHost* loader_host =
873 new PepperURLLoaderHost(host_impl, true, pp_instance(), 0);
874 // TODO(teravest): Remove set_document_loader() from instance and clean up
875 // this relationship.
876 set_document_loader(loader_host);
877 loader_host->didReceiveResponse(NULL, response);
879 // This host will be pending until the resource object attaches to it.
881 // PpapiHost now owns the pointer to loader_host, so we don't have to worry
882 // about managing it.
883 int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
884 scoped_ptr<ppapi::host::ResourceHost>(loader_host));
885 DCHECK(pending_host_id);
887 DataFromWebURLResponse(
888 host_impl,
889 pp_instance(),
890 response,
891 base::Bind(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
892 weak_factory_.GetWeakPtr(),
893 response,
894 pending_host_id));
896 // If the load was not abandoned, document_loader_ will now be set. It's
897 // possible that the load was canceled by now and document_loader_ was
898 // already nulled out.
899 return true;
902 bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
903 PP_InputEvent_Type type,
904 const base::string16& text) {
905 std::vector<blink::WebCompositionUnderline> empty;
906 return SendCompositionEventWithUnderlineInformationToPlugin(
907 type,
908 text,
909 empty,
910 static_cast<int>(text.size()),
911 static_cast<int>(text.size()));
914 bool
915 PepperPluginInstanceImpl::SendCompositionEventWithUnderlineInformationToPlugin(
916 PP_InputEvent_Type type,
917 const base::string16& text,
918 const std::vector<blink::WebCompositionUnderline>& underlines,
919 int selection_start,
920 int selection_end) {
921 // Keep a reference on the stack. See NOTE above.
922 scoped_refptr<PepperPluginInstanceImpl> ref(this);
924 if (!LoadInputEventInterface())
925 return false;
927 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
928 if (!(filtered_input_event_mask_ & event_class) &&
929 !(input_event_mask_ & event_class))
930 return false;
932 ppapi::InputEventData event;
933 event.event_type = type;
934 event.event_time_stamp =
935 ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
937 // Convert UTF16 text to UTF8 with offset conversion.
938 std::vector<size_t> utf16_offsets;
939 utf16_offsets.push_back(selection_start);
940 utf16_offsets.push_back(selection_end);
941 for (size_t i = 0; i < underlines.size(); ++i) {
942 utf16_offsets.push_back(underlines[i].startOffset);
943 utf16_offsets.push_back(underlines[i].endOffset);
945 std::vector<size_t> utf8_offsets(utf16_offsets);
946 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
948 // Set the converted selection range.
949 event.composition_selection_start =
950 (utf8_offsets[0] == std::string::npos ? event.character_text.size()
951 : utf8_offsets[0]);
952 event.composition_selection_end =
953 (utf8_offsets[1] == std::string::npos ? event.character_text.size()
954 : utf8_offsets[1]);
956 // Set the converted segmentation points.
957 // Be sure to add 0 and size(), and remove duplication or errors.
958 std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
959 offset_set.insert(0);
960 offset_set.insert(event.character_text.size());
961 offset_set.erase(std::string::npos);
962 event.composition_segment_offsets.assign(offset_set.begin(),
963 offset_set.end());
965 // Set the composition target.
966 for (size_t i = 0; i < underlines.size(); ++i) {
967 if (underlines[i].thick) {
968 std::vector<uint32_t>::iterator it =
969 std::find(event.composition_segment_offsets.begin(),
970 event.composition_segment_offsets.end(),
971 utf8_offsets[2 * i + 2]);
972 if (it != event.composition_segment_offsets.end()) {
973 event.composition_target_segment =
974 it - event.composition_segment_offsets.begin();
975 break;
980 // Send the event.
981 bool handled = false;
982 if (filtered_input_event_mask_ & event_class)
983 event.is_filtered = true;
984 else
985 handled = true; // Unfiltered events are assumed to be handled.
986 scoped_refptr<PPB_InputEvent_Shared> event_resource(
987 new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
988 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
989 pp_instance(), event_resource->pp_resource()));
990 return handled;
993 void PepperPluginInstanceImpl::RequestInputEventsHelper(
994 uint32_t event_classes) {
995 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
996 UpdateTouchEventRequest();
997 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
998 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
1001 bool PepperPluginInstanceImpl::HandleCompositionStart(
1002 const base::string16& text) {
1003 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1004 text);
1007 bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1008 const base::string16& text,
1009 const std::vector<blink::WebCompositionUnderline>& underlines,
1010 int selection_start,
1011 int selection_end) {
1012 return SendCompositionEventWithUnderlineInformationToPlugin(
1013 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
1014 text,
1015 underlines,
1016 selection_start,
1017 selection_end);
1020 bool PepperPluginInstanceImpl::HandleCompositionEnd(
1021 const base::string16& text) {
1022 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1023 text);
1026 bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1027 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1030 void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1031 gfx::Range* range) const {
1032 std::vector<size_t> offsets;
1033 offsets.push_back(selection_anchor_);
1034 offsets.push_back(selection_caret_);
1035 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1036 range->set_start(offsets[0] == base::string16::npos ? text->size()
1037 : offsets[0]);
1038 range->set_end(offsets[1] == base::string16::npos ? text->size()
1039 : offsets[1]);
1042 bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1043 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1044 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1047 gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1048 if (!text_input_caret_set_) {
1049 // If it is never set by the plugin, use the bottom left corner.
1050 return gfx::Rect(view_data_.rect.point.x,
1051 view_data_.rect.point.y + view_data_.rect.size.height,
1056 // TODO(kinaba) Take CSS transformation into accont.
1057 // TODO(kinaba) Take bounding_box into account. On some platforms, an
1058 // "exclude rectangle" where candidate window must avoid the region can be
1059 // passed to IME. Currently, we pass only the caret rectangle because
1060 // it is the only information supported uniformly in Chromium.
1061 gfx::Rect caret(text_input_caret_);
1062 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1063 return caret;
1066 bool PepperPluginInstanceImpl::HandleInputEvent(
1067 const blink::WebInputEvent& event,
1068 WebCursorInfo* cursor_info) {
1069 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1071 if (!has_been_clicked_ && is_flash_plugin_ &&
1072 event.type == blink::WebInputEvent::MouseDown &&
1073 (event.modifiers & blink::WebInputEvent::LeftButtonDown)) {
1074 has_been_clicked_ = true;
1075 blink::WebRect bounds = container()->element().boundsInViewportSpace();
1076 RecordFlashClickSizeMetric(bounds.width, bounds.height);
1079 if (throttler_ && throttler_->ConsumeInputEvent(event))
1080 return true;
1082 if (!render_frame_)
1083 return false;
1084 if (WebInputEvent::isMouseEventType(event.type)) {
1085 render_frame_->PepperDidReceiveMouseEvent(this);
1088 // Don't dispatch input events to crashed plugins.
1089 if (module()->is_crashed())
1090 return false;
1092 // Don't send reserved system key events to plugins.
1093 if (IsReservedSystemInputEvent(event))
1094 return false;
1096 // Keep a reference on the stack. See NOTE above.
1097 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1099 bool rv = false;
1100 if (LoadInputEventInterface()) {
1101 PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
1102 if (!event_class)
1103 return false;
1105 if ((filtered_input_event_mask_ & event_class) ||
1106 (input_event_mask_ & event_class)) {
1107 // Actually send the event.
1108 std::vector<ppapi::InputEventData> events;
1109 CreateInputEventData(event, &events);
1111 // Allow the user gesture to be pending after the plugin handles the
1112 // event. This allows out-of-process plugins to respond to the user
1113 // gesture after processing has finished here.
1114 if (WebUserGestureIndicator::isProcessingUserGesture()) {
1115 pending_user_gesture_ =
1116 ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
1117 pending_user_gesture_token_ =
1118 WebUserGestureIndicator::currentUserGestureToken();
1119 pending_user_gesture_token_.setOutOfProcess();
1122 // Each input event may generate more than one PP_InputEvent.
1123 for (size_t i = 0; i < events.size(); i++) {
1124 if (filtered_input_event_mask_ & event_class)
1125 events[i].is_filtered = true;
1126 else
1127 rv = true; // Unfiltered events are assumed to be handled.
1128 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1129 new PPB_InputEvent_Shared(
1130 ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1132 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1133 pp_instance(), event_resource->pp_resource()));
1138 if (cursor_)
1139 *cursor_info = *cursor_;
1140 return rv;
1143 void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1144 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1145 if (is_deleted_)
1146 return;
1147 ppapi::proxy::HostDispatcher* dispatcher =
1148 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1149 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1150 // The dispatcher should always be valid, and MessageChannel should never
1151 // send an 'object' var over PPP_Messaging.
1152 NOTREACHED();
1153 return;
1155 dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1156 ppapi::API_ID_PPP_MESSAGING,
1157 pp_instance(),
1158 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1159 pp_instance())));
1162 bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1163 ScopedPPVar* result) {
1164 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
1165 if (is_deleted_)
1166 return false;
1167 ppapi::proxy::HostDispatcher* dispatcher =
1168 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1169 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1170 // The dispatcher should always be valid, and MessageChannel should never
1171 // send an 'object' var over PPP_Messaging.
1172 NOTREACHED();
1173 return false;
1175 ppapi::proxy::ReceiveSerializedVarReturnValue msg_reply;
1176 bool was_handled = false;
1177 dispatcher->Send(new PpapiMsg_PPPMessageHandler_HandleBlockingMessage(
1178 ppapi::API_ID_PPP_MESSAGING,
1179 pp_instance(),
1180 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1181 pp_instance()),
1182 &msg_reply,
1183 &was_handled));
1184 *result = ScopedPPVar(ScopedPPVar::PassRef(), msg_reply.Return(dispatcher));
1185 TRACE_EVENT0("ppapi",
1186 "PepperPluginInstanceImpl::HandleBlockingMessage return.");
1187 return was_handled;
1190 PP_Var PepperPluginInstanceImpl::GetInstanceObject(v8::Isolate* isolate) {
1191 // Keep a reference on the stack. See NOTE above.
1192 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1194 DCHECK_EQ(isolate, isolate_);
1195 RecordFlashJavaScriptUse();
1197 // If the plugin supports the private instance interface, try to retrieve its
1198 // instance object.
1199 if (LoadPrivateInterface())
1200 return plugin_private_interface_->GetInstanceObject(pp_instance());
1201 return PP_MakeUndefined();
1204 void PepperPluginInstanceImpl::ViewChanged(
1205 const gfx::Rect& window,
1206 const gfx::Rect& clip,
1207 const gfx::Rect& unobscured,
1208 const std::vector<gfx::Rect>& cut_outs_rects) {
1209 // WebKit can give weird (x,y) positions for empty clip rects (since the
1210 // position technically doesn't matter). But we want to make these
1211 // consistent since this is given to the plugin, so force everything to 0
1212 // in the "everything is clipped" case.
1213 gfx::Rect new_clip;
1214 if (!clip.IsEmpty())
1215 new_clip = clip;
1217 unobscured_rect_ = unobscured;
1219 cut_outs_rects_ = cut_outs_rects;
1221 view_data_.rect = PP_FromGfxRect(window);
1222 view_data_.clip_rect = PP_FromGfxRect(clip);
1223 view_data_.device_scale = container_->deviceScaleFactor();
1224 view_data_.css_scale =
1225 container_->pageZoomFactor() * container_->pageScaleFactor();
1227 gfx::Size scroll_offset =
1228 container_->element().document().frame()->scrollOffset();
1229 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1230 scroll_offset.height());
1232 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1233 WebElement element = container_->element();
1234 WebDocument document = element.document();
1235 bool is_fullscreen_element = (element == document.fullScreenElement());
1236 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1237 render_frame()->GetRenderWidget()->is_fullscreen_granted() &&
1238 is_fullscreen_element) {
1239 // Entered fullscreen. Only possible via SetFullscreen().
1240 view_data_.is_fullscreen = true;
1241 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1242 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1243 // so desired_fullscreen_state might be out-of-date.
1244 desired_fullscreen_state_ = false;
1245 view_data_.is_fullscreen = false;
1247 // This operation will cause the plugin to re-layout which will send more
1248 // DidChangeView updates. Schedule an asynchronous update and suppress
1249 // notifications until that completes to avoid sending intermediate sizes
1250 // to the plugins.
1251 ScheduleAsyncDidChangeView();
1253 // Reset the size attributes that we hacked to fill in the screen and
1254 // retrigger ViewChanged. Make sure we don't forward duplicates of
1255 // this view to the plugin.
1256 ResetSizeAttributesAfterFullscreen();
1257 return;
1261 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1263 // During plugin initialization, there are often re-layouts. Avoid sending
1264 // intermediate sizes the plugin and throttler.
1265 if (sent_initial_did_change_view_)
1266 SendDidChangeView();
1267 else
1268 ScheduleAsyncDidChangeView();
1271 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1272 if (has_webkit_focus_ == has_focus)
1273 return;
1275 bool old_plugin_focus = PluginHasFocus();
1276 has_webkit_focus_ = has_focus;
1277 if (PluginHasFocus() != old_plugin_focus)
1278 SendFocusChangeNotification();
1281 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1282 if (has_content_area_focus_ == has_focus)
1283 return;
1285 bool old_plugin_focus = PluginHasFocus();
1286 has_content_area_focus_ = has_focus;
1287 if (PluginHasFocus() != old_plugin_focus)
1288 SendFocusChangeNotification();
1291 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1292 if (is_visible == view_data_.is_page_visible)
1293 return; // Nothing to do.
1294 view_data_.is_page_visible = is_visible;
1296 // If the initial DidChangeView notification hasn't been sent to the plugin,
1297 // let it pass the visibility state for us, instead of sending a notification
1298 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1299 // hasn't been called for the first time. In that case, most of the fields in
1300 // |view_data_| haven't been properly initialized.
1301 if (sent_initial_did_change_view_)
1302 SendDidChangeView();
1305 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1306 if (bound_graphics_2d_platform_)
1307 bound_graphics_2d_platform_->ViewInitiatedPaint();
1308 else if (bound_graphics_3d_.get())
1309 bound_graphics_3d_->ViewInitiatedPaint();
1310 else if (bound_compositor_)
1311 bound_compositor_->ViewInitiatedPaint();
1314 void PepperPluginInstanceImpl::SetSelectedText(
1315 const base::string16& selected_text) {
1316 selected_text_ = selected_text;
1317 gfx::Range range(0, selected_text.length());
1318 render_frame_->SetSelectedText(selected_text, 0, range);
1321 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1322 link_under_cursor_ = base::UTF8ToUTF16(url);
1325 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1326 text_input_type_ = type;
1327 render_frame_->PepperTextInputTypeChanged(this);
1330 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1331 if (message_channel_)
1332 message_channel_->PostMessageToJavaScript(message);
1335 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1336 PP_Instance instance,
1337 void* user_data,
1338 const PPP_MessageHandler_0_2* handler,
1339 PP_Resource message_loop) {
1340 // Not supported in-process.
1341 NOTIMPLEMENTED();
1342 return PP_ERROR_FAILED;
1345 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1346 // Not supported in-process.
1347 NOTIMPLEMENTED();
1350 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1351 return selected_text_;
1354 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1355 const gfx::Point& point) {
1356 // Keep a reference on the stack. See NOTE above.
1357 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1358 if (!LoadPdfInterface()) {
1359 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1360 // return |link_under_cursor_| here because this is only ever called with
1361 // the current mouse coordinates.
1362 return link_under_cursor_;
1365 PP_Point p;
1366 p.x = point.x();
1367 p.y = point.y();
1368 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1369 // If the plugin returns undefined for this function it has switched to
1370 // providing us with the link under the cursor eagerly.
1371 if (rv.type == PP_VARTYPE_UNDEFINED)
1372 return link_under_cursor_;
1373 StringVar* string = StringVar::FromPPVar(rv);
1374 base::string16 link;
1375 if (string)
1376 link = base::UTF8ToUTF16(string->value());
1377 // Release the ref the plugin transfered to us.
1378 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1379 return link;
1382 void PepperPluginInstanceImpl::RequestSurroundingText(
1383 size_t desired_number_of_characters) {
1384 // Keep a reference on the stack. See NOTE above.
1385 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1386 if (!LoadTextInputInterface())
1387 return;
1388 plugin_textinput_interface_->RequestSurroundingText(
1389 pp_instance(), desired_number_of_characters);
1392 bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1393 bool case_sensitive,
1394 int identifier) {
1395 // Keep a reference on the stack. See NOTE above.
1396 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1397 if (!LoadFindInterface())
1398 return false;
1399 find_identifier_ = identifier;
1400 return PP_ToBool(
1401 plugin_find_interface_->StartFind(pp_instance(),
1402 base::UTF16ToUTF8(search_text).c_str(),
1403 PP_FromBool(case_sensitive)));
1406 void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1407 // Keep a reference on the stack. See NOTE above.
1408 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1409 if (LoadFindInterface())
1410 plugin_find_interface_->SelectFindResult(pp_instance(),
1411 PP_FromBool(forward));
1414 void PepperPluginInstanceImpl::StopFind() {
1415 // Keep a reference on the stack. See NOTE above.
1416 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1417 if (!LoadFindInterface())
1418 return;
1419 find_identifier_ = -1;
1420 plugin_find_interface_->StopFind(pp_instance());
1423 bool PepperPluginInstanceImpl::LoadFindInterface() {
1424 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1425 return false;
1426 if (!plugin_find_interface_) {
1427 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1428 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1431 return !!plugin_find_interface_;
1434 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1435 if (!checked_for_plugin_input_event_interface_) {
1436 checked_for_plugin_input_event_interface_ = true;
1437 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1438 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1440 return !!plugin_input_event_interface_;
1443 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1444 if (!plugin_mouse_lock_interface_) {
1445 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1446 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1449 return !!plugin_mouse_lock_interface_;
1452 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1453 if (!checked_for_plugin_pdf_interface_) {
1454 checked_for_plugin_pdf_interface_ = true;
1455 plugin_pdf_interface_ = static_cast<const PPP_Pdf*>(
1456 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1459 return !!plugin_pdf_interface_;
1462 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1463 // Only check for the interface if the plugin has dev permission.
1464 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1465 return false;
1466 if (!plugin_print_interface_) {
1467 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1468 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1470 return !!plugin_print_interface_;
1473 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1474 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1475 // call GetInstanceObject. This is necessary to ensure that the properties
1476 // the trusted plugin exposes (readyState and lastError) work properly. Note
1477 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1478 // so it's correct to never look up PPP_InstancePrivate for them.
1480 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1481 // to the "real" module.
1482 scoped_refptr<PluginModule> module =
1483 original_module_.get() ? original_module_ : module_;
1484 // Only check for the interface if the plugin has private permission.
1485 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1486 return false;
1487 if (!plugin_private_interface_) {
1488 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1489 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1492 return !!plugin_private_interface_;
1495 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1496 if (!plugin_textinput_interface_) {
1497 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1498 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1501 return !!plugin_textinput_interface_;
1504 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1505 if (!bound_graphics_2d_platform_ || !texture_layer_.get()) {
1506 // Currently the transform is only applied for Graphics2D.
1507 return;
1509 // Set the UV coordinates of the texture based on the size of the Graphics2D
1510 // context. By default a texture gets scaled to the size of the layer. But
1511 // if the size of the Graphics2D context doesn't match the size of the plugin
1512 // then it will be incorrectly stretched. This also affects how the plugin
1513 // is painted when it is being resized. If the Graphics2D contents are
1514 // stretched when a plugin is resized while waiting for a new frame from the
1515 // plugin to be rendered, then flickering behavior occurs as in
1516 // crbug.com/353453.
1517 gfx::SizeF graphics_2d_size_in_dip =
1518 gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1519 bound_graphics_2d_platform_->GetScale());
1520 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1521 view_data_.rect.size.height);
1523 texture_layer_->SetUV(
1524 gfx::PointF(0.0f, 0.0f),
1525 gfx::PointF(
1526 plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1527 plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1530 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1531 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1534 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1535 // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1536 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1537 // drop its reference, usually the last one. This is similar to possible
1538 // plugin behavior described at the NOTE above Delete().
1539 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1541 if (!render_frame_)
1542 return;
1544 bool has_focus = PluginHasFocus();
1545 render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1547 // instance_interface_ may have been cleared in Delete() if the
1548 // PepperWebPluginImpl is destroyed.
1549 if (instance_interface_)
1550 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1553 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1554 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1555 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1556 container_->requestTouchEventType(
1557 raw_touch
1558 ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1559 : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1562 bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1563 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1564 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1567 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1568 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1569 return; // Already scheduled.
1570 base::ThreadTaskRunnerHandle::Get()->PostTask(
1571 FROM_HERE, base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1572 view_change_weak_ptr_factory_.GetWeakPtr()));
1575 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1576 // The bound callback that owns the weak pointer is still valid until after
1577 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1578 // invalidate them here.
1579 // NOTE: If we ever want to have more than one pending callback, it should
1580 // use a different factory, or we should have a different strategy here.
1581 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1582 SendDidChangeView();
1585 void PepperPluginInstanceImpl::SendDidChangeView() {
1586 // An asynchronous view update is scheduled. Skip sending this update.
1587 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1588 return;
1590 // Don't send DidChangeView to crashed plugins.
1591 if (module()->is_crashed())
1592 return;
1594 // During the first view update, initialize the throttler.
1595 if (!sent_initial_did_change_view_) {
1596 if (is_flash_plugin_ && RenderThread::Get()) {
1597 RenderThread::Get()->RecordAction(
1598 base::UserMetricsAction("Flash.PluginInstanceCreated"));
1599 RecordFlashSizeMetric(unobscured_rect_.width(),
1600 unobscured_rect_.height());
1603 if (throttler_) {
1604 throttler_->Initialize(render_frame_, plugin_url_.GetOrigin(),
1605 module()->name(), unobscured_rect_.size());
1609 ppapi::ViewData view_data = view_data_;
1611 // When plugin content is throttled, fake the page being offscreen. We cannot
1612 // send empty view data here, as some plugins rely on accurate view data.
1613 if (throttler_ && throttler_->IsThrottled()) {
1614 view_data.is_page_visible = false;
1615 view_data.clip_rect.point.x = 0;
1616 view_data.clip_rect.point.y = 0;
1617 view_data.clip_rect.size.width = 0;
1618 view_data.clip_rect.size.height = 0;
1621 if (sent_initial_did_change_view_ && last_sent_view_data_.Equals(view_data))
1622 return; // Nothing to update.
1624 sent_initial_did_change_view_ = true;
1625 last_sent_view_data_ = view_data;
1626 ScopedPPResource resource(
1627 ScopedPPResource::PassRef(),
1628 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data))
1629 ->GetReference());
1631 UpdateLayerTransform();
1633 if (bound_graphics_2d_platform_ &&
1634 (!view_data.is_page_visible ||
1635 PP_ToGfxRect(view_data.clip_rect).IsEmpty())) {
1636 bound_graphics_2d_platform_->ClearCache();
1639 // It's possible that Delete() has been called but the renderer hasn't
1640 // released its reference to this object yet.
1641 if (instance_interface_) {
1642 instance_interface_->DidChangeView(
1643 pp_instance(), resource, &view_data.rect, &view_data.clip_rect);
1647 void PepperPluginInstanceImpl::ReportGeometry() {
1648 // If this call was delayed, we may have transitioned back to fullscreen in
1649 // the mean time, so only report the geometry if we are actually in normal
1650 // mode.
1651 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1652 container_->reportGeometry();
1655 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1656 PP_PrintOutputFormat_Dev* format) {
1657 // Keep a reference on the stack. See NOTE above.
1658 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1659 if (!LoadPrintInterface())
1660 return false;
1661 uint32_t supported_formats =
1662 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1663 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1664 *format = PP_PRINTOUTPUTFORMAT_PDF;
1665 return true;
1667 return false;
1670 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1671 PP_PrintOutputFormat_Dev format;
1672 return GetPreferredPrintOutputFormat(&format);
1675 bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1676 DCHECK(plugin_print_interface_);
1677 if (!plugin_print_interface_)
1678 return false;
1679 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1682 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1683 // Keep a reference on the stack. See NOTE above.
1684 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1685 PP_PrintOutputFormat_Dev format;
1686 if (!GetPreferredPrintOutputFormat(&format)) {
1687 // PrintBegin should not have been called since SupportsPrintInterface
1688 // would have returned false;
1689 NOTREACHED();
1690 return 0;
1692 int num_pages = 0;
1693 PP_PrintSettings_Dev print_settings;
1694 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1695 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1696 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1697 print_settings.dpi = print_params.printerDPI;
1698 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1699 print_settings.grayscale = PP_FALSE;
1700 print_settings.print_scaling_option =
1701 static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1702 print_settings.format = format;
1703 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1704 if (!num_pages)
1705 return 0;
1706 current_print_settings_ = print_settings;
1707 canvas_.clear();
1708 ranges_.clear();
1709 return num_pages;
1712 void PepperPluginInstanceImpl::PrintPage(int page_number,
1713 blink::WebCanvas* canvas) {
1714 #if defined(ENABLE_PRINTING)
1715 DCHECK(plugin_print_interface_);
1716 PP_PrintPageNumberRange_Dev page_range;
1717 page_range.first_page_number = page_range.last_page_number = page_number;
1718 // The canvas only has a metafile on it for print preview.
1719 bool save_for_later =
1720 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1721 #if defined(OS_MACOSX)
1722 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1723 #endif // defined(OS_MACOSX)
1724 if (save_for_later) {
1725 ranges_.push_back(page_range);
1726 canvas_ = skia::SharePtr(canvas);
1727 } else {
1728 PrintPageHelper(&page_range, 1, canvas);
1730 #endif
1733 void PepperPluginInstanceImpl::PrintPageHelper(
1734 PP_PrintPageNumberRange_Dev* page_ranges,
1735 int num_ranges,
1736 blink::WebCanvas* canvas) {
1737 // Keep a reference on the stack. See NOTE above.
1738 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1739 DCHECK(plugin_print_interface_);
1740 if (!plugin_print_interface_)
1741 return;
1742 PP_Resource print_output = plugin_print_interface_->PrintPages(
1743 pp_instance(), page_ranges, num_ranges);
1744 if (!print_output)
1745 return;
1747 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1748 PrintPDFOutput(print_output, canvas);
1750 // Now we need to release the print output resource.
1751 PluginModule::GetCore()->ReleaseResource(print_output);
1754 void PepperPluginInstanceImpl::PrintEnd() {
1755 // Keep a reference on the stack. See NOTE above.
1756 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1757 if (!ranges_.empty())
1758 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1759 canvas_.clear();
1760 ranges_.clear();
1762 DCHECK(plugin_print_interface_);
1763 if (plugin_print_interface_)
1764 plugin_print_interface_->End(pp_instance());
1766 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1767 #if defined(OS_MACOSX)
1768 last_printed_page_ = NULL;
1769 #endif // defined(OS_MACOSX)
1772 bool PepperPluginInstanceImpl::GetPrintPresetOptionsFromDocument(
1773 blink::WebPrintPresetOptions* preset_options) {
1774 // Keep a reference on the stack. See NOTE above.
1775 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1776 if (!LoadPdfInterface())
1777 return false;
1779 PP_PdfPrintPresetOptions_Dev options;
1780 if (!plugin_pdf_interface_->GetPrintPresetOptionsFromDocument(pp_instance(),
1781 &options)) {
1782 return false;
1785 preset_options->isScalingDisabled = PP_ToBool(options.is_scaling_disabled);
1786 switch (options.duplex) {
1787 case PP_PRIVATEDUPLEXMODE_SIMPLEX:
1788 preset_options->duplexMode = blink::WebSimplex;
1789 break;
1790 case PP_PRIVATEDUPLEXMODE_SHORT_EDGE:
1791 preset_options->duplexMode = blink::WebShortEdge;
1792 break;
1793 case PP_PRIVATEDUPLEXMODE_LONG_EDGE:
1794 preset_options->duplexMode = blink::WebLongEdge;
1795 break;
1796 default:
1797 preset_options->duplexMode = blink::WebUnknownDuplexMode;
1798 break;
1800 preset_options->copies = options.copies;
1801 preset_options->isPageSizeUniform = PP_ToBool(options.is_page_size_uniform);
1802 preset_options->uniformPageSize =
1803 blink::WebSize(options.uniform_page_size.width,
1804 options.uniform_page_size.height);
1806 return true;
1809 bool PepperPluginInstanceImpl::CanRotateView() {
1810 if (!LoadPdfInterface() || module()->is_crashed())
1811 return false;
1813 return true;
1816 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1817 if (!LoadPdfInterface())
1818 return;
1819 PP_PrivatePageTransformType transform_type =
1820 type == WebPlugin::RotationType90Clockwise
1821 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1822 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1823 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1824 // NOTE: plugin instance may have been deleted.
1827 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1828 return fullscreen_container_ != NULL;
1831 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1832 return desired_fullscreen_state_;
1835 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1836 // Keep a reference on the stack. See NOTE above.
1837 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1839 // Check whether we are trying to switch to the state we're already going
1840 // to (i.e. if we're already switching to fullscreen but the fullscreen
1841 // container isn't ready yet, don't do anything more).
1842 if (fullscreen == IsFullscreenOrPending())
1843 return false;
1845 if (!render_frame_)
1846 return false;
1847 if (fullscreen && !render_frame_->render_view()
1848 ->renderer_preferences()
1849 .plugin_fullscreen_allowed)
1850 return false;
1852 // Check whether we are trying to switch while the state is in transition.
1853 // The 2nd request gets dropped while messing up the internal state, so
1854 // disallow this.
1855 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1856 return false;
1858 if (fullscreen && !IsProcessingUserGesture())
1859 return false;
1861 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1862 desired_fullscreen_state_ = fullscreen;
1864 if (fullscreen) {
1865 // Create the user gesture in case we're processing one that's pending.
1866 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1867 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1868 // so we will tweak plugin's attributes to support the expected behavior.
1869 KeepSizeAttributesBeforeFullscreen();
1870 SetSizeAttributesForFullscreen();
1871 container_->element().requestFullScreen();
1872 } else {
1873 container_->element().document().cancelFullScreen();
1875 return true;
1878 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1879 bool flash_fullscreen) {
1880 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1882 if (flash_fullscreen == flash_fullscreen_) {
1883 // Manually clear callback when fullscreen fails with mouselock pending.
1884 if (!flash_fullscreen && is_mouselock_pending)
1885 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1886 return;
1889 UpdateLayer(false);
1891 bool old_plugin_focus = PluginHasFocus();
1892 flash_fullscreen_ = flash_fullscreen;
1893 if (is_mouselock_pending && !IsMouseLocked()) {
1894 if (!IsProcessingUserGesture() &&
1895 !module_->permissions().HasPermission(
1896 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1897 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1898 } else {
1899 // Open a user gesture here so the Webkit user gesture checks will succeed
1900 // for out-of-process plugins.
1901 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1902 if (!LockMouse())
1903 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1907 if (PluginHasFocus() != old_plugin_focus)
1908 SendFocusChangeNotification();
1911 bool PepperPluginInstanceImpl::IsViewAccelerated() {
1912 if (!container_)
1913 return false;
1915 WebDocument document = container_->element().document();
1916 WebLocalFrame* frame = document.frame();
1917 if (!frame)
1918 return false;
1919 WebView* view = frame->view();
1920 if (!view)
1921 return false;
1923 return view->isAcceleratedCompositingActive();
1926 bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1927 blink::WebCanvas* canvas) {
1928 #if defined(ENABLE_PRINTING)
1929 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1930 if (enter.failed())
1931 return false;
1933 BufferAutoMapper mapper(enter.object());
1934 if (!mapper.data() || !mapper.size()) {
1935 NOTREACHED();
1936 return false;
1939 printing::PdfMetafileSkia* metafile =
1940 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1941 if (metafile)
1942 return metafile->InitFromData(mapper.data(), mapper.size());
1944 NOTREACHED();
1945 #endif // ENABLE_PRINTING
1946 return false;
1949 void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
1950 if (!container_)
1951 return;
1952 if (throttler_ && throttler_->IsHiddenForPlaceholder())
1953 return;
1955 gpu::Mailbox mailbox;
1956 uint32 sync_point = 0;
1957 if (bound_graphics_3d_.get()) {
1958 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
1959 DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
1961 bool want_3d_layer = !mailbox.IsZero();
1962 bool want_2d_layer = !!bound_graphics_2d_platform_;
1963 bool want_texture_layer = want_3d_layer || want_2d_layer;
1964 bool want_compositor_layer = !!bound_compositor_;
1966 if (!device_changed && (want_texture_layer == !!texture_layer_.get()) &&
1967 (want_3d_layer == layer_is_hardware_) &&
1968 (want_compositor_layer == !!compositor_layer_.get()) &&
1969 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
1970 UpdateLayerTransform();
1971 return;
1974 if (texture_layer_.get() || compositor_layer_.get()) {
1975 if (!layer_bound_to_fullscreen_)
1976 container_->setWebLayer(NULL);
1977 else if (fullscreen_container_)
1978 fullscreen_container_->SetLayer(NULL);
1979 web_layer_.reset();
1980 if (texture_layer_) {
1981 texture_layer_->ClearClient();
1982 texture_layer_ = NULL;
1984 compositor_layer_ = NULL;
1987 if (want_texture_layer) {
1988 bool opaque = false;
1989 if (want_3d_layer) {
1990 DCHECK(bound_graphics_3d_.get());
1991 texture_layer_ = cc::TextureLayer::CreateForMailbox(
1992 cc_blink::WebLayerImpl::LayerSettings(), NULL);
1993 opaque = bound_graphics_3d_->IsOpaque();
1994 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
1995 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
1996 } else {
1997 DCHECK(bound_graphics_2d_platform_);
1998 texture_layer_ = cc::TextureLayer::CreateForMailbox(
1999 cc_blink::WebLayerImpl::LayerSettings(), this);
2000 bound_graphics_2d_platform_->AttachedToNewLayer();
2001 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2002 texture_layer_->SetFlipped(false);
2005 // Ignore transparency in fullscreen, since that's what Flash always
2006 // wants to do, and that lets it not recreate a context if
2007 // wmode=transparent was specified.
2008 opaque = opaque || fullscreen_container_;
2009 texture_layer_->SetContentsOpaque(opaque);
2010 web_layer_.reset(new cc_blink::WebLayerImpl(texture_layer_));
2011 } else if (want_compositor_layer) {
2012 compositor_layer_ = bound_compositor_->layer();
2013 web_layer_.reset(new cc_blink::WebLayerImpl(compositor_layer_));
2016 if (web_layer_) {
2017 if (fullscreen_container_) {
2018 fullscreen_container_->SetLayer(web_layer_.get());
2019 } else {
2020 container_->setWebLayer(web_layer_.get());
2024 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2025 layer_is_hardware_ = want_3d_layer;
2026 UpdateLayerTransform();
2029 bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2030 cc::TextureMailbox* mailbox,
2031 scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2032 bool use_shared_memory) {
2033 if (!bound_graphics_2d_platform_)
2034 return false;
2035 return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2036 release_callback);
2039 void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2041 void PepperPluginInstanceImpl::OnThrottleStateChange() {
2042 SendDidChangeView();
2044 bool is_throttled = throttler_->IsThrottled();
2045 render_frame()->Send(new ViewHostMsg_PluginInstanceThrottleStateChange(
2046 module_->GetPluginChildId(), pp_instance_, is_throttled));
2049 void PepperPluginInstanceImpl::OnHiddenForPlaceholder(bool hidden) {
2050 if (hidden) {
2051 container_->setWebLayer(nullptr);
2052 } else {
2053 UpdateLayer(true /* device_changed */);
2057 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2058 DCHECK(live_plugin_objects_.find(plugin_object) ==
2059 live_plugin_objects_.end());
2060 live_plugin_objects_.insert(plugin_object);
2063 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2064 // Don't actually verify that the object is in the set since during module
2065 // deletion we'll be in the process of freeing them.
2066 live_plugin_objects_.erase(plugin_object);
2069 bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2070 PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2071 // Give a lot of slack so tests won't be flaky.
2072 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2073 return pending_user_gesture_token_.hasGestures() &&
2074 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2077 WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2078 if (!IsProcessingUserGesture())
2079 pending_user_gesture_token_ = WebUserGestureToken();
2080 return pending_user_gesture_token_;
2083 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2084 if (TrackedCallback::IsPending(lock_mouse_callback_))
2085 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2088 void PepperPluginInstanceImpl::OnMouseLockLost() {
2089 if (LoadMouseLockInterface())
2090 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2093 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2094 const blink::WebMouseEvent& event) {
2095 // |cursor_info| is ignored since it is hidden when the mouse is locked.
2096 blink::WebCursorInfo cursor_info;
2097 HandleInputEvent(event, &cursor_info);
2100 void PepperPluginInstanceImpl::SimulateInputEvent(
2101 const InputEventData& input_event) {
2102 WebView* web_view = container()->element().document().frame()->view();
2103 if (!web_view) {
2104 NOTREACHED();
2105 return;
2108 bool handled = SimulateIMEEvent(input_event);
2109 if (handled)
2110 return;
2112 std::vector<linked_ptr<WebInputEvent> > events =
2113 CreateSimulatedWebInputEvents(
2114 input_event,
2115 view_data_.rect.point.x + view_data_.rect.size.width / 2,
2116 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2117 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2118 it != events.end();
2119 ++it) {
2120 web_view->handleInputEvent(*it->get());
2124 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2125 const InputEventData& input_event) {
2126 switch (input_event.event_type) {
2127 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2128 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2129 SimulateImeSetCompositionEvent(input_event);
2130 break;
2131 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2132 DCHECK(input_event.character_text.empty());
2133 SimulateImeSetCompositionEvent(input_event);
2134 break;
2135 case PP_INPUTEVENT_TYPE_IME_TEXT:
2136 if (!render_frame_)
2137 return false;
2138 render_frame_->SimulateImeConfirmComposition(
2139 base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2140 break;
2141 default:
2142 return false;
2144 return true;
2147 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2148 const InputEventData& input_event) {
2149 if (!render_frame_)
2150 return;
2152 std::vector<size_t> offsets;
2153 offsets.push_back(input_event.composition_selection_start);
2154 offsets.push_back(input_event.composition_selection_end);
2155 offsets.insert(offsets.end(),
2156 input_event.composition_segment_offsets.begin(),
2157 input_event.composition_segment_offsets.end());
2159 base::string16 utf16_text =
2160 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2162 std::vector<blink::WebCompositionUnderline> underlines;
2163 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2164 blink::WebCompositionUnderline underline;
2165 underline.startOffset = offsets[i];
2166 underline.endOffset = offsets[i + 1];
2167 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2168 underline.thick = true;
2169 underlines.push_back(underline);
2172 render_frame_->SimulateImeSetComposition(
2173 utf16_text, underlines, offsets[0], offsets[1]);
2176 ContentDecryptorDelegate*
2177 PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2178 if (content_decryptor_delegate_)
2179 return content_decryptor_delegate_.get();
2181 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2182 static_cast<const PPP_ContentDecryptor_Private*>(
2183 module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2184 if (!plugin_decryption_interface)
2185 return NULL;
2187 content_decryptor_delegate_.reset(
2188 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2189 return content_decryptor_delegate_.get();
2192 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2193 PP_Resource device) {
2194 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2195 // The Graphics3D instance can't be destroyed until we call
2196 // UpdateLayer().
2197 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2198 if (bound_graphics_3d_.get()) {
2199 bound_graphics_3d_->BindToInstance(false);
2200 bound_graphics_3d_ = NULL;
2202 if (bound_graphics_2d_platform_) {
2203 bound_graphics_2d_platform_->BindToInstance(NULL);
2204 bound_graphics_2d_platform_ = NULL;
2206 if (bound_compositor_) {
2207 bound_compositor_->BindToInstance(NULL);
2208 bound_compositor_ = NULL;
2211 // Special-case clearing the current device.
2212 if (!device) {
2213 UpdateLayer(true);
2214 InvalidateRect(gfx::Rect());
2215 return PP_TRUE;
2218 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2219 // to/from fullscreen with PPB_Fullscreen.
2220 if ((fullscreen_container_ && !flash_fullscreen_) ||
2221 desired_fullscreen_state_ != view_data_.is_fullscreen)
2222 return PP_FALSE;
2224 const ppapi::host::PpapiHost* ppapi_host =
2225 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2226 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2227 PepperGraphics2DHost* graphics_2d = NULL;
2228 PepperCompositorHost* compositor = NULL;
2229 if (host) {
2230 if (host->IsGraphics2DHost()) {
2231 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2232 } else if (host->IsCompositorHost()) {
2233 compositor = static_cast<PepperCompositorHost*>(host);
2234 } else {
2235 DLOG(ERROR) <<
2236 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2240 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2241 PPB_Graphics3D_Impl* graphics_3d =
2242 enter_3d.succeeded()
2243 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2244 : NULL;
2246 if (compositor) {
2247 if (compositor->BindToInstance(this)) {
2248 bound_compositor_ = compositor;
2249 UpdateLayer(true);
2250 return PP_TRUE;
2252 } else if (graphics_2d) {
2253 if (graphics_2d->BindToInstance(this)) {
2254 bound_graphics_2d_platform_ = graphics_2d;
2255 UpdateLayer(true);
2256 return PP_TRUE;
2258 } else if (graphics_3d) {
2259 // Make sure graphics can only be bound to the instance it is
2260 // associated with.
2261 if (graphics_3d->pp_instance() == pp_instance() &&
2262 graphics_3d->BindToInstance(true)) {
2263 bound_graphics_3d_ = graphics_3d;
2264 UpdateLayer(true);
2265 return PP_TRUE;
2269 // The instance cannot be bound or the device is not a valid resource type.
2270 return PP_FALSE;
2273 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2274 return PP_FromBool(full_frame());
2277 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2278 return &view_data_;
2281 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2282 return PP_FromBool(flash_fullscreen_);
2285 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2286 if (!container_)
2287 return PP_MakeUndefined();
2288 RecordFlashJavaScriptUse();
2289 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2290 PepperTryCatchVar try_catch(this, &converter, NULL);
2291 WebLocalFrame* frame = container_->element().document().frame();
2292 if (!frame) {
2293 try_catch.SetException("No frame exists for window object.");
2294 return PP_MakeUndefined();
2297 ScopedPPVar result =
2298 try_catch.FromV8(frame->mainWorldScriptContext()->Global());
2299 DCHECK(!try_catch.HasException());
2300 return result.Release();
2303 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2304 if (!container_)
2305 return PP_MakeUndefined();
2306 RecordFlashJavaScriptUse();
2307 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2308 PepperTryCatchVar try_catch(this, &converter, NULL);
2309 ScopedPPVar result = try_catch.FromV8(container_->v8ObjectForElement());
2310 DCHECK(!try_catch.HasException());
2311 return result.Release();
2314 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2315 PP_Var script_var,
2316 PP_Var* exception) {
2317 if (!container_)
2318 return PP_MakeUndefined();
2319 if (is_deleted_ && blink::WebPluginScriptForbiddenScope::isForbidden())
2320 return PP_MakeUndefined();
2321 RecordFlashJavaScriptUse();
2323 // Executing the script may remove the plugin from the DOM, so we need to keep
2324 // a reference to ourselves so that we can still process the result after the
2325 // WebBindings::evaluate() below.
2326 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2327 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2328 PepperTryCatchVar try_catch(this, &converter, exception);
2330 // Check for an exception due to the context being destroyed.
2331 if (try_catch.HasException())
2332 return PP_MakeUndefined();
2334 WebLocalFrame* frame = container_->element().document().frame();
2335 if (!frame) {
2336 try_catch.SetException("No frame to execute script in.");
2337 return PP_MakeUndefined();
2340 StringVar* script_string_var = StringVar::FromPPVar(script_var);
2341 if (!script_string_var) {
2342 try_catch.SetException("Script param to ExecuteScript must be a string.");
2343 return PP_MakeUndefined();
2346 std::string script_string = script_string_var->value();
2347 blink::WebScriptSource script(
2348 blink::WebString::fromUTF8(script_string.c_str()));
2349 v8::Local<v8::Value> result;
2350 if (IsProcessingUserGesture()) {
2351 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2352 result = frame->executeScriptAndReturnValue(script);
2353 } else {
2354 result = frame->executeScriptAndReturnValue(script);
2357 ScopedPPVar var_result = try_catch.FromV8(result);
2358 if (try_catch.HasException())
2359 return PP_MakeUndefined();
2361 return var_result.Release();
2364 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2365 PP_Instance instance) {
2366 RenderThreadImpl* thread = RenderThreadImpl::current();
2367 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2370 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2371 PP_Instance instance) {
2372 RenderThreadImpl* thread = RenderThreadImpl::current();
2373 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2376 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2377 if (!render_frame_)
2378 return PP_MakeUndefined();
2379 return StringVar::StringToPPVar(
2380 render_frame_->render_view()->webkit_preferences().default_encoding);
2383 // These PPB_ContentDecryptor_Private calls are responses to
2384 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2385 // Therefore, |content_decryptor_delegate_| must have been initialized when
2386 // the following methods are called.
2387 void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2388 uint32 promise_id) {
2389 content_decryptor_delegate_->OnPromiseResolved(promise_id);
2392 void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2393 PP_Instance instance,
2394 uint32 promise_id,
2395 PP_Var session_id_var) {
2396 content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2397 session_id_var);
2400 void PepperPluginInstanceImpl::PromiseRejected(
2401 PP_Instance instance,
2402 uint32 promise_id,
2403 PP_CdmExceptionCode exception_code,
2404 uint32 system_code,
2405 PP_Var error_description_var) {
2406 content_decryptor_delegate_->OnPromiseRejected(
2407 promise_id, exception_code, system_code, error_description_var);
2410 void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2411 PP_Var session_id_var,
2412 PP_CdmMessageType message_type,
2413 PP_Var message_var,
2414 PP_Var legacy_destination_url) {
2415 content_decryptor_delegate_->OnSessionMessage(
2416 session_id_var, message_type, message_var, legacy_destination_url);
2419 void PepperPluginInstanceImpl::SessionKeysChange(
2420 PP_Instance instance,
2421 PP_Var session_id_var,
2422 PP_Bool has_additional_usable_key,
2423 uint32_t key_count,
2424 const struct PP_KeyInformation key_information[]) {
2425 content_decryptor_delegate_->OnSessionKeysChange(
2426 session_id_var, has_additional_usable_key, key_count, key_information);
2429 void PepperPluginInstanceImpl::SessionExpirationChange(
2430 PP_Instance instance,
2431 PP_Var session_id_var,
2432 PP_Time new_expiry_time) {
2433 content_decryptor_delegate_->OnSessionExpirationChange(session_id_var,
2434 new_expiry_time);
2437 void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2438 PP_Var session_id_var) {
2439 content_decryptor_delegate_->OnSessionClosed(session_id_var);
2442 void PepperPluginInstanceImpl::LegacySessionError(
2443 PP_Instance instance,
2444 PP_Var session_id_var,
2445 PP_CdmExceptionCode exception_code,
2446 uint32 system_code,
2447 PP_Var error_description_var) {
2448 content_decryptor_delegate_->OnLegacySessionError(
2449 session_id_var, exception_code, system_code, error_description_var);
2452 void PepperPluginInstanceImpl::DeliverBlock(
2453 PP_Instance instance,
2454 PP_Resource decrypted_block,
2455 const PP_DecryptedBlockInfo* block_info) {
2456 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2459 void PepperPluginInstanceImpl::DecoderInitializeDone(
2460 PP_Instance instance,
2461 PP_DecryptorStreamType decoder_type,
2462 uint32_t request_id,
2463 PP_Bool success) {
2464 content_decryptor_delegate_->DecoderInitializeDone(
2465 decoder_type, request_id, success);
2468 void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2469 PP_Instance instance,
2470 PP_DecryptorStreamType decoder_type,
2471 uint32_t request_id) {
2472 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2473 request_id);
2476 void PepperPluginInstanceImpl::DecoderResetDone(
2477 PP_Instance instance,
2478 PP_DecryptorStreamType decoder_type,
2479 uint32_t request_id) {
2480 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2483 void PepperPluginInstanceImpl::DeliverFrame(
2484 PP_Instance instance,
2485 PP_Resource decrypted_frame,
2486 const PP_DecryptedFrameInfo* frame_info) {
2487 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2490 void PepperPluginInstanceImpl::DeliverSamples(
2491 PP_Instance instance,
2492 PP_Resource audio_frames,
2493 const PP_DecryptedSampleInfo* sample_info) {
2494 content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2497 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2498 PP_Instance instance) {
2499 if (!LoadFindInterface())
2500 return;
2501 bool is_main_frame =
2502 render_frame_ &&
2503 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2504 if (!is_main_frame)
2505 return;
2506 render_frame_->render_view()->set_plugin_find_handler(this);
2509 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2510 PP_Instance instance,
2511 int32_t total,
2512 PP_Bool final_result) {
2513 DCHECK_NE(find_identifier_, -1);
2514 if (render_frame_) {
2515 render_frame_->reportFindInPageMatchCount(
2516 find_identifier_, total, PP_ToBool(final_result));
2520 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2521 int32_t index) {
2522 DCHECK_NE(find_identifier_, -1);
2523 if (render_frame_) {
2524 render_frame_->reportFindInPageSelection(
2525 find_identifier_, index + 1, blink::WebRect());
2529 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2530 const PP_Rect* tickmarks,
2531 uint32_t count) {
2532 if (!render_frame_ || !render_frame_->GetWebFrame())
2533 return;
2535 blink::WebVector<blink::WebRect> tickmarks_converted(
2536 static_cast<size_t>(count));
2537 for (uint32 i = 0; i < count; ++i) {
2538 tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2539 tickmarks[i].point.y,
2540 tickmarks[i].size.width,
2541 tickmarks[i].size.height);
2543 blink::WebFrame* frame = render_frame_->GetWebFrame();
2544 frame->setTickmarks(tickmarks_converted);
2547 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2548 return PP_FromBool(view_data_.is_fullscreen);
2551 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2552 PP_Bool fullscreen) {
2553 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2556 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2557 PP_Size* size) {
2558 if (flash_fullscreen_) {
2559 // Workaround for Flash rendering bug: Flash is assuming the fullscreen view
2560 // size will be equal to the physical screen size. However, the fullscreen
2561 // view is sized by the browser UI, and may not be the same size as the
2562 // screen or the desktop. Therefore, report the view size as the screen
2563 // size when in fullscreen mode. http://crbug.com/506016
2564 // TODO(miu): Remove this workaround once Flash has been fixed.
2565 *size = view_data_.rect.size;
2566 } else {
2567 // All other cases: Report the screen size.
2568 blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2569 *size = PP_MakeSize(info.rect.width, info.rect.height);
2571 return PP_TRUE;
2574 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2575 PP_Instance instance,
2576 ppapi::SingletonResourceID id) {
2577 // Flash APIs and some others aren't implemented in-process.
2578 switch (id) {
2579 case ppapi::BROKER_SINGLETON_ID:
2580 case ppapi::BROWSER_FONT_SINGLETON_ID:
2581 case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2582 case ppapi::FLASH_FILE_SINGLETON_ID:
2583 case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2584 case ppapi::FLASH_SINGLETON_ID:
2585 case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2586 case ppapi::NETWORK_PROXY_SINGLETON_ID:
2587 case ppapi::PDF_SINGLETON_ID:
2588 case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2589 NOTIMPLEMENTED();
2590 return NULL;
2591 case ppapi::GAMEPAD_SINGLETON_ID:
2592 return gamepad_impl_.get();
2593 case ppapi::UMA_SINGLETON_ID: {
2594 if (!uma_private_impl_.get()) {
2595 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2596 if (host_impl->in_process_router()) {
2597 uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2598 host_impl->in_process_router()->GetPluginConnection(instance),
2599 instance);
2602 return uma_private_impl_.get();
2606 NOTREACHED();
2607 return NULL;
2610 int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2611 uint32_t event_classes) {
2612 input_event_mask_ |= event_classes;
2613 filtered_input_event_mask_ &= ~(event_classes);
2614 RequestInputEventsHelper(event_classes);
2615 return ValidateRequestInputEvents(false, event_classes);
2618 int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2619 PP_Instance instance,
2620 uint32_t event_classes) {
2621 filtered_input_event_mask_ |= event_classes;
2622 input_event_mask_ &= ~(event_classes);
2623 RequestInputEventsHelper(event_classes);
2624 return ValidateRequestInputEvents(true, event_classes);
2627 void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2628 uint32_t event_classes) {
2629 input_event_mask_ &= ~(event_classes);
2630 filtered_input_event_mask_ &= ~(event_classes);
2631 RequestInputEventsHelper(event_classes);
2634 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2635 PP_Var message) {
2636 PostMessageToJavaScript(message);
2639 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2640 PP_MouseCursor_Type type,
2641 PP_Resource image,
2642 const PP_Point* hot_spot) {
2643 if (!ValidateSetCursorParams(type, image, hot_spot))
2644 return PP_FALSE;
2646 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2647 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2648 return PP_TRUE;
2651 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2652 if (enter.failed())
2653 return PP_FALSE;
2654 PPB_ImageData_Impl* image_data =
2655 static_cast<PPB_ImageData_Impl*>(enter.object());
2657 ImageDataAutoMapper auto_mapper(image_data);
2658 if (!auto_mapper.is_valid())
2659 return PP_FALSE;
2661 scoped_ptr<WebCursorInfo> custom_cursor(
2662 new WebCursorInfo(WebCursorInfo::TypeCustom));
2663 custom_cursor->hotSpot.x = hot_spot->x;
2664 custom_cursor->hotSpot.y = hot_spot->y;
2666 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2667 // Make a deep copy, so that the cursor remains valid even after the original
2668 // image data gets freed.
2669 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2670 return PP_FALSE;
2673 DoSetCursor(custom_cursor.release());
2674 return PP_TRUE;
2677 int32_t PepperPluginInstanceImpl::LockMouse(
2678 PP_Instance instance,
2679 scoped_refptr<TrackedCallback> callback) {
2680 if (TrackedCallback::IsPending(lock_mouse_callback_))
2681 return PP_ERROR_INPROGRESS;
2683 if (IsMouseLocked())
2684 return PP_OK;
2686 if (!CanAccessMainFrame())
2687 return PP_ERROR_NOACCESS;
2689 if (!IsProcessingUserGesture())
2690 return PP_ERROR_NO_USER_GESTURE;
2692 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2693 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2694 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2695 // Open a user gesture here so the Webkit user gesture checks will succeed
2696 // for out-of-process plugins.
2697 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2698 if (!LockMouse())
2699 return PP_ERROR_FAILED;
2702 // Either mouselock succeeded or a Flash fullscreen is pending.
2703 lock_mouse_callback_ = callback;
2704 return PP_OK_COMPLETIONPENDING;
2707 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2708 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2711 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2712 PP_TextInput_Type type) {
2713 if (!render_frame_)
2714 return;
2715 int itype = type;
2716 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2717 itype = ui::TEXT_INPUT_TYPE_NONE;
2718 SetTextInputType(static_cast<ui::TextInputType>(itype));
2721 void PepperPluginInstanceImpl::UpdateCaretPosition(
2722 PP_Instance instance,
2723 const PP_Rect& caret,
2724 const PP_Rect& bounding_box) {
2725 if (!render_frame_)
2726 return;
2727 text_input_caret_ = PP_ToGfxRect(caret);
2728 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2729 text_input_caret_set_ = true;
2730 render_frame_->PepperCaretPositionChanged(this);
2733 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2734 if (render_frame_)
2735 render_frame_->PepperCancelComposition(this);
2738 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2739 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2740 // It can be optimized so that it won't call it back until the information
2741 // is really needed.
2743 // Avoid calling in nested context or else this will reenter the plugin. This
2744 // uses a weak pointer rather than exploiting the fact that this class is
2745 // refcounted because we don't actually want this operation to affect the
2746 // lifetime of the instance.
2747 base::ThreadTaskRunnerHandle::Get()->PostTask(
2748 FROM_HERE, base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2749 weak_factory_.GetWeakPtr(),
2750 static_cast<size_t>(kExtraCharsForTextInput)));
2753 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2754 const char* text,
2755 uint32_t caret,
2756 uint32_t anchor) {
2757 if (!render_frame_)
2758 return;
2759 surrounding_text_ = text;
2760 selection_caret_ = caret;
2761 selection_anchor_ = anchor;
2762 render_frame_->PepperSelectionChanged(this);
2765 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2766 PP_Instance instance,
2767 PP_Var relative,
2768 PP_URLComponents_Dev* components) {
2769 StringVar* relative_string = StringVar::FromPPVar(relative);
2770 if (!relative_string)
2771 return PP_MakeNull();
2773 WebElement plugin_element = container()->element();
2774 GURL document_url = plugin_element.document().baseURL();
2775 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2776 document_url.Resolve(relative_string->value()), components);
2779 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2780 PP_Var url) {
2781 StringVar* url_string = StringVar::FromPPVar(url);
2782 if (!url_string)
2783 return PP_FALSE;
2785 blink::WebSecurityOrigin security_origin;
2786 if (!SecurityOriginForInstance(instance, &security_origin))
2787 return PP_FALSE;
2789 GURL gurl(url_string->value());
2790 if (!gurl.is_valid())
2791 return PP_FALSE;
2793 return PP_FromBool(security_origin.canRequest(gurl));
2796 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2797 PP_Instance instance,
2798 PP_Instance target) {
2799 blink::WebSecurityOrigin our_origin;
2800 if (!SecurityOriginForInstance(instance, &our_origin))
2801 return PP_FALSE;
2803 blink::WebSecurityOrigin target_origin;
2804 if (!SecurityOriginForInstance(instance, &target_origin))
2805 return PP_FALSE;
2807 return PP_FromBool(our_origin.canAccess(target_origin));
2810 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2811 PP_Instance instance,
2812 PP_URLComponents_Dev* components) {
2813 blink::WebDocument document = container()->element().document();
2814 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2815 components);
2818 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2819 PP_Instance instance,
2820 PP_URLComponents_Dev* components) {
2821 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2824 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2825 PP_Instance instance,
2826 PP_URLComponents_Dev* components) {
2827 blink::WebDocument document = container()->element().document();
2828 if (!full_frame_)
2829 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2830 components);
2831 WebLocalFrame* frame = document.frame();
2832 if (!frame)
2833 return PP_MakeUndefined();
2834 const WebURLRequest& request = frame->dataSource()->originalRequest();
2835 WebString referer = request.httpHeaderField("Referer");
2836 if (referer.isEmpty())
2837 return PP_MakeUndefined();
2838 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2839 components);
2842 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2843 scoped_refptr<PluginModule> module) {
2844 // Save the original module and switch over to the new one now that this
2845 // plugin is using the IPC-based proxy.
2846 original_module_ = module_;
2847 module_ = module;
2849 // For NaCl instances, remember the NaCl plugin instance interface, so we
2850 // can shut it down by calling its DidDestroy in our Delete() method.
2851 original_instance_interface_.reset(instance_interface_.release());
2853 base::Callback<const void*(const char*)> get_plugin_interface_func =
2854 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2855 PPP_Instance_Combined* ppp_instance_combined =
2856 PPP_Instance_Combined::Create(get_plugin_interface_func);
2857 if (!ppp_instance_combined) {
2858 // The proxy must support at least one usable PPP_Instance interface.
2859 // While this could be a failure to implement the interface in the NaCl
2860 // module, it is more likely that the NaCl process has crashed. Either
2861 // way, report that module initialization failed.
2862 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2865 instance_interface_.reset(ppp_instance_combined);
2866 // Clear all PPP interfaces we may have cached.
2867 plugin_find_interface_ = NULL;
2868 plugin_input_event_interface_ = NULL;
2869 checked_for_plugin_input_event_interface_ = false;
2870 plugin_mouse_lock_interface_ = NULL;
2871 plugin_pdf_interface_ = NULL;
2872 checked_for_plugin_pdf_interface_ = false;
2873 plugin_private_interface_ = NULL;
2874 plugin_textinput_interface_ = NULL;
2876 // Re-send the DidCreate event via the proxy.
2877 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2878 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2879 if (!instance_interface_->DidCreate(
2880 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2881 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2882 if (message_channel_)
2883 message_channel_->Start();
2885 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2886 // event. This way, SendDidChangeView will send the "current" view
2887 // immediately (before other events like HandleDocumentLoad).
2888 sent_initial_did_change_view_ = false;
2889 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2890 SendDidChangeView();
2892 DCHECK(external_document_load_);
2893 external_document_load_ = false;
2894 if (!external_document_response_.isNull()) {
2895 document_loader_ = NULL;
2896 // Pass the response to the new proxy.
2897 HandleDocumentLoad(external_document_response_);
2898 external_document_response_ = blink::WebURLResponse();
2899 // Replay any document load events we've received to the real loader.
2900 external_document_loader_->ReplayReceivedData(document_loader_);
2901 external_document_loader_.reset(NULL);
2904 return PP_EXTERNAL_PLUGIN_OK;
2907 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2908 DCHECK(module);
2909 return module == module_.get() || module == original_module_.get();
2912 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2913 return HostGlobals::Get()->GetInstance(instance_id);
2916 RenderView* PepperPluginInstanceImpl::GetRenderView() {
2917 return render_frame_ ? render_frame_->render_view() : NULL;
2920 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2921 return container_;
2924 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
2926 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
2927 return HostGlobals::Get()->GetVarTracker();
2930 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
2932 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
2933 return module_->path();
2936 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
2937 float scale) {
2938 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
2940 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
2941 return 0;
2943 scoped_refptr<PPB_ImageData_Impl> image_data(
2944 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
2945 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
2946 image_skia_rep.pixel_width(),
2947 image_skia_rep.pixel_height(),
2948 false)) {
2949 return 0;
2952 ImageDataAutoMapper mapper(image_data.get());
2953 if (!mapper.is_valid())
2954 return 0;
2956 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
2957 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
2958 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
2959 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
2961 return image_data->GetReference();
2964 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
2965 const base::FilePath& file_path,
2966 ppapi::PpapiPermissions permissions,
2967 const IPC::ChannelHandle& channel_handle,
2968 base::ProcessId plugin_pid,
2969 int plugin_child_id) {
2970 // Create a new module for each instance of the external plugin that is using
2971 // the IPC based out-of-process proxy. We can't use the existing module,
2972 // because it is configured for the in-process plugin, and we must keep it
2973 // that way to allow the page to create other instances.
2974 scoped_refptr<PluginModule> external_plugin_module(
2975 module_->CreateModuleForExternalPluginInstance());
2977 RendererPpapiHostImpl* renderer_ppapi_host =
2978 external_plugin_module->CreateOutOfProcessModule(render_frame_,
2979 file_path,
2980 permissions,
2981 channel_handle,
2982 plugin_pid,
2983 plugin_child_id,
2984 true);
2985 if (!renderer_ppapi_host) {
2986 DLOG(ERROR) << "CreateExternalPluginModule() failed";
2987 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2990 // Finally, switch the instance to the proxy.
2991 return external_plugin_module->InitAsProxiedExternalPlugin(this);
2994 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
2995 always_on_top_ = on_top;
2998 void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
2999 cursor_.reset(cursor);
3000 if (fullscreen_container_) {
3001 fullscreen_container_->DidChangeCursor(*cursor);
3002 } else if (render_frame_) {
3003 render_frame_->PepperDidChangeCursor(this, *cursor);
3007 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3008 WebLocalFrame* frame = container()->element().document().frame();
3009 return frame->view()->mainFrame()->document().isPluginDocument();
3012 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3013 bool delay_report) {
3014 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3015 // Keep a reference on the stack. See NOTE above.
3016 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3018 // We check whether we are trying to switch to the state we're already going
3019 // to (i.e. if we're already switching to fullscreen but the fullscreen
3020 // container isn't ready yet, don't do anything more).
3021 if (fullscreen == FlashIsFullscreenOrPending())
3022 return true;
3024 if (!render_frame_)
3025 return false;
3026 if (fullscreen && !render_frame_->render_view()
3027 ->renderer_preferences()
3028 .plugin_fullscreen_allowed)
3029 return false;
3031 // Unbind current 2D or 3D graphics context.
3032 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3033 if (fullscreen) {
3034 DCHECK(!fullscreen_container_);
3035 fullscreen_container_ =
3036 render_frame_->CreatePepperFullscreenContainer(this);
3037 UpdateLayer(false);
3038 } else {
3039 DCHECK(fullscreen_container_);
3040 fullscreen_container_->Destroy();
3041 fullscreen_container_ = NULL;
3042 UpdateFlashFullscreenState(false);
3043 if (!delay_report) {
3044 ReportGeometry();
3045 } else {
3046 base::ThreadTaskRunnerHandle::Get()->PostTask(
3047 FROM_HERE,
3048 base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3052 return true;
3055 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3056 if (flash_fullscreen_)
3057 return true;
3059 return container_->isRectTopmost(rect);
3062 int32_t PepperPluginInstanceImpl::Navigate(
3063 const ppapi::URLRequestInfoData& request,
3064 const char* target,
3065 bool from_user_action) {
3066 if (!container_)
3067 return PP_ERROR_FAILED;
3069 WebDocument document = container_->element().document();
3070 WebLocalFrame* frame = document.frame();
3071 if (!frame)
3072 return PP_ERROR_FAILED;
3074 ppapi::URLRequestInfoData completed_request = request;
3076 WebURLRequest web_request;
3077 if (!CreateWebURLRequest(
3078 pp_instance_, &completed_request, frame, &web_request)) {
3079 return PP_ERROR_FAILED;
3081 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3082 if (IsProcessingUserGesture())
3083 web_request.setHasUserGesture(true);
3085 GURL gurl(web_request.url());
3086 if (gurl.SchemeIs(url::kJavaScriptScheme)) {
3087 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3088 // allowed for security reasons.
3089 WebFrame* target_frame =
3090 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3091 if (target_frame != frame)
3092 return PP_ERROR_NOACCESS;
3094 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3095 // need that?
3096 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
3097 WebString result = container_->executeScriptURL(gurl, false);
3098 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3101 // Only GETs and POSTs are supported.
3102 if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3103 return PP_ERROR_BADARGUMENT;
3105 WebString target_str = WebString::fromUTF8(target);
3106 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
3107 container_->loadFrameRequest(web_request, target_str, false, NULL);
3108 return PP_OK;
3111 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3112 const base::FilePath& path) {
3113 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3114 PepperFileRefRendererHost* file_ref_host(
3115 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3116 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3117 scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3120 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3121 if (message_channel_)
3122 message_channel_->SetReadOnlyProperty(key, value);
3125 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3126 if (!container_)
3127 return false;
3128 blink::WebDocument containing_document = container_->element().document();
3130 if (!containing_document.frame() || !containing_document.frame()->view() ||
3131 !containing_document.frame()->view()->mainFrame()) {
3132 return false;
3134 blink::WebDocument main_document =
3135 containing_document.frame()->view()->mainFrame()->document();
3137 return containing_document.securityOrigin().canAccess(
3138 main_document.securityOrigin());
3141 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3142 WebElement element = container_->element();
3143 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3144 height_before_fullscreen_ =
3145 element.getAttribute(WebString::fromUTF8(kHeight));
3146 border_before_fullscreen_ =
3147 element.getAttribute(WebString::fromUTF8(kBorder));
3148 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3151 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3152 if (!render_frame_)
3153 return;
3155 // TODO(miu): Revisit this logic. If the style must be modified for correct
3156 // behavior, the width and height should probably be set to 100%, rather than
3157 // a fixed screen size.
3159 blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3160 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3161 std::string width = base::IntToString(screen_size_for_fullscreen_.width());
3162 std::string height = base::IntToString(screen_size_for_fullscreen_.height());
3164 WebElement element = container_->element();
3165 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3166 element.setAttribute(WebString::fromUTF8(kHeight),
3167 WebString::fromUTF8(height));
3168 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3170 // There should be no style settings that matter in fullscreen mode,
3171 // so just replace them instead of appending.
3172 // NOTE: "position: fixed" and "display: block" reset the plugin and
3173 // using %% settings might not work without them (e.g. if the plugin is a
3174 // child of a container element).
3175 std::string style;
3176 style += StringPrintf("width: %s !important; ", width.c_str());
3177 style += StringPrintf("height: %s !important; ", height.c_str());
3178 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3179 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3182 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3183 screen_size_for_fullscreen_ = gfx::Size();
3184 WebElement element = container_->element();
3185 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3186 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3187 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3188 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3191 bool PepperPluginInstanceImpl::IsMouseLocked() {
3192 return GetMouseLockDispatcher()->IsMouseLockedTo(
3193 GetOrCreateLockTargetAdapter());
3196 bool PepperPluginInstanceImpl::LockMouse() {
3197 return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3200 MouseLockDispatcher::LockTarget*
3201 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3202 if (!lock_target_.get()) {
3203 lock_target_.reset(new PluginInstanceLockTarget(this));
3205 return lock_target_.get();
3208 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3209 if (flash_fullscreen_) {
3210 RenderWidgetFullscreenPepper* container =
3211 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3212 return container->mouse_lock_dispatcher();
3213 } else if (render_frame_) {
3214 return render_frame_->render_view()->mouse_lock_dispatcher();
3216 return NULL;
3219 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3220 if (lock_target_.get()) {
3221 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3222 lock_target_.reset();
3226 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3227 const blink::WebURLResponse& response,
3228 int pending_host_id,
3229 const ppapi::URLResponseInfoData& data) {
3230 if (is_deleted_)
3231 return;
3233 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3235 if (host_impl->in_process_router()) {
3236 // Running in-process, we can just create the resource and call the
3237 // PPP_Instance function directly.
3238 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3239 new ppapi::proxy::URLLoaderResource(
3240 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3241 pp_instance(),
3242 pending_host_id,
3243 data));
3245 PP_Resource loader_pp_resource = loader_resource->GetReference();
3246 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3247 loader_pp_resource))
3248 loader_resource->Close();
3249 // We don't pass a ref into the plugin, if it wants one, it will have taken
3250 // an additional one.
3251 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3252 loader_pp_resource);
3253 } else {
3254 // Running out-of-process. Initiate an IPC call to notify the plugin
3255 // process.
3256 ppapi::proxy::HostDispatcher* dispatcher =
3257 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3258 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3259 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3263 void PepperPluginInstanceImpl::RecordFlashJavaScriptUse() {
3264 if (initialized_ && !javascript_used_ && is_flash_plugin_) {
3265 javascript_used_ = true;
3266 RenderThread::Get()->RecordAction(
3267 base::UserMetricsAction("Flash.JavaScriptUsed"));
3271 } // namespace content