third_party/re2: Remove remove-static-initializers.patch.
[chromium-blink-merge.git] / content / renderer / pepper / pepper_plugin_instance_impl.cc
blob00e2f0508be54c77aee19816e6b11e8061f28039
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/metrics/histogram.h"
13 #include "base/stl_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_offset_string_conversions.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/time/time.h"
18 #include "base/trace_event/trace_event.h"
19 #include "cc/blink/web_layer_impl.h"
20 #include "cc/layers/texture_layer.h"
21 #include "cc/output/latency_info_swap_promise.h"
22 #include "cc/trees/layer_tree_host.h"
23 #include "content/common/content_constants_internal.h"
24 #include "content/common/frame_messages.h"
25 #include "content/common/input/web_input_event_traits.h"
26 #include "content/common/view_messages.h"
27 #include "content/public/common/content_constants.h"
28 #include "content/public/common/page_zoom.h"
29 #include "content/public/renderer/content_renderer_client.h"
30 #include "content/renderer/gpu/render_widget_compositor.h"
31 #include "content/renderer/pepper/content_decryptor_delegate.h"
32 #include "content/renderer/pepper/event_conversion.h"
33 #include "content/renderer/pepper/fullscreen_container.h"
34 #include "content/renderer/pepper/gfx_conversion.h"
35 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
36 #include "content/renderer/pepper/host_globals.h"
37 #include "content/renderer/pepper/message_channel.h"
38 #include "content/renderer/pepper/pepper_browser_connection.h"
39 #include "content/renderer/pepper/pepper_compositor_host.h"
40 #include "content/renderer/pepper/pepper_file_ref_renderer_host.h"
41 #include "content/renderer/pepper/pepper_graphics_2d_host.h"
42 #include "content/renderer/pepper/pepper_in_process_router.h"
43 #include "content/renderer/pepper/pepper_plugin_instance_metrics.h"
44 #include "content/renderer/pepper/pepper_try_catch.h"
45 #include "content/renderer/pepper/pepper_url_loader_host.h"
46 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
47 #include "content/renderer/pepper/plugin_module.h"
48 #include "content/renderer/pepper/plugin_object.h"
49 #include "content/renderer/pepper/ppapi_preferences_builder.h"
50 #include "content/renderer/pepper/ppb_buffer_impl.h"
51 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
52 #include "content/renderer/pepper/ppb_image_data_impl.h"
53 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
54 #include "content/renderer/pepper/url_request_info_util.h"
55 #include "content/renderer/pepper/url_response_info_util.h"
56 #include "content/renderer/render_frame_impl.h"
57 #include "content/renderer/render_thread_impl.h"
58 #include "content/renderer/render_view_impl.h"
59 #include "content/renderer/render_widget.h"
60 #include "content/renderer/render_widget_fullscreen_pepper.h"
61 #include "content/renderer/sad_plugin.h"
62 #include "media/base/audio_hardware_config.h"
63 #include "ppapi/c/dev/ppb_zoom_dev.h"
64 #include "ppapi/c/dev/ppp_selection_dev.h"
65 #include "ppapi/c/dev/ppp_text_input_dev.h"
66 #include "ppapi/c/dev/ppp_zoom_dev.h"
67 #include "ppapi/c/pp_rect.h"
68 #include "ppapi/c/ppb_audio_config.h"
69 #include "ppapi/c/ppb_core.h"
70 #include "ppapi/c/ppb_gamepad.h"
71 #include "ppapi/c/ppp_input_event.h"
72 #include "ppapi/c/ppp_instance.h"
73 #include "ppapi/c/ppp_messaging.h"
74 #include "ppapi/c/ppp_mouse_lock.h"
75 #include "ppapi/c/private/ppb_find_private.h"
76 #include "ppapi/c/private/ppp_find_private.h"
77 #include "ppapi/c/private/ppp_instance_private.h"
78 #include "ppapi/c/private/ppp_pdf.h"
79 #include "ppapi/host/ppapi_host.h"
80 #include "ppapi/proxy/ppapi_messages.h"
81 #include "ppapi/proxy/serialized_var.h"
82 #include "ppapi/proxy/uma_private_resource.h"
83 #include "ppapi/proxy/url_loader_resource.h"
84 #include "ppapi/shared_impl/ppapi_permissions.h"
85 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
86 #include "ppapi/shared_impl/ppb_input_event_shared.h"
87 #include "ppapi/shared_impl/ppb_url_util_shared.h"
88 #include "ppapi/shared_impl/ppb_view_shared.h"
89 #include "ppapi/shared_impl/ppp_instance_combined.h"
90 #include "ppapi/shared_impl/resource.h"
91 #include "ppapi/shared_impl/scoped_pp_resource.h"
92 #include "ppapi/shared_impl/scoped_pp_var.h"
93 #include "ppapi/shared_impl/time_conversion.h"
94 #include "ppapi/shared_impl/url_request_info_data.h"
95 #include "ppapi/shared_impl/var.h"
96 #include "ppapi/thunk/enter.h"
97 #include "ppapi/thunk/ppb_buffer_api.h"
98 #include "printing/metafile_skia_wrapper.h"
99 #include "printing/pdf_metafile_skia.h"
100 #include "skia/ext/platform_canvas.h"
101 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
102 #include "third_party/WebKit/public/platform/WebGamepads.h"
103 #include "third_party/WebKit/public/platform/WebRect.h"
104 #include "third_party/WebKit/public/platform/WebString.h"
105 #include "third_party/WebKit/public/platform/WebURL.h"
106 #include "third_party/WebKit/public/platform/WebURLError.h"
107 #include "third_party/WebKit/public/platform/WebURLRequest.h"
108 #include "third_party/WebKit/public/web/WebBindings.h"
109 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
110 #include "third_party/WebKit/public/web/WebDataSource.h"
111 #include "third_party/WebKit/public/web/WebDocument.h"
112 #include "third_party/WebKit/public/web/WebInputEvent.h"
113 #include "third_party/WebKit/public/web/WebLocalFrame.h"
114 #include "third_party/WebKit/public/web/WebPluginContainer.h"
115 #include "third_party/WebKit/public/web/WebPrintParams.h"
116 #include "third_party/WebKit/public/web/WebPrintPresetOptions.h"
117 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
118 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
119 #include "third_party/WebKit/public/web/WebScriptSource.h"
120 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
121 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
122 #include "third_party/WebKit/public/web/WebView.h"
123 #include "third_party/khronos/GLES2/gl2.h"
124 #include "ui/gfx/image/image_skia.h"
125 #include "ui/gfx/image/image_skia_rep.h"
126 #include "ui/gfx/range/range.h"
127 #include "v8/include/v8.h"
129 #if defined(OS_CHROMEOS)
130 #include "ui/events/keycodes/keyboard_codes_posix.h"
131 #endif
133 using base::StringPrintf;
134 using ppapi::InputEventData;
135 using ppapi::PpapiGlobals;
136 using ppapi::PPB_InputEvent_Shared;
137 using ppapi::PPB_View_Shared;
138 using ppapi::PPP_Instance_Combined;
139 using ppapi::Resource;
140 using ppapi::ScopedPPResource;
141 using ppapi::ScopedPPVar;
142 using ppapi::StringVar;
143 using ppapi::TrackedCallback;
144 using ppapi::thunk::EnterResourceNoLock;
145 using ppapi::thunk::PPB_Buffer_API;
146 using ppapi::thunk::PPB_Gamepad_API;
147 using ppapi::thunk::PPB_Graphics2D_API;
148 using ppapi::thunk::PPB_Graphics3D_API;
149 using ppapi::thunk::PPB_ImageData_API;
150 using ppapi::Var;
151 using ppapi::ArrayBufferVar;
152 using ppapi::ViewData;
153 using blink::WebBindings;
154 using blink::WebCanvas;
155 using blink::WebCursorInfo;
156 using blink::WebDocument;
157 using blink::WebElement;
158 using blink::WebFrame;
159 using blink::WebInputEvent;
160 using blink::WebLocalFrame;
161 using blink::WebPlugin;
162 using blink::WebPluginContainer;
163 using blink::WebPrintParams;
164 using blink::WebPrintScalingOption;
165 using blink::WebScopedUserGesture;
166 using blink::WebString;
167 using blink::WebURLError;
168 using blink::WebURLLoader;
169 using blink::WebURLLoaderClient;
170 using blink::WebURLRequest;
171 using blink::WebURLResponse;
172 using blink::WebUserGestureIndicator;
173 using blink::WebUserGestureToken;
174 using blink::WebView;
176 namespace content {
178 namespace {
180 #define STATIC_ASSERT_PP_MATCHING_ENUM(a, b) \
181 static_assert(static_cast<int>(a) == static_cast<int>(b), \
182 "mismatching enums: " #a)
184 // Check PP_TextInput_Type and ui::TextInputType are kept in sync.
185 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_NONE,
186 PP_TEXTINPUT_TYPE_NONE);
187 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_TEXT,
188 PP_TEXTINPUT_TYPE_TEXT);
189 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_PASSWORD,
190 PP_TEXTINPUT_TYPE_PASSWORD);
191 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_SEARCH,
192 PP_TEXTINPUT_TYPE_SEARCH);
193 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_EMAIL,
194 PP_TEXTINPUT_TYPE_EMAIL);
195 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_NUMBER,
196 PP_TEXTINPUT_TYPE_NUMBER);
197 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_TELEPHONE,
198 PP_TEXTINPUT_TYPE_TELEPHONE);
199 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_URL,
200 PP_TEXTINPUT_TYPE_URL);
202 // The default text input type is to regard the plugin always accept text input.
203 // This is for allowing users to use input methods even on completely-IME-
204 // unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
205 // Plugins need to explicitly opt out the text input mode if they know
206 // that they don't accept texts.
207 const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
209 // <embed>/<object> attributes.
210 const char kWidth[] = "width";
211 const char kHeight[] = "height";
212 const char kBorder[] = "border"; // According to w3c, deprecated.
213 const char kStyle[] = "style";
215 #define STATIC_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
216 static_assert(static_cast<int>(WebCursorInfo::webkit_name) == \
217 static_cast<int>(np_name), \
218 "mismatching enums: " #webkit_name)
220 STATIC_ASSERT_MATCHING_ENUM(TypePointer, PP_MOUSECURSOR_TYPE_POINTER);
221 STATIC_ASSERT_MATCHING_ENUM(TypeCross, PP_MOUSECURSOR_TYPE_CROSS);
222 STATIC_ASSERT_MATCHING_ENUM(TypeHand, PP_MOUSECURSOR_TYPE_HAND);
223 STATIC_ASSERT_MATCHING_ENUM(TypeIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
224 STATIC_ASSERT_MATCHING_ENUM(TypeWait, PP_MOUSECURSOR_TYPE_WAIT);
225 STATIC_ASSERT_MATCHING_ENUM(TypeHelp, PP_MOUSECURSOR_TYPE_HELP);
226 STATIC_ASSERT_MATCHING_ENUM(TypeEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
227 STATIC_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
228 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastResize,
229 PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
230 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestResize,
231 PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
232 STATIC_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
233 STATIC_ASSERT_MATCHING_ENUM(TypeSouthEastResize,
234 PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
235 STATIC_ASSERT_MATCHING_ENUM(TypeSouthWestResize,
236 PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
237 STATIC_ASSERT_MATCHING_ENUM(TypeWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
238 STATIC_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
239 PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
240 STATIC_ASSERT_MATCHING_ENUM(TypeEastWestResize,
241 PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
242 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
243 PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
244 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
245 PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
246 STATIC_ASSERT_MATCHING_ENUM(TypeColumnResize,
247 PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
248 STATIC_ASSERT_MATCHING_ENUM(TypeRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
249 STATIC_ASSERT_MATCHING_ENUM(TypeMiddlePanning,
250 PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
251 STATIC_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
252 STATIC_ASSERT_MATCHING_ENUM(TypeNorthPanning,
253 PP_MOUSECURSOR_TYPE_NORTHPANNING);
254 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
255 PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
256 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
257 PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
258 STATIC_ASSERT_MATCHING_ENUM(TypeSouthPanning,
259 PP_MOUSECURSOR_TYPE_SOUTHPANNING);
260 STATIC_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
261 PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
262 STATIC_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
263 PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
264 STATIC_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
265 STATIC_ASSERT_MATCHING_ENUM(TypeMove, PP_MOUSECURSOR_TYPE_MOVE);
266 STATIC_ASSERT_MATCHING_ENUM(TypeVerticalText,
267 PP_MOUSECURSOR_TYPE_VERTICALTEXT);
268 STATIC_ASSERT_MATCHING_ENUM(TypeCell, PP_MOUSECURSOR_TYPE_CELL);
269 STATIC_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
270 STATIC_ASSERT_MATCHING_ENUM(TypeAlias, PP_MOUSECURSOR_TYPE_ALIAS);
271 STATIC_ASSERT_MATCHING_ENUM(TypeProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
272 STATIC_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
273 STATIC_ASSERT_MATCHING_ENUM(TypeCopy, PP_MOUSECURSOR_TYPE_COPY);
274 STATIC_ASSERT_MATCHING_ENUM(TypeNone, PP_MOUSECURSOR_TYPE_NONE);
275 STATIC_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
276 STATIC_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
277 STATIC_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
278 STATIC_ASSERT_MATCHING_ENUM(TypeGrab, PP_MOUSECURSOR_TYPE_GRAB);
279 STATIC_ASSERT_MATCHING_ENUM(TypeGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
280 // Do not assert WebCursorInfo::TypeCustom == PP_CURSORTYPE_CUSTOM;
281 // PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
283 STATIC_ASSERT_PP_MATCHING_ENUM(blink::WebPrintScalingOptionNone,
284 PP_PRINTSCALINGOPTION_NONE);
285 STATIC_ASSERT_PP_MATCHING_ENUM(
286 blink::WebPrintScalingOptionFitToPrintableArea,
287 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
288 STATIC_ASSERT_PP_MATCHING_ENUM(
289 blink::WebPrintScalingOptionSourceSize,
290 PP_PRINTSCALINGOPTION_SOURCE_SIZE);
292 // Sets |*security_origin| to be the WebKit security origin associated with the
293 // document containing the given plugin instance. On success, returns true. If
294 // the instance is invalid, returns false and |*security_origin| will be
295 // unchanged.
296 bool SecurityOriginForInstance(PP_Instance instance_id,
297 blink::WebSecurityOrigin* security_origin) {
298 PepperPluginInstanceImpl* instance =
299 HostGlobals::Get()->GetInstance(instance_id);
300 if (!instance)
301 return false;
303 WebElement plugin_element = instance->container()->element();
304 *security_origin = plugin_element.document().securityOrigin();
305 return true;
308 // Convert the given vector to an array of C-strings. The strings in the
309 // returned vector are only guaranteed valid so long as the vector of strings
310 // is not modified.
311 scoped_ptr<const char* []> StringVectorToArgArray(
312 const std::vector<std::string>& vector) {
313 scoped_ptr<const char * []> array(new const char* [vector.size()]);
314 for (size_t i = 0; i < vector.size(); ++i)
315 array[i] = vector[i].c_str();
316 return array.Pass();
319 // Returns true if this is a "system reserved" key which should not be sent to
320 // a plugin. Some poorly behaving plugins (like Flash) incorrectly report that
321 // they handle all keys sent to them. This can prevent keystrokes from working
322 // for things like screen brightness and volume control.
323 bool IsReservedSystemInputEvent(const blink::WebInputEvent& event) {
324 #if defined(OS_CHROMEOS)
325 if (event.type != WebInputEvent::KeyDown &&
326 event.type != WebInputEvent::KeyUp)
327 return false;
328 const blink::WebKeyboardEvent& key_event =
329 static_cast<const blink::WebKeyboardEvent&>(event);
330 switch (key_event.windowsKeyCode) {
331 case ui::VKEY_BRIGHTNESS_DOWN:
332 case ui::VKEY_BRIGHTNESS_UP:
333 case ui::VKEY_KBD_BRIGHTNESS_DOWN:
334 case ui::VKEY_KBD_BRIGHTNESS_UP:
335 case ui::VKEY_VOLUME_MUTE:
336 case ui::VKEY_VOLUME_DOWN:
337 case ui::VKEY_VOLUME_UP:
338 return true;
339 default:
340 return false;
342 #endif // defined(OS_CHROMEOS)
343 return false;
346 class PluginInstanceLockTarget : public MouseLockDispatcher::LockTarget {
347 public:
348 explicit PluginInstanceLockTarget(PepperPluginInstanceImpl* plugin)
349 : plugin_(plugin) {}
351 void OnLockMouseACK(bool succeeded) override {
352 plugin_->OnLockMouseACK(succeeded);
355 void OnMouseLockLost() override { plugin_->OnMouseLockLost(); }
357 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
358 plugin_->HandleMouseLockedInputEvent(event);
359 return true;
362 private:
363 PepperPluginInstanceImpl* plugin_;
366 void InitLatencyInfo(ui::LatencyInfo* new_latency,
367 const ui::LatencyInfo* old_latency,
368 blink::WebInputEvent::Type type,
369 int64 input_sequence) {
370 new_latency->AddLatencyNumberWithTraceName(
371 ui::INPUT_EVENT_LATENCY_BEGIN_PLUGIN_COMPONENT,
373 input_sequence,
374 WebInputEventTraits::GetName(type));
375 if (old_latency) {
376 new_latency->CopyLatencyFrom(*old_latency,
377 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
378 new_latency->CopyLatencyFrom(*old_latency,
379 ui::INPUT_EVENT_LATENCY_UI_COMPONENT);
383 } // namespace
385 // static
386 PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
387 RenderFrameImpl* render_frame,
388 PluginModule* module,
389 WebPluginContainer* container,
390 const GURL& plugin_url) {
391 base::Callback<const void*(const char*)> get_plugin_interface_func =
392 base::Bind(&PluginModule::GetPluginInterface, module);
393 PPP_Instance_Combined* ppp_instance_combined =
394 PPP_Instance_Combined::Create(get_plugin_interface_func);
395 if (!ppp_instance_combined)
396 return NULL;
398 return new PepperPluginInstanceImpl(render_frame,
399 module,
400 ppp_instance_combined,
401 container,
402 plugin_url);
405 PepperPluginInstanceImpl::ExternalDocumentLoader::ExternalDocumentLoader()
406 : finished_loading_(false) {}
408 PepperPluginInstanceImpl::ExternalDocumentLoader::~ExternalDocumentLoader() {}
410 void PepperPluginInstanceImpl::ExternalDocumentLoader::ReplayReceivedData(
411 WebURLLoaderClient* document_loader) {
412 for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
413 ++it) {
414 document_loader->didReceiveData(
415 NULL, it->c_str(), it->length(), 0 /* encoded_data_length */);
417 if (finished_loading_) {
418 document_loader->didFinishLoading(
419 NULL,
420 0 /* finish_time */,
421 blink::WebURLLoaderClient::kUnknownEncodedDataLength);
423 if (error_.get()) {
424 document_loader->didFail(NULL, *error_);
428 void PepperPluginInstanceImpl::ExternalDocumentLoader::didReceiveData(
429 WebURLLoader* loader,
430 const char* data,
431 int data_length,
432 int encoded_data_length) {
433 data_.push_back(std::string(data, data_length));
436 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFinishLoading(
437 WebURLLoader* loader,
438 double finish_time,
439 int64_t total_encoded_data_length) {
440 DCHECK(!finished_loading_);
441 finished_loading_ = true;
444 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFail(
445 WebURLLoader* loader,
446 const WebURLError& error) {
447 DCHECK(!error_.get());
448 error_.reset(new WebURLError(error));
451 PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
452 : Resource(ppapi::Resource::Untracked()) {}
454 PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
456 PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
457 return this;
460 void PepperPluginInstanceImpl::GamepadImpl::Sample(
461 PP_Instance instance,
462 PP_GamepadsSampleData* data) {
463 blink::WebGamepads webkit_data;
464 RenderThreadImpl::current()->SampleGamepads(&webkit_data);
465 ConvertWebKitGamepadData(bit_cast<ppapi::WebKitGamepads>(webkit_data), data);
468 PepperPluginInstanceImpl::PepperPluginInstanceImpl(
469 RenderFrameImpl* render_frame,
470 PluginModule* module,
471 ppapi::PPP_Instance_Combined* instance_interface,
472 WebPluginContainer* container,
473 const GURL& plugin_url)
474 : RenderFrameObserver(render_frame),
475 render_frame_(render_frame),
476 module_(module),
477 instance_interface_(instance_interface),
478 pp_instance_(0),
479 container_(container),
480 layer_bound_to_fullscreen_(false),
481 layer_is_hardware_(false),
482 plugin_url_(plugin_url),
483 document_url_(container ? GURL(container->element().document().url())
484 : GURL()),
485 is_flash_plugin_(module->name() == kFlashPluginName),
486 has_been_clicked_(false),
487 javascript_used_(false),
488 full_frame_(false),
489 sent_initial_did_change_view_(false),
490 bound_graphics_2d_platform_(NULL),
491 bound_compositor_(NULL),
492 has_webkit_focus_(false),
493 has_content_area_focus_(false),
494 find_identifier_(-1),
495 plugin_find_interface_(NULL),
496 plugin_input_event_interface_(NULL),
497 plugin_mouse_lock_interface_(NULL),
498 plugin_pdf_interface_(NULL),
499 plugin_private_interface_(NULL),
500 plugin_textinput_interface_(NULL),
501 plugin_zoom_interface_(NULL),
502 checked_for_plugin_input_event_interface_(false),
503 checked_for_plugin_pdf_interface_(false),
504 gamepad_impl_(new GamepadImpl()),
505 uma_private_impl_(NULL),
506 plugin_print_interface_(NULL),
507 plugin_graphics_3d_interface_(NULL),
508 always_on_top_(false),
509 fullscreen_container_(NULL),
510 flash_fullscreen_(false),
511 desired_fullscreen_state_(false),
512 message_channel_(NULL),
513 sad_plugin_(NULL),
514 input_event_mask_(0),
515 filtered_input_event_mask_(0),
516 text_input_type_(kPluginDefaultTextInputType),
517 text_input_caret_(0, 0, 0, 0),
518 text_input_caret_bounds_(0, 0, 0, 0),
519 text_input_caret_set_(false),
520 selection_caret_(0),
521 selection_anchor_(0),
522 pending_user_gesture_(0.0),
523 document_loader_(NULL),
524 external_document_load_(false),
525 isolate_(v8::Isolate::GetCurrent()),
526 is_deleted_(false),
527 last_input_number_(0),
528 is_tracking_latency_(false),
529 initialized_(false),
530 view_change_weak_ptr_factory_(this),
531 weak_factory_(this) {
532 pp_instance_ = HostGlobals::Get()->AddInstance(this);
534 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
535 module_->InstanceCreated(this);
537 if (render_frame) { // NULL in tests
538 render_frame->render_view()->PepperInstanceCreated(this);
539 // Bind a callback now so that we can inform the RenderViewImpl when we are
540 // destroyed. This works around a temporary problem stemming from work to
541 // move parts of RenderViewImpl in to RenderFrameImpl (see
542 // crbug.com/245126). If destruction happens in this order:
543 // 1) RenderFrameImpl
544 // 2) PepperPluginInstanceImpl
545 // 3) RenderViewImpl
546 // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
547 // to the RenderViewImpl. But when the instance is destroyed, it still
548 // needs to inform the RenderViewImpl that it has gone away, otherwise
549 // between (2) and (3), the RenderViewImpl will still have the dead
550 // instance in its active set, and so might make calls on the deleted
551 // instance. See crbug.com/343576 for more information. Once the plugin
552 // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
553 // can be a little bit simplified by instead making a direct call on
554 // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
555 instance_deleted_callback_ =
556 base::Bind(&RenderViewImpl::PepperInstanceDeleted,
557 render_frame->render_view()->AsWeakPtr(),
558 base::Unretained(this));
559 view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
561 // Set the initial focus.
562 SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
564 if (!module_->IsProxied()) {
565 PepperBrowserConnection* browser_connection =
566 PepperBrowserConnection::Get(render_frame_);
567 browser_connection->DidCreateInProcessInstance(
568 pp_instance(),
569 render_frame_->GetRoutingID(),
570 document_url_,
571 GetPluginURL());
575 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
576 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
578 if (GetContentClient()->renderer() && // NULL in unit tests.
579 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
580 external_document_load_ = true;
583 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
584 DCHECK(!fullscreen_container_);
586 // Notify all the plugin objects of deletion. This will prevent blink from
587 // calling into the plugin any more.
589 // Swap out the set so we can delete from it (the objects will try to
590 // unregister themselves inside the delete call).
591 PluginObjectSet plugin_object_copy;
592 live_plugin_objects_.swap(plugin_object_copy);
593 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
594 i != plugin_object_copy.end();
595 ++i) {
596 (*i)->InstanceDeleted();
599 if (message_channel_)
600 message_channel_->InstanceDeleted();
601 message_channel_object_.Reset();
603 if (TrackedCallback::IsPending(lock_mouse_callback_))
604 lock_mouse_callback_->Abort();
606 if (!instance_deleted_callback_.is_null())
607 instance_deleted_callback_.Run();
609 if (!module_->IsProxied() && render_frame_) {
610 PepperBrowserConnection* browser_connection =
611 PepperBrowserConnection::Get(render_frame_);
612 browser_connection->DidDeleteInProcessInstance(pp_instance());
615 UnSetAndDeleteLockTargetAdapter();
616 module_->InstanceDeleted(this);
617 // If we switched from the NaCl plugin module, notify it too.
618 if (original_module_.get())
619 original_module_->InstanceDeleted(this);
621 // This should be last since some of the above "instance deleted" calls will
622 // want to look up in the global map to get info off of our object.
623 HostGlobals::Get()->InstanceDeleted(pp_instance_);
625 if (throttler_)
626 throttler_->RemoveObserver(this);
629 // NOTE: Any of these methods that calls into the plugin needs to take into
630 // account that the plugin may use Var to remove the <embed> from the DOM, which
631 // will make the PepperWebPluginImpl drop its reference, usually the last one.
632 // If a method needs to access a member of the instance after the call has
633 // returned, then it needs to keep its own reference on the stack.
635 v8::Local<v8::Object> PepperPluginInstanceImpl::GetMessageChannelObject() {
636 return v8::Local<v8::Object>::New(isolate_, message_channel_object_);
639 void PepperPluginInstanceImpl::MessageChannelDestroyed() {
640 message_channel_ = NULL;
641 message_channel_object_.Reset();
644 v8::Local<v8::Context> PepperPluginInstanceImpl::GetMainWorldContext() {
645 if (!container_)
646 return v8::Handle<v8::Context>();
648 if (container_->element().isNull())
649 return v8::Handle<v8::Context>();
651 if (container_->element().document().isNull())
652 return v8::Handle<v8::Context>();
654 if (!container_->element().document().frame())
655 return v8::Handle<v8::Context>();
657 v8::Local<v8::Context> context =
658 container_->element().document().frame()->mainWorldScriptContext();
659 DCHECK(context->GetIsolate() == isolate_);
660 return context;
663 void PepperPluginInstanceImpl::Delete() {
664 is_deleted_ = true;
666 if (render_frame_ &&
667 render_frame_->render_view()->plugin_find_handler() == this) {
668 render_frame_->render_view()->set_plugin_find_handler(NULL);
671 // Keep a reference on the stack. See NOTE above.
672 scoped_refptr<PepperPluginInstanceImpl> ref(this);
673 // Force the MessageChannel to release its "passthrough object" which should
674 // release our last reference to the "InstanceObject" and will probably
675 // destroy it. We want to do this prior to calling DidDestroy in case the
676 // destructor of the instance object tries to use the instance.
677 if (message_channel_)
678 message_channel_->SetPassthroughObject(v8::Handle<v8::Object>());
679 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
680 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
681 // since there is little that it can do at this point.
682 if (original_instance_interface_) {
683 base::TimeTicks start = base::TimeTicks::Now();
684 original_instance_interface_->DidDestroy(pp_instance());
685 UMA_HISTOGRAM_CUSTOM_TIMES("NaCl.Perf.ShutdownTime.Total",
686 base::TimeTicks::Now() - start,
687 base::TimeDelta::FromMilliseconds(1),
688 base::TimeDelta::FromSeconds(20),
689 100);
690 } else {
691 instance_interface_->DidDestroy(pp_instance());
693 // Ensure we don't attempt to call functions on the destroyed instance.
694 original_instance_interface_.reset();
695 instance_interface_.reset();
697 if (fullscreen_container_) {
698 fullscreen_container_->Destroy();
699 fullscreen_container_ = NULL;
702 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
703 // leaks the graphics 2D, it may actually get cleaned up after our
704 // destruction, so we need its pointers to be up-to-date.
705 BindGraphics(pp_instance(), 0);
706 container_ = NULL;
709 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
711 void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
712 const gfx::Rect& plugin_rect,
713 const gfx::Rect& paint_rect) {
714 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
715 if (module()->is_crashed()) {
716 // Crashed plugin painting.
717 if (!sad_plugin_) // Lazily initialize bitmap.
718 sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
719 if (sad_plugin_)
720 PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
721 return;
724 if (bound_graphics_2d_platform_)
725 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
728 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
729 if (fullscreen_container_) {
730 if (rect.IsEmpty())
731 fullscreen_container_->Invalidate();
732 else
733 fullscreen_container_->InvalidateRect(rect);
734 } else {
735 if (!container_ || view_data_.rect.size.width == 0 ||
736 view_data_.rect.size.height == 0)
737 return; // Nothing to do.
738 if (rect.IsEmpty())
739 container_->invalidate();
740 else
741 container_->invalidateRect(rect);
744 cc::Layer* layer =
745 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
746 if (layer) {
747 if (rect.IsEmpty()) {
748 layer->SetNeedsDisplay();
749 } else {
750 layer->SetNeedsDisplayRect(rect);
755 void PepperPluginInstanceImpl::ScrollRect(int dx,
756 int dy,
757 const gfx::Rect& rect) {
758 cc::Layer* layer =
759 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
760 if (layer) {
761 InvalidateRect(rect);
762 } else if (fullscreen_container_) {
763 fullscreen_container_->ScrollRect(dx, dy, rect);
764 } else {
765 if (full_frame_ && !IsViewAccelerated()) {
766 container_->scrollRect(rect);
767 } else {
768 // Can't do optimized scrolling since there could be other elements on top
769 // of us or the view renders via the accelerated compositor which is
770 // incompatible with the move and backfill scrolling model.
771 InvalidateRect(rect);
776 void PepperPluginInstanceImpl::CommitBackingTexture() {
777 if (!texture_layer_.get())
778 return;
779 gpu::Mailbox mailbox;
780 uint32 sync_point = 0;
781 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
782 DCHECK(!mailbox.IsZero());
783 DCHECK_NE(sync_point, 0u);
784 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
785 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
786 texture_layer_->SetNeedsDisplay();
789 void PepperPluginInstanceImpl::InstanceCrashed() {
790 // Force free all resources and vars.
791 HostGlobals::Get()->InstanceCrashed(pp_instance());
793 // Free any associated graphics.
794 SetFullscreen(false);
795 FlashSetFullscreen(false, false);
796 // Unbind current 2D or 3D graphics context.
797 BindGraphics(pp_instance(), 0);
798 InvalidateRect(gfx::Rect());
800 if (content_decryptor_delegate_) {
801 content_decryptor_delegate_->InstanceCrashed();
802 content_decryptor_delegate_.reset();
805 if (render_frame_)
806 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
807 UnSetAndDeleteLockTargetAdapter();
810 bool PepperPluginInstanceImpl::Initialize(
811 const std::vector<std::string>& arg_names,
812 const std::vector<std::string>& arg_values,
813 bool full_frame,
814 scoped_ptr<PluginInstanceThrottlerImpl> throttler) {
815 DCHECK(!throttler_);
817 if (!render_frame_)
818 return false;
820 if (throttler) {
821 throttler_ = throttler.Pass();
822 throttler_->AddObserver(this);
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& window,
1235 const gfx::Rect& clip,
1236 const gfx::Rect& unobscured,
1237 const std::vector<gfx::Rect>& cut_outs_rects) {
1238 // WebKit can give weird (x,y) positions for empty clip rects (since the
1239 // position technically doesn't matter). But we want to make these
1240 // consistent since this is given to the plugin, so force everything to 0
1241 // in the "everything is clipped" case.
1242 gfx::Rect new_clip;
1243 if (!clip.IsEmpty())
1244 new_clip = clip;
1246 unobscured_rect_ = unobscured;
1248 cut_outs_rects_ = cut_outs_rects;
1250 view_data_.rect = PP_FromGfxRect(window);
1251 view_data_.clip_rect = PP_FromGfxRect(clip);
1252 view_data_.device_scale = container_->deviceScaleFactor();
1253 view_data_.css_scale =
1254 container_->pageZoomFactor() * container_->pageScaleFactor();
1256 gfx::Size scroll_offset =
1257 container_->element().document().frame()->scrollOffset();
1258 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1259 scroll_offset.height());
1261 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1262 WebElement element = container_->element();
1263 WebDocument document = element.document();
1264 bool is_fullscreen_element = (element == document.fullScreenElement());
1265 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1266 render_frame()->GetRenderWidget()->is_fullscreen_granted() &&
1267 is_fullscreen_element) {
1268 // Entered fullscreen. Only possible via SetFullscreen().
1269 view_data_.is_fullscreen = true;
1270 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1271 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1272 // so desired_fullscreen_state might be out-of-date.
1273 desired_fullscreen_state_ = false;
1274 view_data_.is_fullscreen = false;
1276 // This operation will cause the plugin to re-layout which will send more
1277 // DidChangeView updates. Schedule an asynchronous update and suppress
1278 // notifications until that completes to avoid sending intermediate sizes
1279 // to the plugins.
1280 ScheduleAsyncDidChangeView();
1282 // Reset the size attributes that we hacked to fill in the screen and
1283 // retrigger ViewChanged. Make sure we don't forward duplicates of
1284 // this view to the plugin.
1285 ResetSizeAttributesAfterFullscreen();
1286 return;
1290 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1292 // During plugin initialization, there are often re-layouts. Avoid sending
1293 // intermediate sizes the plugin and throttler.
1294 if (sent_initial_did_change_view_)
1295 SendDidChangeView();
1296 else
1297 ScheduleAsyncDidChangeView();
1300 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1301 if (has_webkit_focus_ == has_focus)
1302 return;
1304 bool old_plugin_focus = PluginHasFocus();
1305 has_webkit_focus_ = has_focus;
1306 if (PluginHasFocus() != old_plugin_focus)
1307 SendFocusChangeNotification();
1310 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1311 if (has_content_area_focus_ == has_focus)
1312 return;
1314 bool old_plugin_focus = PluginHasFocus();
1315 has_content_area_focus_ = has_focus;
1316 if (PluginHasFocus() != old_plugin_focus)
1317 SendFocusChangeNotification();
1320 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1321 if (is_visible == view_data_.is_page_visible)
1322 return; // Nothing to do.
1323 view_data_.is_page_visible = is_visible;
1325 // If the initial DidChangeView notification hasn't been sent to the plugin,
1326 // let it pass the visibility state for us, instead of sending a notification
1327 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1328 // hasn't been called for the first time. In that case, most of the fields in
1329 // |view_data_| haven't been properly initialized.
1330 if (sent_initial_did_change_view_)
1331 SendDidChangeView();
1334 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1335 if (bound_graphics_2d_platform_)
1336 bound_graphics_2d_platform_->ViewInitiatedPaint();
1337 else if (bound_graphics_3d_.get())
1338 bound_graphics_3d_->ViewInitiatedPaint();
1339 else if (bound_compositor_)
1340 bound_compositor_->ViewInitiatedPaint();
1343 void PepperPluginInstanceImpl::SetSelectedText(
1344 const base::string16& selected_text) {
1345 selected_text_ = selected_text;
1346 gfx::Range range(0, selected_text.length());
1347 render_frame_->SetSelectedText(selected_text, 0, range);
1350 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1351 link_under_cursor_ = base::UTF8ToUTF16(url);
1354 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1355 text_input_type_ = type;
1356 render_frame_->PepperTextInputTypeChanged(this);
1359 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1360 if (message_channel_)
1361 message_channel_->PostMessageToJavaScript(message);
1364 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1365 PP_Instance instance,
1366 void* user_data,
1367 const PPP_MessageHandler_0_2* handler,
1368 PP_Resource message_loop) {
1369 // Not supported in-process.
1370 NOTIMPLEMENTED();
1371 return PP_ERROR_FAILED;
1374 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1375 // Not supported in-process.
1376 NOTIMPLEMENTED();
1379 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1380 return selected_text_;
1383 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1384 const gfx::Point& point) {
1385 // Keep a reference on the stack. See NOTE above.
1386 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1387 if (!LoadPdfInterface()) {
1388 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1389 // return |link_under_cursor_| here because this is only ever called with
1390 // the current mouse coordinates.
1391 return link_under_cursor_;
1394 PP_Point p;
1395 p.x = point.x();
1396 p.y = point.y();
1397 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1398 // If the plugin returns undefined for this function it has switched to
1399 // providing us with the link under the cursor eagerly.
1400 if (rv.type == PP_VARTYPE_UNDEFINED)
1401 return link_under_cursor_;
1402 StringVar* string = StringVar::FromPPVar(rv);
1403 base::string16 link;
1404 if (string)
1405 link = base::UTF8ToUTF16(string->value());
1406 // Release the ref the plugin transfered to us.
1407 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1408 return link;
1411 void PepperPluginInstanceImpl::RequestSurroundingText(
1412 size_t desired_number_of_characters) {
1413 // Keep a reference on the stack. See NOTE above.
1414 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1415 if (!LoadTextInputInterface())
1416 return;
1417 plugin_textinput_interface_->RequestSurroundingText(
1418 pp_instance(), desired_number_of_characters);
1421 void PepperPluginInstanceImpl::Zoom(double factor, bool text_only) {
1422 // Keep a reference on the stack. See NOTE above.
1423 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1424 if (!LoadZoomInterface())
1425 return;
1426 plugin_zoom_interface_->Zoom(pp_instance(), factor, PP_FromBool(text_only));
1429 bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1430 bool case_sensitive,
1431 int identifier) {
1432 // Keep a reference on the stack. See NOTE above.
1433 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1434 if (!LoadFindInterface())
1435 return false;
1436 find_identifier_ = identifier;
1437 return PP_ToBool(
1438 plugin_find_interface_->StartFind(pp_instance(),
1439 base::UTF16ToUTF8(search_text).c_str(),
1440 PP_FromBool(case_sensitive)));
1443 void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1444 // Keep a reference on the stack. See NOTE above.
1445 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1446 if (LoadFindInterface())
1447 plugin_find_interface_->SelectFindResult(pp_instance(),
1448 PP_FromBool(forward));
1451 void PepperPluginInstanceImpl::StopFind() {
1452 // Keep a reference on the stack. See NOTE above.
1453 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1454 if (!LoadFindInterface())
1455 return;
1456 find_identifier_ = -1;
1457 plugin_find_interface_->StopFind(pp_instance());
1460 bool PepperPluginInstanceImpl::LoadFindInterface() {
1461 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1462 return false;
1463 if (!plugin_find_interface_) {
1464 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1465 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1468 return !!plugin_find_interface_;
1471 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1472 if (!checked_for_plugin_input_event_interface_) {
1473 checked_for_plugin_input_event_interface_ = true;
1474 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1475 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1477 return !!plugin_input_event_interface_;
1480 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1481 if (!plugin_mouse_lock_interface_) {
1482 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1483 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1486 return !!plugin_mouse_lock_interface_;
1489 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1490 if (!checked_for_plugin_pdf_interface_) {
1491 checked_for_plugin_pdf_interface_ = true;
1492 plugin_pdf_interface_ = static_cast<const PPP_Pdf*>(
1493 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1496 return !!plugin_pdf_interface_;
1499 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1500 // Only check for the interface if the plugin has dev permission.
1501 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1502 return false;
1503 if (!plugin_print_interface_) {
1504 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1505 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1507 return !!plugin_print_interface_;
1510 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1511 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1512 // call GetInstanceObject. This is necessary to ensure that the properties
1513 // the trusted plugin exposes (readyState and lastError) work properly. Note
1514 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1515 // so it's correct to never look up PPP_InstancePrivate for them.
1517 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1518 // to the "real" module.
1519 scoped_refptr<PluginModule> module =
1520 original_module_.get() ? original_module_ : module_;
1521 // Only check for the interface if the plugin has private permission.
1522 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1523 return false;
1524 if (!plugin_private_interface_) {
1525 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1526 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1529 return !!plugin_private_interface_;
1532 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1533 if (!plugin_textinput_interface_) {
1534 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1535 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1538 return !!plugin_textinput_interface_;
1541 bool PepperPluginInstanceImpl::LoadZoomInterface() {
1542 if (!plugin_zoom_interface_) {
1543 plugin_zoom_interface_ = static_cast<const PPP_Zoom_Dev*>(
1544 module_->GetPluginInterface(PPP_ZOOM_DEV_INTERFACE));
1547 return !!plugin_zoom_interface_;
1550 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1551 if (!bound_graphics_2d_platform_ || !texture_layer_.get()) {
1552 // Currently the transform is only applied for Graphics2D.
1553 return;
1555 // Set the UV coordinates of the texture based on the size of the Graphics2D
1556 // context. By default a texture gets scaled to the size of the layer. But
1557 // if the size of the Graphics2D context doesn't match the size of the plugin
1558 // then it will be incorrectly stretched. This also affects how the plugin
1559 // is painted when it is being resized. If the Graphics2D contents are
1560 // stretched when a plugin is resized while waiting for a new frame from the
1561 // plugin to be rendered, then flickering behavior occurs as in
1562 // crbug.com/353453.
1563 gfx::SizeF graphics_2d_size_in_dip =
1564 gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1565 bound_graphics_2d_platform_->GetScale());
1566 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1567 view_data_.rect.size.height);
1569 texture_layer_->SetUV(
1570 gfx::PointF(0.0f, 0.0f),
1571 gfx::PointF(
1572 plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1573 plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1576 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1577 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1580 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1581 // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1582 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1583 // drop its reference, usually the last one. This is similar to possible
1584 // plugin behavior described at the NOTE above Delete().
1585 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1587 if (!render_frame_)
1588 return;
1590 bool has_focus = PluginHasFocus();
1591 render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1593 // instance_interface_ may have been cleared in Delete() if the
1594 // PepperWebPluginImpl is destroyed.
1595 if (instance_interface_)
1596 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1599 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1600 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1601 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1602 container_->requestTouchEventType(
1603 raw_touch
1604 ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1605 : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1608 bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1609 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1610 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1613 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1614 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1615 return; // Already scheduled.
1616 base::MessageLoop::current()->PostTask(
1617 FROM_HERE,
1618 base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1619 view_change_weak_ptr_factory_.GetWeakPtr()));
1622 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1623 // The bound callback that owns the weak pointer is still valid until after
1624 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1625 // invalidate them here.
1626 // NOTE: If we ever want to have more than one pending callback, it should
1627 // use a different factory, or we should have a different strategy here.
1628 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1629 SendDidChangeView();
1632 void PepperPluginInstanceImpl::SendDidChangeView() {
1633 // An asynchronous view update is scheduled. Skip sending this update.
1634 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1635 return;
1637 // Don't send DidChangeView to crashed plugins.
1638 if (module()->is_crashed())
1639 return;
1641 // During the first view update, initialize the throttler.
1642 if (!sent_initial_did_change_view_) {
1643 if (is_flash_plugin_ && RenderThread::Get()) {
1644 RenderThread::Get()->RecordAction(
1645 base::UserMetricsAction("Flash.PluginInstanceCreated"));
1646 RecordFlashSizeMetric(unobscured_rect_.width(),
1647 unobscured_rect_.height());
1650 if (throttler_) {
1651 throttler_->Initialize(render_frame_, plugin_url_.GetOrigin(),
1652 module()->name(), unobscured_rect_.size());
1656 ppapi::ViewData view_data = view_data_;
1658 // When plugin content is throttled, fake the page being offscreen. We cannot
1659 // send empty view data here, as some plugins rely on accurate view data.
1660 if (throttler_ && throttler_->IsThrottled()) {
1661 view_data.is_page_visible = false;
1662 view_data.clip_rect.point.x = 0;
1663 view_data.clip_rect.point.y = 0;
1664 view_data.clip_rect.size.width = 0;
1665 view_data.clip_rect.size.height = 0;
1668 if (sent_initial_did_change_view_ && last_sent_view_data_.Equals(view_data))
1669 return; // Nothing to update.
1671 sent_initial_did_change_view_ = true;
1672 last_sent_view_data_ = view_data;
1673 ScopedPPResource resource(
1674 ScopedPPResource::PassRef(),
1675 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data))
1676 ->GetReference());
1678 UpdateLayerTransform();
1680 if (bound_graphics_2d_platform_ &&
1681 (!view_data.is_page_visible ||
1682 PP_ToGfxRect(view_data.clip_rect).IsEmpty())) {
1683 bound_graphics_2d_platform_->ClearCache();
1686 // It's possible that Delete() has been called but the renderer hasn't
1687 // released its reference to this object yet.
1688 if (instance_interface_) {
1689 instance_interface_->DidChangeView(
1690 pp_instance(), resource, &view_data.rect, &view_data.clip_rect);
1694 void PepperPluginInstanceImpl::ReportGeometry() {
1695 // If this call was delayed, we may have transitioned back to fullscreen in
1696 // the mean time, so only report the geometry if we are actually in normal
1697 // mode.
1698 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1699 container_->reportGeometry();
1702 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1703 PP_PrintOutputFormat_Dev* format) {
1704 // Keep a reference on the stack. See NOTE above.
1705 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1706 if (!LoadPrintInterface())
1707 return false;
1708 uint32_t supported_formats =
1709 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1710 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1711 *format = PP_PRINTOUTPUTFORMAT_PDF;
1712 return true;
1714 return false;
1717 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1718 PP_PrintOutputFormat_Dev format;
1719 return GetPreferredPrintOutputFormat(&format);
1722 bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1723 DCHECK(plugin_print_interface_);
1724 if (!plugin_print_interface_)
1725 return false;
1726 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1729 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1730 // Keep a reference on the stack. See NOTE above.
1731 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1732 PP_PrintOutputFormat_Dev format;
1733 if (!GetPreferredPrintOutputFormat(&format)) {
1734 // PrintBegin should not have been called since SupportsPrintInterface
1735 // would have returned false;
1736 NOTREACHED();
1737 return 0;
1739 int num_pages = 0;
1740 PP_PrintSettings_Dev print_settings;
1741 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1742 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1743 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1744 print_settings.dpi = print_params.printerDPI;
1745 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1746 print_settings.grayscale = PP_FALSE;
1747 print_settings.print_scaling_option =
1748 static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1749 print_settings.format = format;
1750 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1751 if (!num_pages)
1752 return 0;
1753 current_print_settings_ = print_settings;
1754 canvas_.clear();
1755 ranges_.clear();
1756 return num_pages;
1759 bool PepperPluginInstanceImpl::PrintPage(int page_number,
1760 blink::WebCanvas* canvas) {
1761 #if defined(ENABLE_PRINTING)
1762 DCHECK(plugin_print_interface_);
1763 PP_PrintPageNumberRange_Dev page_range;
1764 page_range.first_page_number = page_range.last_page_number = page_number;
1765 // The canvas only has a metafile on it for print preview.
1766 bool save_for_later =
1767 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1768 #if defined(OS_MACOSX)
1769 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1770 #endif // defined(OS_MACOSX)
1771 if (save_for_later) {
1772 ranges_.push_back(page_range);
1773 canvas_ = skia::SharePtr(canvas);
1774 return true;
1775 } else {
1776 return PrintPageHelper(&page_range, 1, canvas);
1778 #else // ENABLE_PRINTING
1779 return false;
1780 #endif
1783 bool PepperPluginInstanceImpl::PrintPageHelper(
1784 PP_PrintPageNumberRange_Dev* page_ranges,
1785 int num_ranges,
1786 blink::WebCanvas* canvas) {
1787 // Keep a reference on the stack. See NOTE above.
1788 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1789 DCHECK(plugin_print_interface_);
1790 if (!plugin_print_interface_)
1791 return false;
1792 PP_Resource print_output = plugin_print_interface_->PrintPages(
1793 pp_instance(), page_ranges, num_ranges);
1794 if (!print_output)
1795 return false;
1797 bool ret = false;
1799 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1800 ret = PrintPDFOutput(print_output, canvas);
1802 // Now we need to release the print output resource.
1803 PluginModule::GetCore()->ReleaseResource(print_output);
1805 return ret;
1808 void PepperPluginInstanceImpl::PrintEnd() {
1809 // Keep a reference on the stack. See NOTE above.
1810 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1811 if (!ranges_.empty())
1812 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1813 canvas_.clear();
1814 ranges_.clear();
1816 DCHECK(plugin_print_interface_);
1817 if (plugin_print_interface_)
1818 plugin_print_interface_->End(pp_instance());
1820 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1821 #if defined(OS_MACOSX)
1822 last_printed_page_ = NULL;
1823 #endif // defined(OS_MACOSX)
1826 bool PepperPluginInstanceImpl::GetPrintPresetOptionsFromDocument(
1827 blink::WebPrintPresetOptions* preset_options) {
1828 // Keep a reference on the stack. See NOTE above.
1829 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1830 if (!LoadPdfInterface())
1831 return false;
1833 PP_PdfPrintPresetOptions_Dev options;
1834 if (!plugin_pdf_interface_->GetPrintPresetOptionsFromDocument(pp_instance(),
1835 &options)) {
1836 return false;
1839 preset_options->isScalingDisabled = PP_ToBool(options.is_scaling_disabled);
1840 switch (options.duplex) {
1841 case PP_PRIVATEDUPLEXMODE_SIMPLEX:
1842 preset_options->duplexMode = blink::WebSimplex;
1843 break;
1844 case PP_PRIVATEDUPLEXMODE_SHORT_EDGE:
1845 preset_options->duplexMode = blink::WebShortEdge;
1846 break;
1847 case PP_PRIVATEDUPLEXMODE_LONG_EDGE:
1848 preset_options->duplexMode = blink::WebLongEdge;
1849 break;
1850 default:
1851 preset_options->duplexMode = blink::WebUnknownDuplexMode;
1852 break;
1854 preset_options->copies = options.copies;
1855 preset_options->isPageSizeUniform = PP_ToBool(options.is_page_size_uniform);
1856 preset_options->uniformPageSize =
1857 blink::WebSize(options.uniform_page_size.width,
1858 options.uniform_page_size.height);
1860 return true;
1863 bool PepperPluginInstanceImpl::CanRotateView() {
1864 if (!LoadPdfInterface() || module()->is_crashed())
1865 return false;
1867 return true;
1870 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1871 if (!LoadPdfInterface())
1872 return;
1873 PP_PrivatePageTransformType transform_type =
1874 type == WebPlugin::RotationType90Clockwise
1875 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1876 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1877 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1878 // NOTE: plugin instance may have been deleted.
1881 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1882 return fullscreen_container_ != NULL;
1885 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1886 return desired_fullscreen_state_;
1889 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1890 // Keep a reference on the stack. See NOTE above.
1891 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1893 // Check whether we are trying to switch to the state we're already going
1894 // to (i.e. if we're already switching to fullscreen but the fullscreen
1895 // container isn't ready yet, don't do anything more).
1896 if (fullscreen == IsFullscreenOrPending())
1897 return false;
1899 if (!render_frame_)
1900 return false;
1901 if (fullscreen && !render_frame_->render_view()
1902 ->renderer_preferences()
1903 .plugin_fullscreen_allowed)
1904 return false;
1906 // Check whether we are trying to switch while the state is in transition.
1907 // The 2nd request gets dropped while messing up the internal state, so
1908 // disallow this.
1909 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1910 return false;
1912 if (fullscreen && !IsProcessingUserGesture())
1913 return false;
1915 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1916 desired_fullscreen_state_ = fullscreen;
1918 if (fullscreen) {
1919 // Create the user gesture in case we're processing one that's pending.
1920 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1921 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1922 // so we will tweak plugin's attributes to support the expected behavior.
1923 KeepSizeAttributesBeforeFullscreen();
1924 SetSizeAttributesForFullscreen();
1925 container_->element().requestFullScreen();
1926 } else {
1927 container_->element().document().cancelFullScreen();
1929 return true;
1932 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1933 bool flash_fullscreen) {
1934 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1936 if (flash_fullscreen == flash_fullscreen_) {
1937 // Manually clear callback when fullscreen fails with mouselock pending.
1938 if (!flash_fullscreen && is_mouselock_pending)
1939 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1940 return;
1943 UpdateLayer(false);
1945 bool old_plugin_focus = PluginHasFocus();
1946 flash_fullscreen_ = flash_fullscreen;
1947 if (is_mouselock_pending && !IsMouseLocked()) {
1948 if (!IsProcessingUserGesture() &&
1949 !module_->permissions().HasPermission(
1950 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1951 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1952 } else {
1953 // Open a user gesture here so the Webkit user gesture checks will succeed
1954 // for out-of-process plugins.
1955 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1956 if (!LockMouse())
1957 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1961 if (PluginHasFocus() != old_plugin_focus)
1962 SendFocusChangeNotification();
1965 bool PepperPluginInstanceImpl::IsViewAccelerated() {
1966 if (!container_)
1967 return false;
1969 WebDocument document = container_->element().document();
1970 WebLocalFrame* frame = document.frame();
1971 if (!frame)
1972 return false;
1973 WebView* view = frame->view();
1974 if (!view)
1975 return false;
1977 return view->isAcceleratedCompositingActive();
1980 bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1981 blink::WebCanvas* canvas) {
1982 #if defined(ENABLE_PRINTING)
1983 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1984 if (enter.failed())
1985 return false;
1987 BufferAutoMapper mapper(enter.object());
1988 if (!mapper.data() || !mapper.size()) {
1989 NOTREACHED();
1990 return false;
1993 printing::PdfMetafileSkia* metafile =
1994 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1995 if (metafile)
1996 return metafile->InitFromData(mapper.data(), mapper.size());
1998 NOTREACHED();
1999 #endif // ENABLE_PRINTING
2000 return false;
2003 void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
2004 if (!container_)
2005 return;
2006 if (throttler_ && throttler_->IsHiddenForPlaceholder())
2007 return;
2009 gpu::Mailbox mailbox;
2010 uint32 sync_point = 0;
2011 if (bound_graphics_3d_.get()) {
2012 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
2013 DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
2015 bool want_3d_layer = !mailbox.IsZero();
2016 bool want_2d_layer = !!bound_graphics_2d_platform_;
2017 bool want_texture_layer = want_3d_layer || want_2d_layer;
2018 bool want_compositor_layer = !!bound_compositor_;
2020 if (!device_changed && (want_texture_layer == !!texture_layer_.get()) &&
2021 (want_3d_layer == layer_is_hardware_) &&
2022 (want_compositor_layer == !!compositor_layer_.get()) &&
2023 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
2024 UpdateLayerTransform();
2025 return;
2028 if (texture_layer_.get() || compositor_layer_.get()) {
2029 if (!layer_bound_to_fullscreen_)
2030 container_->setWebLayer(NULL);
2031 else if (fullscreen_container_)
2032 fullscreen_container_->SetLayer(NULL);
2033 web_layer_.reset();
2034 texture_layer_ = NULL;
2035 compositor_layer_ = NULL;
2038 if (want_texture_layer) {
2039 bool opaque = false;
2040 if (want_3d_layer) {
2041 DCHECK(bound_graphics_3d_.get());
2042 texture_layer_ = cc::TextureLayer::CreateForMailbox(NULL);
2043 opaque = bound_graphics_3d_->IsOpaque();
2044 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
2045 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
2046 } else {
2047 DCHECK(bound_graphics_2d_platform_);
2048 texture_layer_ = cc::TextureLayer::CreateForMailbox(this);
2049 bound_graphics_2d_platform_->AttachedToNewLayer();
2050 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2051 texture_layer_->SetFlipped(false);
2054 // Ignore transparency in fullscreen, since that's what Flash always
2055 // wants to do, and that lets it not recreate a context if
2056 // wmode=transparent was specified.
2057 opaque = opaque || fullscreen_container_;
2058 texture_layer_->SetContentsOpaque(opaque);
2059 web_layer_.reset(new cc_blink::WebLayerImpl(texture_layer_));
2060 } else if (want_compositor_layer) {
2061 compositor_layer_ = bound_compositor_->layer();
2062 web_layer_.reset(new cc_blink::WebLayerImpl(compositor_layer_));
2065 if (web_layer_) {
2066 if (fullscreen_container_) {
2067 fullscreen_container_->SetLayer(web_layer_.get());
2068 } else {
2069 container_->setWebLayer(web_layer_.get());
2073 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2074 layer_is_hardware_ = want_3d_layer;
2075 UpdateLayerTransform();
2078 bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2079 cc::TextureMailbox* mailbox,
2080 scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2081 bool use_shared_memory) {
2082 if (!bound_graphics_2d_platform_)
2083 return false;
2084 return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2085 release_callback);
2088 void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2090 void PepperPluginInstanceImpl::OnThrottleStateChange() {
2091 SendDidChangeView();
2093 bool is_throttled = throttler_->IsThrottled();
2094 render_frame()->Send(new ViewHostMsg_PluginInstanceThrottleStateChange(
2095 module_->GetPluginChildId(), pp_instance_, is_throttled));
2098 void PepperPluginInstanceImpl::OnHiddenForPlaceholder(bool hidden) {
2099 if (hidden) {
2100 container_->setWebLayer(nullptr);
2101 } else {
2102 UpdateLayer(true /* device_changed */);
2106 void PepperPluginInstanceImpl::AddLatencyInfo(
2107 const std::vector<ui::LatencyInfo>& latency_info) {
2108 if (render_frame_ && render_frame_->GetRenderWidget()) {
2109 RenderWidgetCompositor* compositor =
2110 render_frame_->GetRenderWidget()->compositor();
2111 if (compositor) {
2112 for (size_t i = 0; i < latency_info.size(); i++) {
2113 scoped_ptr<cc::SwapPromise> swap_promise(
2114 new cc::LatencyInfoSwapPromise(latency_info[i]));
2115 compositor->QueueSwapPromise(swap_promise.Pass());
2121 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2122 DCHECK(live_plugin_objects_.find(plugin_object) ==
2123 live_plugin_objects_.end());
2124 live_plugin_objects_.insert(plugin_object);
2127 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2128 // Don't actually verify that the object is in the set since during module
2129 // deletion we'll be in the process of freeing them.
2130 live_plugin_objects_.erase(plugin_object);
2133 bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2134 PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2135 // Give a lot of slack so tests won't be flaky.
2136 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2137 return pending_user_gesture_token_.hasGestures() &&
2138 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2141 WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2142 if (!IsProcessingUserGesture())
2143 pending_user_gesture_token_ = WebUserGestureToken();
2144 return pending_user_gesture_token_;
2147 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2148 if (TrackedCallback::IsPending(lock_mouse_callback_))
2149 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2152 void PepperPluginInstanceImpl::OnMouseLockLost() {
2153 if (LoadMouseLockInterface())
2154 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2157 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2158 const blink::WebMouseEvent& event) {
2159 // |cursor_info| is ignored since it is hidden when the mouse is locked.
2160 blink::WebCursorInfo cursor_info;
2161 HandleInputEvent(event, &cursor_info);
2164 void PepperPluginInstanceImpl::SimulateInputEvent(
2165 const InputEventData& input_event) {
2166 WebView* web_view = container()->element().document().frame()->view();
2167 if (!web_view) {
2168 NOTREACHED();
2169 return;
2172 bool handled = SimulateIMEEvent(input_event);
2173 if (handled)
2174 return;
2176 std::vector<linked_ptr<WebInputEvent> > events =
2177 CreateSimulatedWebInputEvents(
2178 input_event,
2179 view_data_.rect.point.x + view_data_.rect.size.width / 2,
2180 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2181 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2182 it != events.end();
2183 ++it) {
2184 web_view->handleInputEvent(*it->get());
2188 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2189 const InputEventData& input_event) {
2190 switch (input_event.event_type) {
2191 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2192 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2193 SimulateImeSetCompositionEvent(input_event);
2194 break;
2195 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2196 DCHECK(input_event.character_text.empty());
2197 SimulateImeSetCompositionEvent(input_event);
2198 break;
2199 case PP_INPUTEVENT_TYPE_IME_TEXT:
2200 if (!render_frame_)
2201 return false;
2202 render_frame_->SimulateImeConfirmComposition(
2203 base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2204 break;
2205 default:
2206 return false;
2208 return true;
2211 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2212 const InputEventData& input_event) {
2213 if (!render_frame_)
2214 return;
2216 std::vector<size_t> offsets;
2217 offsets.push_back(input_event.composition_selection_start);
2218 offsets.push_back(input_event.composition_selection_end);
2219 offsets.insert(offsets.end(),
2220 input_event.composition_segment_offsets.begin(),
2221 input_event.composition_segment_offsets.end());
2223 base::string16 utf16_text =
2224 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2226 std::vector<blink::WebCompositionUnderline> underlines;
2227 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2228 blink::WebCompositionUnderline underline;
2229 underline.startOffset = offsets[i];
2230 underline.endOffset = offsets[i + 1];
2231 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2232 underline.thick = true;
2233 underlines.push_back(underline);
2236 render_frame_->SimulateImeSetComposition(
2237 utf16_text, underlines, offsets[0], offsets[1]);
2240 ContentDecryptorDelegate*
2241 PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2242 if (content_decryptor_delegate_)
2243 return content_decryptor_delegate_.get();
2245 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2246 static_cast<const PPP_ContentDecryptor_Private*>(
2247 module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2248 if (!plugin_decryption_interface)
2249 return NULL;
2251 content_decryptor_delegate_.reset(
2252 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2253 return content_decryptor_delegate_.get();
2256 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2257 PP_Resource device) {
2258 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2259 // The Graphics3D instance can't be destroyed until we call
2260 // UpdateLayer().
2261 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2262 if (bound_graphics_3d_.get()) {
2263 bound_graphics_3d_->BindToInstance(false);
2264 bound_graphics_3d_ = NULL;
2266 if (bound_graphics_2d_platform_) {
2267 bound_graphics_2d_platform_->BindToInstance(NULL);
2268 bound_graphics_2d_platform_ = NULL;
2270 if (bound_compositor_) {
2271 bound_compositor_->BindToInstance(NULL);
2272 bound_compositor_ = NULL;
2275 // Special-case clearing the current device.
2276 if (!device) {
2277 UpdateLayer(true);
2278 InvalidateRect(gfx::Rect());
2279 return PP_TRUE;
2282 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2283 // to/from fullscreen with PPB_Fullscreen.
2284 if ((fullscreen_container_ && !flash_fullscreen_) ||
2285 desired_fullscreen_state_ != view_data_.is_fullscreen)
2286 return PP_FALSE;
2288 const ppapi::host::PpapiHost* ppapi_host =
2289 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2290 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2291 PepperGraphics2DHost* graphics_2d = NULL;
2292 PepperCompositorHost* compositor = NULL;
2293 if (host) {
2294 if (host->IsGraphics2DHost()) {
2295 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2296 } else if (host->IsCompositorHost()) {
2297 compositor = static_cast<PepperCompositorHost*>(host);
2298 } else {
2299 DLOG(ERROR) <<
2300 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2304 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2305 PPB_Graphics3D_Impl* graphics_3d =
2306 enter_3d.succeeded()
2307 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2308 : NULL;
2310 if (compositor) {
2311 if (compositor->BindToInstance(this)) {
2312 bound_compositor_ = compositor;
2313 UpdateLayer(true);
2314 return PP_TRUE;
2316 } else if (graphics_2d) {
2317 if (graphics_2d->BindToInstance(this)) {
2318 bound_graphics_2d_platform_ = graphics_2d;
2319 UpdateLayer(true);
2320 return PP_TRUE;
2322 } else if (graphics_3d) {
2323 // Make sure graphics can only be bound to the instance it is
2324 // associated with.
2325 if (graphics_3d->pp_instance() == pp_instance() &&
2326 graphics_3d->BindToInstance(true)) {
2327 bound_graphics_3d_ = graphics_3d;
2328 UpdateLayer(true);
2329 return PP_TRUE;
2333 // The instance cannot be bound or the device is not a valid resource type.
2334 return PP_FALSE;
2337 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2338 return PP_FromBool(full_frame());
2341 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2342 return &view_data_;
2345 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2346 return PP_FromBool(flash_fullscreen_);
2349 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2350 if (!container_)
2351 return PP_MakeUndefined();
2352 RecordFlashJavaScriptUse();
2353 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2354 PepperTryCatchVar try_catch(this, &converter, NULL);
2355 WebLocalFrame* frame = container_->element().document().frame();
2356 if (!frame) {
2357 try_catch.SetException("No frame exists for window object.");
2358 return PP_MakeUndefined();
2361 ScopedPPVar result =
2362 try_catch.FromV8(frame->mainWorldScriptContext()->Global());
2363 DCHECK(!try_catch.HasException());
2364 return result.Release();
2367 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2368 if (!container_)
2369 return PP_MakeUndefined();
2370 RecordFlashJavaScriptUse();
2371 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2372 PepperTryCatchVar try_catch(this, &converter, NULL);
2373 ScopedPPVar result = try_catch.FromV8(container_->v8ObjectForElement());
2374 DCHECK(!try_catch.HasException());
2375 return result.Release();
2378 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2379 PP_Var script_var,
2380 PP_Var* exception) {
2381 if (!container_)
2382 return PP_MakeUndefined();
2383 RecordFlashJavaScriptUse();
2385 // Executing the script may remove the plugin from the DOM, so we need to keep
2386 // a reference to ourselves so that we can still process the result after the
2387 // WebBindings::evaluate() below.
2388 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2389 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2390 PepperTryCatchVar try_catch(this, &converter, exception);
2392 // Check for an exception due to the context being destroyed.
2393 if (try_catch.HasException())
2394 return PP_MakeUndefined();
2396 WebLocalFrame* frame = container_->element().document().frame();
2397 if (!frame) {
2398 try_catch.SetException("No frame to execute script in.");
2399 return PP_MakeUndefined();
2402 StringVar* script_string_var = StringVar::FromPPVar(script_var);
2403 if (!script_string_var) {
2404 try_catch.SetException("Script param to ExecuteScript must be a string.");
2405 return PP_MakeUndefined();
2408 std::string script_string = script_string_var->value();
2409 blink::WebScriptSource script(
2410 blink::WebString::fromUTF8(script_string.c_str()));
2411 v8::Handle<v8::Value> result;
2412 if (IsProcessingUserGesture()) {
2413 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2414 result = frame->executeScriptAndReturnValue(script);
2415 } else {
2416 result = frame->executeScriptAndReturnValue(script);
2419 ScopedPPVar var_result = try_catch.FromV8(result);
2420 if (try_catch.HasException())
2421 return PP_MakeUndefined();
2423 return var_result.Release();
2426 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2427 PP_Instance instance) {
2428 RenderThreadImpl* thread = RenderThreadImpl::current();
2429 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2432 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2433 PP_Instance instance) {
2434 RenderThreadImpl* thread = RenderThreadImpl::current();
2435 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2438 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2439 if (!render_frame_)
2440 return PP_MakeUndefined();
2441 return StringVar::StringToPPVar(
2442 render_frame_->render_view()->webkit_preferences().default_encoding);
2445 // These PPB_ContentDecryptor_Private calls are responses to
2446 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2447 // Therefore, |content_decryptor_delegate_| must have been initialized when
2448 // the following methods are called.
2449 void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2450 uint32 promise_id) {
2451 content_decryptor_delegate_->OnPromiseResolved(promise_id);
2454 void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2455 PP_Instance instance,
2456 uint32 promise_id,
2457 PP_Var session_id_var) {
2458 content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2459 session_id_var);
2462 void PepperPluginInstanceImpl::PromiseRejected(
2463 PP_Instance instance,
2464 uint32 promise_id,
2465 PP_CdmExceptionCode exception_code,
2466 uint32 system_code,
2467 PP_Var error_description_var) {
2468 content_decryptor_delegate_->OnPromiseRejected(
2469 promise_id, exception_code, system_code, error_description_var);
2472 void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2473 PP_Var session_id_var,
2474 PP_CdmMessageType message_type,
2475 PP_Var message_var,
2476 PP_Var legacy_destination_url) {
2477 content_decryptor_delegate_->OnSessionMessage(
2478 session_id_var, message_type, message_var, legacy_destination_url);
2481 void PepperPluginInstanceImpl::SessionKeysChange(
2482 PP_Instance instance,
2483 PP_Var session_id_var,
2484 PP_Bool has_additional_usable_key,
2485 uint32_t key_count,
2486 const struct PP_KeyInformation key_information[]) {
2487 content_decryptor_delegate_->OnSessionKeysChange(
2488 session_id_var, has_additional_usable_key, key_count, key_information);
2491 void PepperPluginInstanceImpl::SessionExpirationChange(
2492 PP_Instance instance,
2493 PP_Var session_id_var,
2494 PP_Time new_expiry_time) {
2495 content_decryptor_delegate_->OnSessionExpirationChange(session_id_var,
2496 new_expiry_time);
2499 void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2500 PP_Var session_id_var) {
2501 content_decryptor_delegate_->OnSessionClosed(session_id_var);
2504 void PepperPluginInstanceImpl::LegacySessionError(
2505 PP_Instance instance,
2506 PP_Var session_id_var,
2507 PP_CdmExceptionCode exception_code,
2508 uint32 system_code,
2509 PP_Var error_description_var) {
2510 content_decryptor_delegate_->OnLegacySessionError(
2511 session_id_var, exception_code, system_code, error_description_var);
2514 void PepperPluginInstanceImpl::DeliverBlock(
2515 PP_Instance instance,
2516 PP_Resource decrypted_block,
2517 const PP_DecryptedBlockInfo* block_info) {
2518 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2521 void PepperPluginInstanceImpl::DecoderInitializeDone(
2522 PP_Instance instance,
2523 PP_DecryptorStreamType decoder_type,
2524 uint32_t request_id,
2525 PP_Bool success) {
2526 content_decryptor_delegate_->DecoderInitializeDone(
2527 decoder_type, request_id, success);
2530 void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2531 PP_Instance instance,
2532 PP_DecryptorStreamType decoder_type,
2533 uint32_t request_id) {
2534 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2535 request_id);
2538 void PepperPluginInstanceImpl::DecoderResetDone(
2539 PP_Instance instance,
2540 PP_DecryptorStreamType decoder_type,
2541 uint32_t request_id) {
2542 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2545 void PepperPluginInstanceImpl::DeliverFrame(
2546 PP_Instance instance,
2547 PP_Resource decrypted_frame,
2548 const PP_DecryptedFrameInfo* frame_info) {
2549 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2552 void PepperPluginInstanceImpl::DeliverSamples(
2553 PP_Instance instance,
2554 PP_Resource audio_frames,
2555 const PP_DecryptedSampleInfo* sample_info) {
2556 content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2559 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2560 PP_Instance instance) {
2561 if (!LoadFindInterface())
2562 return;
2563 bool is_main_frame =
2564 render_frame_ &&
2565 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2566 if (!is_main_frame)
2567 return;
2568 render_frame_->render_view()->set_plugin_find_handler(this);
2571 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2572 PP_Instance instance,
2573 int32_t total,
2574 PP_Bool final_result) {
2575 DCHECK_NE(find_identifier_, -1);
2576 if (render_frame_) {
2577 render_frame_->reportFindInPageMatchCount(
2578 find_identifier_, total, PP_ToBool(final_result));
2582 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2583 int32_t index) {
2584 DCHECK_NE(find_identifier_, -1);
2585 if (render_frame_) {
2586 render_frame_->reportFindInPageSelection(
2587 find_identifier_, index + 1, blink::WebRect());
2591 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2592 const PP_Rect* tickmarks,
2593 uint32_t count) {
2594 if (!render_frame_ || !render_frame_->GetWebFrame())
2595 return;
2597 blink::WebVector<blink::WebRect> tickmarks_converted(
2598 static_cast<size_t>(count));
2599 for (uint32 i = 0; i < count; ++i) {
2600 tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2601 tickmarks[i].point.y,
2602 tickmarks[i].size.width,
2603 tickmarks[i].size.height);
2605 blink::WebFrame* frame = render_frame_->GetWebFrame();
2606 frame->setTickmarks(tickmarks_converted);
2609 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2610 return PP_FromBool(view_data_.is_fullscreen);
2613 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2614 PP_Bool fullscreen) {
2615 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2618 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2619 PP_Size* size) {
2620 blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2621 *size = PP_MakeSize(info.rect.width, info.rect.height);
2622 return PP_TRUE;
2625 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2626 PP_Instance instance,
2627 ppapi::SingletonResourceID id) {
2628 // Flash APIs and some others aren't implemented in-process.
2629 switch (id) {
2630 case ppapi::BROKER_SINGLETON_ID:
2631 case ppapi::BROWSER_FONT_SINGLETON_ID:
2632 case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2633 case ppapi::FLASH_FILE_SINGLETON_ID:
2634 case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2635 case ppapi::FLASH_SINGLETON_ID:
2636 case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2637 case ppapi::NETWORK_PROXY_SINGLETON_ID:
2638 case ppapi::PDF_SINGLETON_ID:
2639 case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2640 NOTIMPLEMENTED();
2641 return NULL;
2642 case ppapi::GAMEPAD_SINGLETON_ID:
2643 return gamepad_impl_.get();
2644 case ppapi::UMA_SINGLETON_ID: {
2645 if (!uma_private_impl_.get()) {
2646 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2647 if (host_impl->in_process_router()) {
2648 uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2649 host_impl->in_process_router()->GetPluginConnection(instance),
2650 instance);
2653 return uma_private_impl_.get();
2657 NOTREACHED();
2658 return NULL;
2661 int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2662 uint32_t event_classes) {
2663 input_event_mask_ |= event_classes;
2664 filtered_input_event_mask_ &= ~(event_classes);
2665 RequestInputEventsHelper(event_classes);
2666 return ValidateRequestInputEvents(false, event_classes);
2669 int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2670 PP_Instance instance,
2671 uint32_t event_classes) {
2672 filtered_input_event_mask_ |= event_classes;
2673 input_event_mask_ &= ~(event_classes);
2674 RequestInputEventsHelper(event_classes);
2675 return ValidateRequestInputEvents(true, event_classes);
2678 void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2679 uint32_t event_classes) {
2680 input_event_mask_ &= ~(event_classes);
2681 filtered_input_event_mask_ &= ~(event_classes);
2682 RequestInputEventsHelper(event_classes);
2685 void PepperPluginInstanceImpl::StartTrackingLatency(PP_Instance instance) {
2686 if (module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
2687 is_tracking_latency_ = true;
2690 void PepperPluginInstanceImpl::ZoomChanged(PP_Instance instance,
2691 double factor) {
2692 // We only want to tell the page to change its zoom if the whole page is the
2693 // plugin. If we're in an iframe, then don't do anything.
2694 if (!IsFullPagePlugin())
2695 return;
2696 container()->zoomLevelChanged(content::ZoomFactorToZoomLevel(factor));
2699 void PepperPluginInstanceImpl::ZoomLimitsChanged(PP_Instance instance,
2700 double minimum_factor,
2701 double maximum_factor) {
2702 if (!render_frame_)
2703 return;
2704 if (minimum_factor > maximum_factor) {
2705 NOTREACHED();
2706 return;
2708 double minimum_level = ZoomFactorToZoomLevel(minimum_factor);
2709 double maximum_level = ZoomFactorToZoomLevel(maximum_factor);
2710 render_frame_->render_view()->webview()->zoomLimitsChanged(minimum_level,
2711 maximum_level);
2714 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2715 PP_Var message) {
2716 PostMessageToJavaScript(message);
2719 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2720 PP_MouseCursor_Type type,
2721 PP_Resource image,
2722 const PP_Point* hot_spot) {
2723 if (!ValidateSetCursorParams(type, image, hot_spot))
2724 return PP_FALSE;
2726 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2727 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2728 return PP_TRUE;
2731 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2732 if (enter.failed())
2733 return PP_FALSE;
2734 PPB_ImageData_Impl* image_data =
2735 static_cast<PPB_ImageData_Impl*>(enter.object());
2737 ImageDataAutoMapper auto_mapper(image_data);
2738 if (!auto_mapper.is_valid())
2739 return PP_FALSE;
2741 scoped_ptr<WebCursorInfo> custom_cursor(
2742 new WebCursorInfo(WebCursorInfo::TypeCustom));
2743 custom_cursor->hotSpot.x = hot_spot->x;
2744 custom_cursor->hotSpot.y = hot_spot->y;
2746 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2747 // Make a deep copy, so that the cursor remains valid even after the original
2748 // image data gets freed.
2749 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2750 return PP_FALSE;
2753 DoSetCursor(custom_cursor.release());
2754 return PP_TRUE;
2757 int32_t PepperPluginInstanceImpl::LockMouse(
2758 PP_Instance instance,
2759 scoped_refptr<TrackedCallback> callback) {
2760 if (TrackedCallback::IsPending(lock_mouse_callback_))
2761 return PP_ERROR_INPROGRESS;
2763 if (IsMouseLocked())
2764 return PP_OK;
2766 if (!CanAccessMainFrame())
2767 return PP_ERROR_NOACCESS;
2769 if (!IsProcessingUserGesture())
2770 return PP_ERROR_NO_USER_GESTURE;
2772 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2773 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2774 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2775 // Open a user gesture here so the Webkit user gesture checks will succeed
2776 // for out-of-process plugins.
2777 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2778 if (!LockMouse())
2779 return PP_ERROR_FAILED;
2782 // Either mouselock succeeded or a Flash fullscreen is pending.
2783 lock_mouse_callback_ = callback;
2784 return PP_OK_COMPLETIONPENDING;
2787 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2788 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2791 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2792 PP_TextInput_Type type) {
2793 if (!render_frame_)
2794 return;
2795 int itype = type;
2796 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2797 itype = ui::TEXT_INPUT_TYPE_NONE;
2798 SetTextInputType(static_cast<ui::TextInputType>(itype));
2801 void PepperPluginInstanceImpl::UpdateCaretPosition(
2802 PP_Instance instance,
2803 const PP_Rect& caret,
2804 const PP_Rect& bounding_box) {
2805 if (!render_frame_)
2806 return;
2807 text_input_caret_ = PP_ToGfxRect(caret);
2808 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2809 text_input_caret_set_ = true;
2810 render_frame_->PepperCaretPositionChanged(this);
2813 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2814 if (render_frame_)
2815 render_frame_->PepperCancelComposition(this);
2818 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2819 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2820 // It can be optimized so that it won't call it back until the information
2821 // is really needed.
2823 // Avoid calling in nested context or else this will reenter the plugin. This
2824 // uses a weak pointer rather than exploiting the fact that this class is
2825 // refcounted because we don't actually want this operation to affect the
2826 // lifetime of the instance.
2827 base::MessageLoop::current()->PostTask(
2828 FROM_HERE,
2829 base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2830 weak_factory_.GetWeakPtr(),
2831 static_cast<size_t>(kExtraCharsForTextInput)));
2834 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2835 const char* text,
2836 uint32_t caret,
2837 uint32_t anchor) {
2838 if (!render_frame_)
2839 return;
2840 surrounding_text_ = text;
2841 selection_caret_ = caret;
2842 selection_anchor_ = anchor;
2843 render_frame_->PepperSelectionChanged(this);
2846 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2847 PP_Instance instance,
2848 PP_Var relative,
2849 PP_URLComponents_Dev* components) {
2850 StringVar* relative_string = StringVar::FromPPVar(relative);
2851 if (!relative_string)
2852 return PP_MakeNull();
2854 WebElement plugin_element = container()->element();
2855 GURL document_url = plugin_element.document().baseURL();
2856 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2857 document_url.Resolve(relative_string->value()), components);
2860 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2861 PP_Var url) {
2862 StringVar* url_string = StringVar::FromPPVar(url);
2863 if (!url_string)
2864 return PP_FALSE;
2866 blink::WebSecurityOrigin security_origin;
2867 if (!SecurityOriginForInstance(instance, &security_origin))
2868 return PP_FALSE;
2870 GURL gurl(url_string->value());
2871 if (!gurl.is_valid())
2872 return PP_FALSE;
2874 return PP_FromBool(security_origin.canRequest(gurl));
2877 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2878 PP_Instance instance,
2879 PP_Instance target) {
2880 blink::WebSecurityOrigin our_origin;
2881 if (!SecurityOriginForInstance(instance, &our_origin))
2882 return PP_FALSE;
2884 blink::WebSecurityOrigin target_origin;
2885 if (!SecurityOriginForInstance(instance, &target_origin))
2886 return PP_FALSE;
2888 return PP_FromBool(our_origin.canAccess(target_origin));
2891 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2892 PP_Instance instance,
2893 PP_URLComponents_Dev* components) {
2894 blink::WebDocument document = container()->element().document();
2895 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2896 components);
2899 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2900 PP_Instance instance,
2901 PP_URLComponents_Dev* components) {
2902 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2905 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2906 PP_Instance instance,
2907 PP_URLComponents_Dev* components) {
2908 blink::WebDocument document = container()->element().document();
2909 if (!full_frame_)
2910 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2911 components);
2912 WebLocalFrame* frame = document.frame();
2913 if (!frame)
2914 return PP_MakeUndefined();
2915 const WebURLRequest& request = frame->dataSource()->originalRequest();
2916 WebString referer = request.httpHeaderField("Referer");
2917 if (referer.isEmpty())
2918 return PP_MakeUndefined();
2919 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2920 components);
2923 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2924 scoped_refptr<PluginModule> module) {
2925 // Save the original module and switch over to the new one now that this
2926 // plugin is using the IPC-based proxy.
2927 original_module_ = module_;
2928 module_ = module;
2930 // For NaCl instances, remember the NaCl plugin instance interface, so we
2931 // can shut it down by calling its DidDestroy in our Delete() method.
2932 original_instance_interface_.reset(instance_interface_.release());
2934 base::Callback<const void*(const char*)> get_plugin_interface_func =
2935 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2936 PPP_Instance_Combined* ppp_instance_combined =
2937 PPP_Instance_Combined::Create(get_plugin_interface_func);
2938 if (!ppp_instance_combined) {
2939 // The proxy must support at least one usable PPP_Instance interface.
2940 // While this could be a failure to implement the interface in the NaCl
2941 // module, it is more likely that the NaCl process has crashed. Either
2942 // way, report that module initialization failed.
2943 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2946 instance_interface_.reset(ppp_instance_combined);
2947 // Clear all PPP interfaces we may have cached.
2948 plugin_find_interface_ = NULL;
2949 plugin_input_event_interface_ = NULL;
2950 checked_for_plugin_input_event_interface_ = false;
2951 plugin_mouse_lock_interface_ = NULL;
2952 plugin_pdf_interface_ = NULL;
2953 checked_for_plugin_pdf_interface_ = false;
2954 plugin_private_interface_ = NULL;
2955 plugin_textinput_interface_ = NULL;
2956 plugin_zoom_interface_ = NULL;
2958 // Re-send the DidCreate event via the proxy.
2959 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2960 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2961 if (!instance_interface_->DidCreate(
2962 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2963 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2964 if (message_channel_)
2965 message_channel_->Start();
2967 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2968 // event. This way, SendDidChangeView will send the "current" view
2969 // immediately (before other events like HandleDocumentLoad).
2970 sent_initial_did_change_view_ = false;
2971 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2972 SendDidChangeView();
2974 DCHECK(external_document_load_);
2975 external_document_load_ = false;
2976 if (!external_document_response_.isNull()) {
2977 document_loader_ = NULL;
2978 // Pass the response to the new proxy.
2979 HandleDocumentLoad(external_document_response_);
2980 external_document_response_ = blink::WebURLResponse();
2981 // Replay any document load events we've received to the real loader.
2982 external_document_loader_->ReplayReceivedData(document_loader_);
2983 external_document_loader_.reset(NULL);
2986 return PP_EXTERNAL_PLUGIN_OK;
2989 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2990 DCHECK(module);
2991 return module == module_.get() || module == original_module_.get();
2994 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2995 return HostGlobals::Get()->GetInstance(instance_id);
2998 RenderView* PepperPluginInstanceImpl::GetRenderView() {
2999 return render_frame_ ? render_frame_->render_view() : NULL;
3002 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
3003 return container_;
3006 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
3008 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
3009 return HostGlobals::Get()->GetVarTracker();
3012 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
3014 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
3015 return module_->path();
3018 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
3019 float scale) {
3020 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
3022 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
3023 return 0;
3025 scoped_refptr<PPB_ImageData_Impl> image_data(
3026 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
3027 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
3028 image_skia_rep.pixel_width(),
3029 image_skia_rep.pixel_height(),
3030 false)) {
3031 return 0;
3034 ImageDataAutoMapper mapper(image_data.get());
3035 if (!mapper.is_valid())
3036 return 0;
3038 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
3039 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
3040 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
3041 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
3043 return image_data->GetReference();
3046 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
3047 const base::FilePath& file_path,
3048 ppapi::PpapiPermissions permissions,
3049 const IPC::ChannelHandle& channel_handle,
3050 base::ProcessId plugin_pid,
3051 int plugin_child_id) {
3052 // Create a new module for each instance of the external plugin that is using
3053 // the IPC based out-of-process proxy. We can't use the existing module,
3054 // because it is configured for the in-process plugin, and we must keep it
3055 // that way to allow the page to create other instances.
3056 scoped_refptr<PluginModule> external_plugin_module(
3057 module_->CreateModuleForExternalPluginInstance());
3059 RendererPpapiHostImpl* renderer_ppapi_host =
3060 external_plugin_module->CreateOutOfProcessModule(render_frame_,
3061 file_path,
3062 permissions,
3063 channel_handle,
3064 plugin_pid,
3065 plugin_child_id,
3066 true);
3067 if (!renderer_ppapi_host) {
3068 DLOG(ERROR) << "CreateExternalPluginModule() failed";
3069 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
3072 // Finally, switch the instance to the proxy.
3073 return external_plugin_module->InitAsProxiedExternalPlugin(this);
3076 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3077 always_on_top_ = on_top;
3080 void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
3081 cursor_.reset(cursor);
3082 if (fullscreen_container_) {
3083 fullscreen_container_->DidChangeCursor(*cursor);
3084 } else if (render_frame_) {
3085 render_frame_->PepperDidChangeCursor(this, *cursor);
3089 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3090 WebLocalFrame* frame = container()->element().document().frame();
3091 return frame->view()->mainFrame()->document().isPluginDocument();
3094 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3095 bool delay_report) {
3096 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3097 // Keep a reference on the stack. See NOTE above.
3098 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3100 // We check whether we are trying to switch to the state we're already going
3101 // to (i.e. if we're already switching to fullscreen but the fullscreen
3102 // container isn't ready yet, don't do anything more).
3103 if (fullscreen == FlashIsFullscreenOrPending())
3104 return true;
3106 if (!render_frame_)
3107 return false;
3108 if (fullscreen && !render_frame_->render_view()
3109 ->renderer_preferences()
3110 .plugin_fullscreen_allowed)
3111 return false;
3113 // Unbind current 2D or 3D graphics context.
3114 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3115 if (fullscreen) {
3116 DCHECK(!fullscreen_container_);
3117 fullscreen_container_ =
3118 render_frame_->CreatePepperFullscreenContainer(this);
3119 UpdateLayer(false);
3120 } else {
3121 DCHECK(fullscreen_container_);
3122 fullscreen_container_->Destroy();
3123 fullscreen_container_ = NULL;
3124 UpdateFlashFullscreenState(false);
3125 if (!delay_report) {
3126 ReportGeometry();
3127 } else {
3128 base::MessageLoop::current()->PostTask(
3129 FROM_HERE,
3130 base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3134 return true;
3137 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3138 if (is_deleted_)
3139 return false;
3141 if (flash_fullscreen_)
3142 return true;
3144 return container_->isRectTopmost(rect);
3147 int32_t PepperPluginInstanceImpl::Navigate(
3148 const ppapi::URLRequestInfoData& request,
3149 const char* target,
3150 bool from_user_action) {
3151 if (!container_)
3152 return PP_ERROR_FAILED;
3154 WebDocument document = container_->element().document();
3155 WebLocalFrame* frame = document.frame();
3156 if (!frame)
3157 return PP_ERROR_FAILED;
3159 ppapi::URLRequestInfoData completed_request = request;
3161 WebURLRequest web_request;
3162 if (!CreateWebURLRequest(
3163 pp_instance_, &completed_request, frame, &web_request)) {
3164 return PP_ERROR_FAILED;
3166 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3167 if (IsProcessingUserGesture())
3168 web_request.setHasUserGesture(true);
3170 GURL gurl(web_request.url());
3171 if (gurl.SchemeIs(url::kJavaScriptScheme)) {
3172 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3173 // allowed for security reasons.
3174 WebFrame* target_frame =
3175 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3176 if (target_frame != frame)
3177 return PP_ERROR_NOACCESS;
3179 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3180 // need that?
3181 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
3182 WebString result = container_->executeScriptURL(gurl, false);
3183 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3186 // Only GETs and POSTs are supported.
3187 if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3188 return PP_ERROR_BADARGUMENT;
3190 WebString target_str = WebString::fromUTF8(target);
3191 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
3192 container_->loadFrameRequest(web_request, target_str, false, NULL);
3193 return PP_OK;
3196 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3197 const base::FilePath& path) {
3198 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3199 PepperFileRefRendererHost* file_ref_host(
3200 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3201 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3202 scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3205 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3206 if (message_channel_)
3207 message_channel_->SetReadOnlyProperty(key, value);
3210 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3211 if (!container_)
3212 return false;
3213 blink::WebDocument containing_document = container_->element().document();
3215 if (!containing_document.frame() || !containing_document.frame()->view() ||
3216 !containing_document.frame()->view()->mainFrame()) {
3217 return false;
3219 blink::WebDocument main_document =
3220 containing_document.frame()->view()->mainFrame()->document();
3222 return containing_document.securityOrigin().canAccess(
3223 main_document.securityOrigin());
3226 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3227 WebElement element = container_->element();
3228 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3229 height_before_fullscreen_ =
3230 element.getAttribute(WebString::fromUTF8(kHeight));
3231 border_before_fullscreen_ =
3232 element.getAttribute(WebString::fromUTF8(kBorder));
3233 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3236 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3237 if (!render_frame_)
3238 return;
3239 blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3240 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3241 std::string width = StringPrintf("%d", screen_size_for_fullscreen_.width());
3242 std::string height = StringPrintf("%d", screen_size_for_fullscreen_.height());
3244 WebElement element = container_->element();
3245 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3246 element.setAttribute(WebString::fromUTF8(kHeight),
3247 WebString::fromUTF8(height));
3248 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3250 // There should be no style settings that matter in fullscreen mode,
3251 // so just replace them instead of appending.
3252 // NOTE: "position: fixed" and "display: block" reset the plugin and
3253 // using %% settings might not work without them (e.g. if the plugin is a
3254 // child of a container element).
3255 std::string style;
3256 style += StringPrintf("width: %s !important; ", width.c_str());
3257 style += StringPrintf("height: %s !important; ", height.c_str());
3258 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3259 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3262 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3263 screen_size_for_fullscreen_ = gfx::Size();
3264 WebElement element = container_->element();
3265 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3266 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3267 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3268 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3271 bool PepperPluginInstanceImpl::IsMouseLocked() {
3272 return GetMouseLockDispatcher()->IsMouseLockedTo(
3273 GetOrCreateLockTargetAdapter());
3276 bool PepperPluginInstanceImpl::LockMouse() {
3277 return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3280 MouseLockDispatcher::LockTarget*
3281 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3282 if (!lock_target_.get()) {
3283 lock_target_.reset(new PluginInstanceLockTarget(this));
3285 return lock_target_.get();
3288 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3289 if (flash_fullscreen_) {
3290 RenderWidgetFullscreenPepper* container =
3291 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3292 return container->mouse_lock_dispatcher();
3293 } else if (render_frame_) {
3294 return render_frame_->render_view()->mouse_lock_dispatcher();
3296 return NULL;
3299 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3300 if (lock_target_.get()) {
3301 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3302 lock_target_.reset();
3306 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3307 const blink::WebURLResponse& response,
3308 int pending_host_id,
3309 const ppapi::URLResponseInfoData& data) {
3310 if (is_deleted_)
3311 return;
3313 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3315 if (host_impl->in_process_router()) {
3316 // Running in-process, we can just create the resource and call the
3317 // PPP_Instance function directly.
3318 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3319 new ppapi::proxy::URLLoaderResource(
3320 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3321 pp_instance(),
3322 pending_host_id,
3323 data));
3325 PP_Resource loader_pp_resource = loader_resource->GetReference();
3326 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3327 loader_pp_resource))
3328 loader_resource->Close();
3329 // We don't pass a ref into the plugin, if it wants one, it will have taken
3330 // an additional one.
3331 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3332 loader_pp_resource);
3333 } else {
3334 // Running out-of-process. Initiate an IPC call to notify the plugin
3335 // process.
3336 ppapi::proxy::HostDispatcher* dispatcher =
3337 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3338 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3339 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3343 void PepperPluginInstanceImpl::RecordFlashJavaScriptUse() {
3344 if (initialized_ && !javascript_used_ && is_flash_plugin_) {
3345 javascript_used_ = true;
3346 RenderThread::Get()->RecordAction(
3347 base::UserMetricsAction("Flash.JavaScriptUsed"));
3351 } // namespace content