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