Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / renderer / pepper / pepper_plugin_instance_impl.cc
blob0618ddb3361359675dd546d0064148b9c479d1c2
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
7 #include "base/bind.h"
8 #include "base/callback_helpers.h"
9 #include "base/location.h"
10 #include "base/logging.h"
11 #include "base/memory/linked_ptr.h"
12 #include "base/metrics/histogram.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_offset_string_conversions.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/time/time.h"
21 #include "base/trace_event/trace_event.h"
22 #include "cc/blink/web_layer_impl.h"
23 #include "cc/layers/texture_layer.h"
24 #include "cc/output/latency_info_swap_promise.h"
25 #include "cc/trees/layer_tree_host.h"
26 #include "content/common/content_constants_internal.h"
27 #include "content/common/frame_messages.h"
28 #include "content/common/input/web_input_event_traits.h"
29 #include "content/common/view_messages.h"
30 #include "content/public/common/content_constants.h"
31 #include "content/public/renderer/content_renderer_client.h"
32 #include "content/renderer/gpu/render_widget_compositor.h"
33 #include "content/renderer/pepper/content_decryptor_delegate.h"
34 #include "content/renderer/pepper/event_conversion.h"
35 #include "content/renderer/pepper/fullscreen_container.h"
36 #include "content/renderer/pepper/gfx_conversion.h"
37 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
38 #include "content/renderer/pepper/host_globals.h"
39 #include "content/renderer/pepper/message_channel.h"
40 #include "content/renderer/pepper/pepper_browser_connection.h"
41 #include "content/renderer/pepper/pepper_compositor_host.h"
42 #include "content/renderer/pepper/pepper_file_ref_renderer_host.h"
43 #include "content/renderer/pepper/pepper_graphics_2d_host.h"
44 #include "content/renderer/pepper/pepper_in_process_router.h"
45 #include "content/renderer/pepper/pepper_plugin_instance_metrics.h"
46 #include "content/renderer/pepper/pepper_try_catch.h"
47 #include "content/renderer/pepper/pepper_url_loader_host.h"
48 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
49 #include "content/renderer/pepper/plugin_module.h"
50 #include "content/renderer/pepper/plugin_object.h"
51 #include "content/renderer/pepper/ppapi_preferences_builder.h"
52 #include "content/renderer/pepper/ppb_buffer_impl.h"
53 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
54 #include "content/renderer/pepper/ppb_image_data_impl.h"
55 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
56 #include "content/renderer/pepper/url_request_info_util.h"
57 #include "content/renderer/pepper/url_response_info_util.h"
58 #include "content/renderer/render_frame_impl.h"
59 #include "content/renderer/render_thread_impl.h"
60 #include "content/renderer/render_view_impl.h"
61 #include "content/renderer/render_widget.h"
62 #include "content/renderer/render_widget_fullscreen_pepper.h"
63 #include "content/renderer/sad_plugin.h"
64 #include "media/base/audio_hardware_config.h"
65 #include "ppapi/c/dev/ppp_text_input_dev.h"
66 #include "ppapi/c/pp_rect.h"
67 #include "ppapi/c/ppb_audio_config.h"
68 #include "ppapi/c/ppb_core.h"
69 #include "ppapi/c/ppb_gamepad.h"
70 #include "ppapi/c/ppp_input_event.h"
71 #include "ppapi/c/ppp_instance.h"
72 #include "ppapi/c/ppp_messaging.h"
73 #include "ppapi/c/ppp_mouse_lock.h"
74 #include "ppapi/c/private/ppb_find_private.h"
75 #include "ppapi/c/private/ppp_find_private.h"
76 #include "ppapi/c/private/ppp_instance_private.h"
77 #include "ppapi/c/private/ppp_pdf.h"
78 #include "ppapi/host/ppapi_host.h"
79 #include "ppapi/proxy/ppapi_messages.h"
80 #include "ppapi/proxy/serialized_var.h"
81 #include "ppapi/proxy/uma_private_resource.h"
82 #include "ppapi/proxy/url_loader_resource.h"
83 #include "ppapi/shared_impl/ppapi_permissions.h"
84 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
85 #include "ppapi/shared_impl/ppb_input_event_shared.h"
86 #include "ppapi/shared_impl/ppb_url_util_shared.h"
87 #include "ppapi/shared_impl/ppb_view_shared.h"
88 #include "ppapi/shared_impl/ppp_instance_combined.h"
89 #include "ppapi/shared_impl/resource.h"
90 #include "ppapi/shared_impl/scoped_pp_resource.h"
91 #include "ppapi/shared_impl/scoped_pp_var.h"
92 #include "ppapi/shared_impl/time_conversion.h"
93 #include "ppapi/shared_impl/url_request_info_data.h"
94 #include "ppapi/shared_impl/var.h"
95 #include "ppapi/thunk/enter.h"
96 #include "ppapi/thunk/ppb_buffer_api.h"
97 #include "printing/metafile_skia_wrapper.h"
98 #include "printing/pdf_metafile_skia.h"
99 #include "skia/ext/platform_canvas.h"
100 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
101 #include "third_party/WebKit/public/platform/WebGamepads.h"
102 #include "third_party/WebKit/public/platform/WebRect.h"
103 #include "third_party/WebKit/public/platform/WebString.h"
104 #include "third_party/WebKit/public/platform/WebURL.h"
105 #include "third_party/WebKit/public/platform/WebURLError.h"
106 #include "third_party/WebKit/public/platform/WebURLRequest.h"
107 #include "third_party/WebKit/public/web/WebBindings.h"
108 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
109 #include "third_party/WebKit/public/web/WebDataSource.h"
110 #include "third_party/WebKit/public/web/WebDocument.h"
111 #include "third_party/WebKit/public/web/WebInputEvent.h"
112 #include "third_party/WebKit/public/web/WebLocalFrame.h"
113 #include "third_party/WebKit/public/web/WebPluginContainer.h"
114 #include "third_party/WebKit/public/web/WebPluginScriptForbiddenScope.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 checked_for_plugin_input_event_interface_(false),
502 checked_for_plugin_pdf_interface_(false),
503 gamepad_impl_(new GamepadImpl()),
504 uma_private_impl_(NULL),
505 plugin_print_interface_(NULL),
506 plugin_graphics_3d_interface_(NULL),
507 always_on_top_(false),
508 fullscreen_container_(NULL),
509 flash_fullscreen_(false),
510 desired_fullscreen_state_(false),
511 message_channel_(NULL),
512 sad_plugin_(NULL),
513 input_event_mask_(0),
514 filtered_input_event_mask_(0),
515 text_input_type_(kPluginDefaultTextInputType),
516 text_input_caret_(0, 0, 0, 0),
517 text_input_caret_bounds_(0, 0, 0, 0),
518 text_input_caret_set_(false),
519 selection_caret_(0),
520 selection_anchor_(0),
521 pending_user_gesture_(0.0),
522 document_loader_(NULL),
523 external_document_load_(false),
524 isolate_(v8::Isolate::GetCurrent()),
525 is_deleted_(false),
526 last_input_number_(0),
527 is_tracking_latency_(false),
528 initialized_(false),
529 view_change_weak_ptr_factory_(this),
530 weak_factory_(this) {
531 pp_instance_ = HostGlobals::Get()->AddInstance(this);
533 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
534 module_->InstanceCreated(this);
536 if (render_frame) { // NULL in tests
537 render_frame->render_view()->PepperInstanceCreated(this);
538 // Bind a callback now so that we can inform the RenderViewImpl when we are
539 // destroyed. This works around a temporary problem stemming from work to
540 // move parts of RenderViewImpl in to RenderFrameImpl (see
541 // crbug.com/245126). If destruction happens in this order:
542 // 1) RenderFrameImpl
543 // 2) PepperPluginInstanceImpl
544 // 3) RenderViewImpl
545 // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
546 // to the RenderViewImpl. But when the instance is destroyed, it still
547 // needs to inform the RenderViewImpl that it has gone away, otherwise
548 // between (2) and (3), the RenderViewImpl will still have the dead
549 // instance in its active set, and so might make calls on the deleted
550 // instance. See crbug.com/343576 for more information. Once the plugin
551 // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
552 // can be a little bit simplified by instead making a direct call on
553 // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
554 instance_deleted_callback_ =
555 base::Bind(&RenderViewImpl::PepperInstanceDeleted,
556 render_frame->render_view()->AsWeakPtr(),
557 base::Unretained(this));
558 view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
560 // Set the initial focus.
561 SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
563 if (!module_->IsProxied()) {
564 PepperBrowserConnection* browser_connection =
565 PepperBrowserConnection::Get(render_frame_);
566 browser_connection->DidCreateInProcessInstance(
567 pp_instance(),
568 render_frame_->GetRoutingID(),
569 document_url_,
570 GetPluginURL());
574 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
575 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
577 if (GetContentClient()->renderer() && // NULL in unit tests.
578 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
579 external_document_load_ = true;
582 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
583 DCHECK(!fullscreen_container_);
585 // Notify all the plugin objects of deletion. This will prevent blink from
586 // calling into the plugin any more.
588 // Swap out the set so we can delete from it (the objects will try to
589 // unregister themselves inside the delete call).
590 PluginObjectSet plugin_object_copy;
591 live_plugin_objects_.swap(plugin_object_copy);
592 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
593 i != plugin_object_copy.end();
594 ++i) {
595 (*i)->InstanceDeleted();
598 if (message_channel_)
599 message_channel_->InstanceDeleted();
600 message_channel_object_.Reset();
602 if (TrackedCallback::IsPending(lock_mouse_callback_))
603 lock_mouse_callback_->Abort();
605 if (!instance_deleted_callback_.is_null())
606 instance_deleted_callback_.Run();
608 if (!module_->IsProxied() && render_frame_) {
609 PepperBrowserConnection* browser_connection =
610 PepperBrowserConnection::Get(render_frame_);
611 browser_connection->DidDeleteInProcessInstance(pp_instance());
614 UnSetAndDeleteLockTargetAdapter();
615 module_->InstanceDeleted(this);
616 // If we switched from the NaCl plugin module, notify it too.
617 if (original_module_.get())
618 original_module_->InstanceDeleted(this);
620 // This should be last since some of the above "instance deleted" calls will
621 // want to look up in the global map to get info off of our object.
622 HostGlobals::Get()->InstanceDeleted(pp_instance_);
624 if (throttler_)
625 throttler_->RemoveObserver(this);
628 // NOTE: Any of these methods that calls into the plugin needs to take into
629 // account that the plugin may use Var to remove the <embed> from the DOM, which
630 // will make the PepperWebPluginImpl drop its reference, usually the last one.
631 // If a method needs to access a member of the instance after the call has
632 // returned, then it needs to keep its own reference on the stack.
634 v8::Local<v8::Object> PepperPluginInstanceImpl::GetMessageChannelObject() {
635 return v8::Local<v8::Object>::New(isolate_, message_channel_object_);
638 void PepperPluginInstanceImpl::MessageChannelDestroyed() {
639 message_channel_ = NULL;
640 message_channel_object_.Reset();
643 v8::Local<v8::Context> PepperPluginInstanceImpl::GetMainWorldContext() {
644 if (!container_)
645 return v8::Local<v8::Context>();
647 if (container_->element().isNull())
648 return v8::Local<v8::Context>();
650 if (container_->element().document().isNull())
651 return v8::Local<v8::Context>();
653 if (!container_->element().document().frame())
654 return v8::Local<v8::Context>();
656 v8::Local<v8::Context> context =
657 container_->element().document().frame()->mainWorldScriptContext();
658 DCHECK(context->GetIsolate() == isolate_);
659 return context;
662 void PepperPluginInstanceImpl::Delete() {
663 is_deleted_ = true;
665 if (render_frame_ && render_frame_->render_view() &&
666 render_frame_->render_view()->plugin_find_handler() == this) {
667 render_frame_->render_view()->set_plugin_find_handler(NULL);
670 // Keep a reference on the stack. See NOTE above.
671 scoped_refptr<PepperPluginInstanceImpl> ref(this);
673 // It is important to destroy the throttler before anything else.
674 // The plugin instance may flush its graphics pipeline during its postmortem
675 // spasm, causing the throttler to engage and obtain new dangling reference
676 // to the plugin container being destroyed.
677 throttler_.reset();
679 // Force the MessageChannel to release its "passthrough object" which should
680 // release our last reference to the "InstanceObject" and will probably
681 // destroy it. We want to do this prior to calling DidDestroy in case the
682 // destructor of the instance object tries to use the instance.
683 if (message_channel_)
684 message_channel_->SetPassthroughObject(v8::Local<v8::Object>());
685 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
686 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
687 // since there is little that it can do at this point.
688 if (original_instance_interface_) {
689 base::TimeTicks start = base::TimeTicks::Now();
690 original_instance_interface_->DidDestroy(pp_instance());
691 UMA_HISTOGRAM_CUSTOM_TIMES("NaCl.Perf.ShutdownTime.Total",
692 base::TimeTicks::Now() - start,
693 base::TimeDelta::FromMilliseconds(1),
694 base::TimeDelta::FromSeconds(20),
695 100);
696 } else {
697 instance_interface_->DidDestroy(pp_instance());
699 // Ensure we don't attempt to call functions on the destroyed instance.
700 original_instance_interface_.reset();
701 instance_interface_.reset();
703 if (fullscreen_container_) {
704 fullscreen_container_->Destroy();
705 fullscreen_container_ = NULL;
708 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
709 // leaks the graphics 2D, it may actually get cleaned up after our
710 // destruction, so we need its pointers to be up-to-date.
711 BindGraphics(pp_instance(), 0);
712 container_ = NULL;
715 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
717 void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
718 const gfx::Rect& plugin_rect,
719 const gfx::Rect& paint_rect) {
720 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
721 if (module()->is_crashed()) {
722 // Crashed plugin painting.
723 if (!sad_plugin_) // Lazily initialize bitmap.
724 sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
725 if (sad_plugin_)
726 PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
727 return;
730 if (bound_graphics_2d_platform_)
731 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
734 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
735 if (fullscreen_container_) {
736 if (rect.IsEmpty())
737 fullscreen_container_->Invalidate();
738 else
739 fullscreen_container_->InvalidateRect(rect);
740 } else {
741 if (!container_ || view_data_.rect.size.width == 0 ||
742 view_data_.rect.size.height == 0)
743 return; // Nothing to do.
744 if (rect.IsEmpty())
745 container_->invalidate();
746 else
747 container_->invalidateRect(rect);
750 cc::Layer* layer =
751 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
752 if (layer) {
753 if (rect.IsEmpty()) {
754 layer->SetNeedsDisplay();
755 } else {
756 layer->SetNeedsDisplayRect(rect);
761 void PepperPluginInstanceImpl::ScrollRect(int dx,
762 int dy,
763 const gfx::Rect& rect) {
764 cc::Layer* layer =
765 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
766 if (layer) {
767 InvalidateRect(rect);
768 } else if (fullscreen_container_) {
769 fullscreen_container_->ScrollRect(dx, dy, rect);
770 } else {
771 if (full_frame_ && !IsViewAccelerated()) {
772 container_->scrollRect(rect);
773 } else {
774 // Can't do optimized scrolling since there could be other elements on top
775 // of us or the view renders via the accelerated compositor which is
776 // incompatible with the move and backfill scrolling model.
777 InvalidateRect(rect);
782 void PepperPluginInstanceImpl::CommitBackingTexture() {
783 if (!texture_layer_.get())
784 return;
785 gpu::Mailbox mailbox;
786 uint32 sync_point = 0;
787 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
788 DCHECK(!mailbox.IsZero());
789 DCHECK_NE(sync_point, 0u);
790 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
791 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
792 texture_layer_->SetNeedsDisplay();
795 void PepperPluginInstanceImpl::InstanceCrashed() {
796 // Force free all resources and vars.
797 HostGlobals::Get()->InstanceCrashed(pp_instance());
799 // Free any associated graphics.
800 SetFullscreen(false);
801 FlashSetFullscreen(false, false);
802 // Unbind current 2D or 3D graphics context.
803 BindGraphics(pp_instance(), 0);
804 InvalidateRect(gfx::Rect());
806 if (content_decryptor_delegate_) {
807 content_decryptor_delegate_->InstanceCrashed();
808 content_decryptor_delegate_.reset();
811 if (render_frame_)
812 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
813 UnSetAndDeleteLockTargetAdapter();
816 bool PepperPluginInstanceImpl::Initialize(
817 const std::vector<std::string>& arg_names,
818 const std::vector<std::string>& arg_values,
819 bool full_frame,
820 scoped_ptr<PluginInstanceThrottlerImpl> throttler) {
821 DCHECK(!throttler_);
823 if (!render_frame_)
824 return false;
826 if (throttler) {
827 throttler_ = throttler.Pass();
828 throttler_->AddObserver(this);
831 message_channel_ = MessageChannel::Create(this, &message_channel_object_);
833 full_frame_ = full_frame;
835 UpdateTouchEventRequest();
836 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
838 SetGPUHistogram(ppapi::Preferences(PpapiPreferencesBuilder::Build(
839 render_frame_->render_view()->webkit_preferences())),
840 arg_names,
841 arg_values);
843 argn_ = arg_names;
844 argv_ = arg_values;
845 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
846 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
847 auto weak_this = weak_factory_.GetWeakPtr();
848 bool success = PP_ToBool(instance_interface_->DidCreate(
849 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
850 if (!weak_this) {
851 // The plugin may do synchronous scripting during "DidCreate", so |this|
852 // may be deleted. In that case, return failure and don't touch any
853 // member variables.
854 return false;
856 // If this is a plugin that hosts external plugins, we should delay messages
857 // so that the child plugin that's created later will receive all the
858 // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
860 // A host for external plugins will call ResetAsProxied later, at which point
861 // we can Start() the MessageChannel.
862 if (success && (!module_->renderer_ppapi_host()->IsExternalPluginHost())) {
863 if (message_channel_)
864 message_channel_->Start();
866 initialized_ = success;
867 return success;
870 bool PepperPluginInstanceImpl::HandleDocumentLoad(
871 const blink::WebURLResponse& response) {
872 DCHECK(!document_loader_);
873 if (external_document_load_) {
874 // The external proxy isn't available, so save the response and record
875 // document load notifications for later replay.
876 external_document_response_ = response;
877 external_document_loader_.reset(new ExternalDocumentLoader());
878 document_loader_ = external_document_loader_.get();
879 return true;
882 if (module()->is_crashed()) {
883 // Don't create a resource for a crashed plugin.
884 container()->element().document().frame()->stopLoading();
885 return false;
888 DCHECK(!document_loader_);
890 // Create a loader resource host for this load. Note that we have to set
891 // the document_loader before issuing the in-process
892 // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
893 // call into the instance and expect it to be valid.
894 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
895 PepperURLLoaderHost* loader_host =
896 new PepperURLLoaderHost(host_impl, true, pp_instance(), 0);
897 // TODO(teravest): Remove set_document_loader() from instance and clean up
898 // this relationship.
899 set_document_loader(loader_host);
900 loader_host->didReceiveResponse(NULL, response);
902 // This host will be pending until the resource object attaches to it.
904 // PpapiHost now owns the pointer to loader_host, so we don't have to worry
905 // about managing it.
906 int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
907 scoped_ptr<ppapi::host::ResourceHost>(loader_host));
908 DCHECK(pending_host_id);
910 DataFromWebURLResponse(
911 host_impl,
912 pp_instance(),
913 response,
914 base::Bind(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
915 weak_factory_.GetWeakPtr(),
916 response,
917 pending_host_id));
919 // If the load was not abandoned, document_loader_ will now be set. It's
920 // possible that the load was canceled by now and document_loader_ was
921 // already nulled out.
922 return true;
925 bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
926 PP_InputEvent_Type type,
927 const base::string16& text) {
928 std::vector<blink::WebCompositionUnderline> empty;
929 return SendCompositionEventWithUnderlineInformationToPlugin(
930 type,
931 text,
932 empty,
933 static_cast<int>(text.size()),
934 static_cast<int>(text.size()));
937 bool
938 PepperPluginInstanceImpl::SendCompositionEventWithUnderlineInformationToPlugin(
939 PP_InputEvent_Type type,
940 const base::string16& text,
941 const std::vector<blink::WebCompositionUnderline>& underlines,
942 int selection_start,
943 int selection_end) {
944 // Keep a reference on the stack. See NOTE above.
945 scoped_refptr<PepperPluginInstanceImpl> ref(this);
947 if (!LoadInputEventInterface())
948 return false;
950 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
951 if (!(filtered_input_event_mask_ & event_class) &&
952 !(input_event_mask_ & event_class))
953 return false;
955 ppapi::InputEventData event;
956 event.event_type = type;
957 event.event_time_stamp =
958 ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
960 // Convert UTF16 text to UTF8 with offset conversion.
961 std::vector<size_t> utf16_offsets;
962 utf16_offsets.push_back(selection_start);
963 utf16_offsets.push_back(selection_end);
964 for (size_t i = 0; i < underlines.size(); ++i) {
965 utf16_offsets.push_back(underlines[i].startOffset);
966 utf16_offsets.push_back(underlines[i].endOffset);
968 std::vector<size_t> utf8_offsets(utf16_offsets);
969 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
971 // Set the converted selection range.
972 event.composition_selection_start =
973 (utf8_offsets[0] == std::string::npos ? event.character_text.size()
974 : utf8_offsets[0]);
975 event.composition_selection_end =
976 (utf8_offsets[1] == std::string::npos ? event.character_text.size()
977 : utf8_offsets[1]);
979 // Set the converted segmentation points.
980 // Be sure to add 0 and size(), and remove duplication or errors.
981 std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
982 offset_set.insert(0);
983 offset_set.insert(event.character_text.size());
984 offset_set.erase(std::string::npos);
985 event.composition_segment_offsets.assign(offset_set.begin(),
986 offset_set.end());
988 // Set the composition target.
989 for (size_t i = 0; i < underlines.size(); ++i) {
990 if (underlines[i].thick) {
991 std::vector<uint32_t>::iterator it =
992 std::find(event.composition_segment_offsets.begin(),
993 event.composition_segment_offsets.end(),
994 utf8_offsets[2 * i + 2]);
995 if (it != event.composition_segment_offsets.end()) {
996 event.composition_target_segment =
997 it - event.composition_segment_offsets.begin();
998 break;
1003 // Send the event.
1004 bool handled = false;
1005 if (filtered_input_event_mask_ & event_class)
1006 event.is_filtered = true;
1007 else
1008 handled = true; // Unfiltered events are assumed to be handled.
1009 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1010 new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
1011 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1012 pp_instance(), event_resource->pp_resource()));
1013 return handled;
1016 void PepperPluginInstanceImpl::RequestInputEventsHelper(
1017 uint32_t event_classes) {
1018 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
1019 UpdateTouchEventRequest();
1020 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
1021 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
1024 bool PepperPluginInstanceImpl::HandleCompositionStart(
1025 const base::string16& text) {
1026 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1027 text);
1030 bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1031 const base::string16& text,
1032 const std::vector<blink::WebCompositionUnderline>& underlines,
1033 int selection_start,
1034 int selection_end) {
1035 return SendCompositionEventWithUnderlineInformationToPlugin(
1036 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
1037 text,
1038 underlines,
1039 selection_start,
1040 selection_end);
1043 bool PepperPluginInstanceImpl::HandleCompositionEnd(
1044 const base::string16& text) {
1045 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1046 text);
1049 bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1050 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1053 void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1054 gfx::Range* range) const {
1055 std::vector<size_t> offsets;
1056 offsets.push_back(selection_anchor_);
1057 offsets.push_back(selection_caret_);
1058 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1059 range->set_start(offsets[0] == base::string16::npos ? text->size()
1060 : offsets[0]);
1061 range->set_end(offsets[1] == base::string16::npos ? text->size()
1062 : offsets[1]);
1065 bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1066 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1067 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1070 gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1071 if (!text_input_caret_set_) {
1072 // If it is never set by the plugin, use the bottom left corner.
1073 return gfx::Rect(view_data_.rect.point.x,
1074 view_data_.rect.point.y + view_data_.rect.size.height,
1079 // TODO(kinaba) Take CSS transformation into accont.
1080 // TODO(kinaba) Take bounding_box into account. On some platforms, an
1081 // "exclude rectangle" where candidate window must avoid the region can be
1082 // passed to IME. Currently, we pass only the caret rectangle because
1083 // it is the only information supported uniformly in Chromium.
1084 gfx::Rect caret(text_input_caret_);
1085 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1086 return caret;
1089 bool PepperPluginInstanceImpl::HandleInputEvent(
1090 const blink::WebInputEvent& event,
1091 WebCursorInfo* cursor_info) {
1092 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1094 if (!has_been_clicked_ && is_flash_plugin_ &&
1095 event.type == blink::WebInputEvent::MouseDown &&
1096 (event.modifiers & blink::WebInputEvent::LeftButtonDown)) {
1097 has_been_clicked_ = true;
1098 blink::WebRect bounds = container()->element().boundsInViewportSpace();
1099 RecordFlashClickSizeMetric(bounds.width, bounds.height);
1102 if (throttler_ && throttler_->ConsumeInputEvent(event))
1103 return true;
1105 if (!render_frame_)
1106 return false;
1107 if (WebInputEvent::isMouseEventType(event.type)) {
1108 render_frame_->PepperDidReceiveMouseEvent(this);
1111 // Don't dispatch input events to crashed plugins.
1112 if (module()->is_crashed())
1113 return false;
1115 // Don't send reserved system key events to plugins.
1116 if (IsReservedSystemInputEvent(event))
1117 return false;
1119 // Keep a reference on the stack. See NOTE above.
1120 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1122 bool rv = false;
1123 if (LoadInputEventInterface()) {
1124 PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
1125 if (!event_class)
1126 return false;
1128 if ((filtered_input_event_mask_ & event_class) ||
1129 (input_event_mask_ & event_class)) {
1130 // Actually send the event.
1131 std::vector<ppapi::InputEventData> events;
1132 CreateInputEventData(event, &events);
1134 // Allow the user gesture to be pending after the plugin handles the
1135 // event. This allows out-of-process plugins to respond to the user
1136 // gesture after processing has finished here.
1137 if (WebUserGestureIndicator::isProcessingUserGesture()) {
1138 pending_user_gesture_ =
1139 ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
1140 pending_user_gesture_token_ =
1141 WebUserGestureIndicator::currentUserGestureToken();
1142 pending_user_gesture_token_.setOutOfProcess();
1145 const ui::LatencyInfo* current_event_latency_info = NULL;
1146 if (render_frame_->GetRenderWidget()) {
1147 current_event_latency_info =
1148 render_frame_->GetRenderWidget()->current_event_latency_info();
1151 // Each input event may generate more than one PP_InputEvent.
1152 for (size_t i = 0; i < events.size(); i++) {
1153 if (is_tracking_latency_) {
1154 InitLatencyInfo(&events[i].latency_info,
1155 current_event_latency_info,
1156 event.type,
1157 last_input_number_++);
1159 if (filtered_input_event_mask_ & event_class)
1160 events[i].is_filtered = true;
1161 else
1162 rv = true; // Unfiltered events are assumed to be handled.
1163 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1164 new PPB_InputEvent_Shared(
1165 ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1167 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1168 pp_instance(), event_resource->pp_resource()));
1173 if (cursor_)
1174 *cursor_info = *cursor_;
1175 return rv;
1178 void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1179 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1180 if (is_deleted_)
1181 return;
1182 ppapi::proxy::HostDispatcher* dispatcher =
1183 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1184 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1185 // The dispatcher should always be valid, and MessageChannel should never
1186 // send an 'object' var over PPP_Messaging.
1187 NOTREACHED();
1188 return;
1190 dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1191 ppapi::API_ID_PPP_MESSAGING,
1192 pp_instance(),
1193 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1194 pp_instance())));
1197 bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1198 ScopedPPVar* result) {
1199 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
1200 if (is_deleted_)
1201 return false;
1202 ppapi::proxy::HostDispatcher* dispatcher =
1203 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1204 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1205 // The dispatcher should always be valid, and MessageChannel should never
1206 // send an 'object' var over PPP_Messaging.
1207 NOTREACHED();
1208 return false;
1210 ppapi::proxy::ReceiveSerializedVarReturnValue msg_reply;
1211 bool was_handled = false;
1212 dispatcher->Send(new PpapiMsg_PPPMessageHandler_HandleBlockingMessage(
1213 ppapi::API_ID_PPP_MESSAGING,
1214 pp_instance(),
1215 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1216 pp_instance()),
1217 &msg_reply,
1218 &was_handled));
1219 *result = ScopedPPVar(ScopedPPVar::PassRef(), msg_reply.Return(dispatcher));
1220 TRACE_EVENT0("ppapi",
1221 "PepperPluginInstanceImpl::HandleBlockingMessage return.");
1222 return was_handled;
1225 PP_Var PepperPluginInstanceImpl::GetInstanceObject(v8::Isolate* isolate) {
1226 // Keep a reference on the stack. See NOTE above.
1227 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1229 DCHECK_EQ(isolate, isolate_);
1230 RecordFlashJavaScriptUse();
1232 // If the plugin supports the private instance interface, try to retrieve its
1233 // instance object.
1234 if (LoadPrivateInterface())
1235 return plugin_private_interface_->GetInstanceObject(pp_instance());
1236 return PP_MakeUndefined();
1239 void PepperPluginInstanceImpl::ViewChanged(
1240 const gfx::Rect& window,
1241 const gfx::Rect& clip,
1242 const gfx::Rect& unobscured,
1243 const std::vector<gfx::Rect>& cut_outs_rects) {
1244 // WebKit can give weird (x,y) positions for empty clip rects (since the
1245 // position technically doesn't matter). But we want to make these
1246 // consistent since this is given to the plugin, so force everything to 0
1247 // in the "everything is clipped" case.
1248 gfx::Rect new_clip;
1249 if (!clip.IsEmpty())
1250 new_clip = clip;
1252 unobscured_rect_ = unobscured;
1254 cut_outs_rects_ = cut_outs_rects;
1256 view_data_.rect = PP_FromGfxRect(window);
1257 view_data_.clip_rect = PP_FromGfxRect(clip);
1258 view_data_.device_scale = container_->deviceScaleFactor();
1259 view_data_.css_scale =
1260 container_->pageZoomFactor() * container_->pageScaleFactor();
1262 gfx::Size scroll_offset =
1263 container_->element().document().frame()->scrollOffset();
1264 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1265 scroll_offset.height());
1267 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1268 WebElement element = container_->element();
1269 WebDocument document = element.document();
1270 bool is_fullscreen_element = (element == document.fullScreenElement());
1271 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1272 render_frame()->GetRenderWidget()->is_fullscreen_granted() &&
1273 is_fullscreen_element) {
1274 // Entered fullscreen. Only possible via SetFullscreen().
1275 view_data_.is_fullscreen = true;
1276 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1277 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1278 // so desired_fullscreen_state might be out-of-date.
1279 desired_fullscreen_state_ = false;
1280 view_data_.is_fullscreen = false;
1282 // This operation will cause the plugin to re-layout which will send more
1283 // DidChangeView updates. Schedule an asynchronous update and suppress
1284 // notifications until that completes to avoid sending intermediate sizes
1285 // to the plugins.
1286 ScheduleAsyncDidChangeView();
1288 // Reset the size attributes that we hacked to fill in the screen and
1289 // retrigger ViewChanged. Make sure we don't forward duplicates of
1290 // this view to the plugin.
1291 ResetSizeAttributesAfterFullscreen();
1292 return;
1296 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1298 // During plugin initialization, there are often re-layouts. Avoid sending
1299 // intermediate sizes the plugin and throttler.
1300 if (sent_initial_did_change_view_)
1301 SendDidChangeView();
1302 else
1303 ScheduleAsyncDidChangeView();
1306 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1307 if (has_webkit_focus_ == has_focus)
1308 return;
1310 bool old_plugin_focus = PluginHasFocus();
1311 has_webkit_focus_ = has_focus;
1312 if (PluginHasFocus() != old_plugin_focus)
1313 SendFocusChangeNotification();
1316 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1317 if (has_content_area_focus_ == has_focus)
1318 return;
1320 bool old_plugin_focus = PluginHasFocus();
1321 has_content_area_focus_ = has_focus;
1322 if (PluginHasFocus() != old_plugin_focus)
1323 SendFocusChangeNotification();
1326 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1327 if (is_visible == view_data_.is_page_visible)
1328 return; // Nothing to do.
1329 view_data_.is_page_visible = is_visible;
1331 // If the initial DidChangeView notification hasn't been sent to the plugin,
1332 // let it pass the visibility state for us, instead of sending a notification
1333 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1334 // hasn't been called for the first time. In that case, most of the fields in
1335 // |view_data_| haven't been properly initialized.
1336 if (sent_initial_did_change_view_)
1337 SendDidChangeView();
1340 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1341 if (bound_graphics_2d_platform_)
1342 bound_graphics_2d_platform_->ViewInitiatedPaint();
1343 else if (bound_graphics_3d_.get())
1344 bound_graphics_3d_->ViewInitiatedPaint();
1345 else if (bound_compositor_)
1346 bound_compositor_->ViewInitiatedPaint();
1349 void PepperPluginInstanceImpl::SetSelectedText(
1350 const base::string16& selected_text) {
1351 selected_text_ = selected_text;
1352 gfx::Range range(0, selected_text.length());
1353 render_frame_->SetSelectedText(selected_text, 0, range);
1356 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1357 link_under_cursor_ = base::UTF8ToUTF16(url);
1360 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1361 text_input_type_ = type;
1362 render_frame_->PepperTextInputTypeChanged(this);
1365 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1366 if (message_channel_)
1367 message_channel_->PostMessageToJavaScript(message);
1370 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1371 PP_Instance instance,
1372 void* user_data,
1373 const PPP_MessageHandler_0_2* handler,
1374 PP_Resource message_loop) {
1375 // Not supported in-process.
1376 NOTIMPLEMENTED();
1377 return PP_ERROR_FAILED;
1380 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1381 // Not supported in-process.
1382 NOTIMPLEMENTED();
1385 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1386 return selected_text_;
1389 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1390 const gfx::Point& point) {
1391 // Keep a reference on the stack. See NOTE above.
1392 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1393 if (!LoadPdfInterface()) {
1394 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1395 // return |link_under_cursor_| here because this is only ever called with
1396 // the current mouse coordinates.
1397 return link_under_cursor_;
1400 PP_Point p;
1401 p.x = point.x();
1402 p.y = point.y();
1403 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1404 // If the plugin returns undefined for this function it has switched to
1405 // providing us with the link under the cursor eagerly.
1406 if (rv.type == PP_VARTYPE_UNDEFINED)
1407 return link_under_cursor_;
1408 StringVar* string = StringVar::FromPPVar(rv);
1409 base::string16 link;
1410 if (string)
1411 link = base::UTF8ToUTF16(string->value());
1412 // Release the ref the plugin transfered to us.
1413 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1414 return link;
1417 void PepperPluginInstanceImpl::RequestSurroundingText(
1418 size_t desired_number_of_characters) {
1419 // Keep a reference on the stack. See NOTE above.
1420 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1421 if (!LoadTextInputInterface())
1422 return;
1423 plugin_textinput_interface_->RequestSurroundingText(
1424 pp_instance(), desired_number_of_characters);
1427 bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1428 bool case_sensitive,
1429 int identifier) {
1430 // Keep a reference on the stack. See NOTE above.
1431 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1432 if (!LoadFindInterface())
1433 return false;
1434 find_identifier_ = identifier;
1435 return PP_ToBool(
1436 plugin_find_interface_->StartFind(pp_instance(),
1437 base::UTF16ToUTF8(search_text).c_str(),
1438 PP_FromBool(case_sensitive)));
1441 void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1442 // Keep a reference on the stack. See NOTE above.
1443 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1444 if (LoadFindInterface())
1445 plugin_find_interface_->SelectFindResult(pp_instance(),
1446 PP_FromBool(forward));
1449 void PepperPluginInstanceImpl::StopFind() {
1450 // Keep a reference on the stack. See NOTE above.
1451 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1452 if (!LoadFindInterface())
1453 return;
1454 find_identifier_ = -1;
1455 plugin_find_interface_->StopFind(pp_instance());
1458 bool PepperPluginInstanceImpl::LoadFindInterface() {
1459 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1460 return false;
1461 if (!plugin_find_interface_) {
1462 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1463 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1466 return !!plugin_find_interface_;
1469 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1470 if (!checked_for_plugin_input_event_interface_) {
1471 checked_for_plugin_input_event_interface_ = true;
1472 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1473 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1475 return !!plugin_input_event_interface_;
1478 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1479 if (!plugin_mouse_lock_interface_) {
1480 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1481 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1484 return !!plugin_mouse_lock_interface_;
1487 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1488 if (!checked_for_plugin_pdf_interface_) {
1489 checked_for_plugin_pdf_interface_ = true;
1490 plugin_pdf_interface_ = static_cast<const PPP_Pdf*>(
1491 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1494 return !!plugin_pdf_interface_;
1497 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1498 // Only check for the interface if the plugin has dev permission.
1499 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1500 return false;
1501 if (!plugin_print_interface_) {
1502 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1503 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1505 return !!plugin_print_interface_;
1508 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1509 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1510 // call GetInstanceObject. This is necessary to ensure that the properties
1511 // the trusted plugin exposes (readyState and lastError) work properly. Note
1512 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1513 // so it's correct to never look up PPP_InstancePrivate for them.
1515 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1516 // to the "real" module.
1517 scoped_refptr<PluginModule> module =
1518 original_module_.get() ? original_module_ : module_;
1519 // Only check for the interface if the plugin has private permission.
1520 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1521 return false;
1522 if (!plugin_private_interface_) {
1523 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1524 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1527 return !!plugin_private_interface_;
1530 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1531 if (!plugin_textinput_interface_) {
1532 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1533 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1536 return !!plugin_textinput_interface_;
1539 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1540 if (!bound_graphics_2d_platform_ || !texture_layer_.get()) {
1541 // Currently the transform is only applied for Graphics2D.
1542 return;
1544 // Set the UV coordinates of the texture based on the size of the Graphics2D
1545 // context. By default a texture gets scaled to the size of the layer. But
1546 // if the size of the Graphics2D context doesn't match the size of the plugin
1547 // then it will be incorrectly stretched. This also affects how the plugin
1548 // is painted when it is being resized. If the Graphics2D contents are
1549 // stretched when a plugin is resized while waiting for a new frame from the
1550 // plugin to be rendered, then flickering behavior occurs as in
1551 // crbug.com/353453.
1552 gfx::SizeF graphics_2d_size_in_dip =
1553 gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1554 bound_graphics_2d_platform_->GetScale());
1555 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1556 view_data_.rect.size.height);
1558 texture_layer_->SetUV(
1559 gfx::PointF(0.0f, 0.0f),
1560 gfx::PointF(
1561 plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1562 plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1565 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1566 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1569 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1570 // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1571 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1572 // drop its reference, usually the last one. This is similar to possible
1573 // plugin behavior described at the NOTE above Delete().
1574 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1576 if (!render_frame_)
1577 return;
1579 bool has_focus = PluginHasFocus();
1580 render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1582 // instance_interface_ may have been cleared in Delete() if the
1583 // PepperWebPluginImpl is destroyed.
1584 if (instance_interface_)
1585 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1588 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1589 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1590 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1591 container_->requestTouchEventType(
1592 raw_touch
1593 ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1594 : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1597 bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1598 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1599 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1602 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1603 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1604 return; // Already scheduled.
1605 base::ThreadTaskRunnerHandle::Get()->PostTask(
1606 FROM_HERE, base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1607 view_change_weak_ptr_factory_.GetWeakPtr()));
1610 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1611 // The bound callback that owns the weak pointer is still valid until after
1612 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1613 // invalidate them here.
1614 // NOTE: If we ever want to have more than one pending callback, it should
1615 // use a different factory, or we should have a different strategy here.
1616 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1617 SendDidChangeView();
1620 void PepperPluginInstanceImpl::SendDidChangeView() {
1621 // An asynchronous view update is scheduled. Skip sending this update.
1622 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1623 return;
1625 // Don't send DidChangeView to crashed plugins.
1626 if (module()->is_crashed())
1627 return;
1629 // During the first view update, initialize the throttler.
1630 if (!sent_initial_did_change_view_) {
1631 if (is_flash_plugin_ && RenderThread::Get()) {
1632 RenderThread::Get()->RecordAction(
1633 base::UserMetricsAction("Flash.PluginInstanceCreated"));
1634 RecordFlashSizeMetric(unobscured_rect_.width(),
1635 unobscured_rect_.height());
1638 if (throttler_) {
1639 throttler_->Initialize(render_frame_, plugin_url_.GetOrigin(),
1640 module()->name(), unobscured_rect_.size());
1644 ppapi::ViewData view_data = view_data_;
1646 // When plugin content is throttled, fake the page being offscreen. We cannot
1647 // send empty view data here, as some plugins rely on accurate view data.
1648 if (throttler_ && throttler_->IsThrottled()) {
1649 view_data.is_page_visible = false;
1650 view_data.clip_rect.point.x = 0;
1651 view_data.clip_rect.point.y = 0;
1652 view_data.clip_rect.size.width = 0;
1653 view_data.clip_rect.size.height = 0;
1656 if (sent_initial_did_change_view_ && last_sent_view_data_.Equals(view_data))
1657 return; // Nothing to update.
1659 sent_initial_did_change_view_ = true;
1660 last_sent_view_data_ = view_data;
1661 ScopedPPResource resource(
1662 ScopedPPResource::PassRef(),
1663 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data))
1664 ->GetReference());
1666 UpdateLayerTransform();
1668 if (bound_graphics_2d_platform_ &&
1669 (!view_data.is_page_visible ||
1670 PP_ToGfxRect(view_data.clip_rect).IsEmpty())) {
1671 bound_graphics_2d_platform_->ClearCache();
1674 // It's possible that Delete() has been called but the renderer hasn't
1675 // released its reference to this object yet.
1676 if (instance_interface_) {
1677 instance_interface_->DidChangeView(
1678 pp_instance(), resource, &view_data.rect, &view_data.clip_rect);
1682 void PepperPluginInstanceImpl::ReportGeometry() {
1683 // If this call was delayed, we may have transitioned back to fullscreen in
1684 // the mean time, so only report the geometry if we are actually in normal
1685 // mode.
1686 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1687 container_->reportGeometry();
1690 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1691 PP_PrintOutputFormat_Dev* format) {
1692 // Keep a reference on the stack. See NOTE above.
1693 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1694 if (!LoadPrintInterface())
1695 return false;
1696 uint32_t supported_formats =
1697 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1698 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1699 *format = PP_PRINTOUTPUTFORMAT_PDF;
1700 return true;
1702 return false;
1705 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1706 PP_PrintOutputFormat_Dev format;
1707 return GetPreferredPrintOutputFormat(&format);
1710 bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1711 DCHECK(plugin_print_interface_);
1712 if (!plugin_print_interface_)
1713 return false;
1714 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1717 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1718 // Keep a reference on the stack. See NOTE above.
1719 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1720 PP_PrintOutputFormat_Dev format;
1721 if (!GetPreferredPrintOutputFormat(&format)) {
1722 // PrintBegin should not have been called since SupportsPrintInterface
1723 // would have returned false;
1724 NOTREACHED();
1725 return 0;
1727 int num_pages = 0;
1728 PP_PrintSettings_Dev print_settings;
1729 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1730 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1731 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1732 print_settings.dpi = print_params.printerDPI;
1733 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1734 print_settings.grayscale = PP_FALSE;
1735 print_settings.print_scaling_option =
1736 static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1737 print_settings.format = format;
1738 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1739 if (!num_pages)
1740 return 0;
1741 current_print_settings_ = print_settings;
1742 canvas_.clear();
1743 ranges_.clear();
1744 return num_pages;
1747 void PepperPluginInstanceImpl::PrintPage(int page_number,
1748 blink::WebCanvas* canvas) {
1749 #if defined(ENABLE_PRINTING)
1750 DCHECK(plugin_print_interface_);
1751 PP_PrintPageNumberRange_Dev page_range;
1752 page_range.first_page_number = page_range.last_page_number = page_number;
1753 // The canvas only has a metafile on it for print preview.
1754 bool save_for_later =
1755 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1756 #if defined(OS_MACOSX)
1757 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1758 #endif // defined(OS_MACOSX)
1759 if (save_for_later) {
1760 ranges_.push_back(page_range);
1761 canvas_ = skia::SharePtr(canvas);
1762 } else {
1763 PrintPageHelper(&page_range, 1, canvas);
1765 #endif
1768 void PepperPluginInstanceImpl::PrintPageHelper(
1769 PP_PrintPageNumberRange_Dev* page_ranges,
1770 int num_ranges,
1771 blink::WebCanvas* canvas) {
1772 // Keep a reference on the stack. See NOTE above.
1773 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1774 DCHECK(plugin_print_interface_);
1775 if (!plugin_print_interface_)
1776 return;
1777 PP_Resource print_output = plugin_print_interface_->PrintPages(
1778 pp_instance(), page_ranges, num_ranges);
1779 if (!print_output)
1780 return;
1782 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1783 PrintPDFOutput(print_output, canvas);
1785 // Now we need to release the print output resource.
1786 PluginModule::GetCore()->ReleaseResource(print_output);
1789 void PepperPluginInstanceImpl::PrintEnd() {
1790 // Keep a reference on the stack. See NOTE above.
1791 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1792 if (!ranges_.empty())
1793 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1794 canvas_.clear();
1795 ranges_.clear();
1797 DCHECK(plugin_print_interface_);
1798 if (plugin_print_interface_)
1799 plugin_print_interface_->End(pp_instance());
1801 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1802 #if defined(OS_MACOSX)
1803 last_printed_page_ = NULL;
1804 #endif // defined(OS_MACOSX)
1807 bool PepperPluginInstanceImpl::GetPrintPresetOptionsFromDocument(
1808 blink::WebPrintPresetOptions* preset_options) {
1809 // Keep a reference on the stack. See NOTE above.
1810 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1811 if (!LoadPdfInterface())
1812 return false;
1814 PP_PdfPrintPresetOptions_Dev options;
1815 if (!plugin_pdf_interface_->GetPrintPresetOptionsFromDocument(pp_instance(),
1816 &options)) {
1817 return false;
1820 preset_options->isScalingDisabled = PP_ToBool(options.is_scaling_disabled);
1821 switch (options.duplex) {
1822 case PP_PRIVATEDUPLEXMODE_SIMPLEX:
1823 preset_options->duplexMode = blink::WebSimplex;
1824 break;
1825 case PP_PRIVATEDUPLEXMODE_SHORT_EDGE:
1826 preset_options->duplexMode = blink::WebShortEdge;
1827 break;
1828 case PP_PRIVATEDUPLEXMODE_LONG_EDGE:
1829 preset_options->duplexMode = blink::WebLongEdge;
1830 break;
1831 default:
1832 preset_options->duplexMode = blink::WebUnknownDuplexMode;
1833 break;
1835 preset_options->copies = options.copies;
1836 preset_options->isPageSizeUniform = PP_ToBool(options.is_page_size_uniform);
1837 preset_options->uniformPageSize =
1838 blink::WebSize(options.uniform_page_size.width,
1839 options.uniform_page_size.height);
1841 return true;
1844 bool PepperPluginInstanceImpl::CanRotateView() {
1845 if (!LoadPdfInterface() || module()->is_crashed())
1846 return false;
1848 return true;
1851 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1852 if (!LoadPdfInterface())
1853 return;
1854 PP_PrivatePageTransformType transform_type =
1855 type == WebPlugin::RotationType90Clockwise
1856 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1857 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1858 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1859 // NOTE: plugin instance may have been deleted.
1862 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1863 return fullscreen_container_ != NULL;
1866 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1867 return desired_fullscreen_state_;
1870 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1871 // Keep a reference on the stack. See NOTE above.
1872 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1874 // Check whether we are trying to switch to the state we're already going
1875 // to (i.e. if we're already switching to fullscreen but the fullscreen
1876 // container isn't ready yet, don't do anything more).
1877 if (fullscreen == IsFullscreenOrPending())
1878 return false;
1880 if (!render_frame_)
1881 return false;
1882 if (fullscreen && !render_frame_->render_view()
1883 ->renderer_preferences()
1884 .plugin_fullscreen_allowed)
1885 return false;
1887 // Check whether we are trying to switch while the state is in transition.
1888 // The 2nd request gets dropped while messing up the internal state, so
1889 // disallow this.
1890 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1891 return false;
1893 if (fullscreen && !IsProcessingUserGesture())
1894 return false;
1896 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1897 desired_fullscreen_state_ = fullscreen;
1899 if (fullscreen) {
1900 // Create the user gesture in case we're processing one that's pending.
1901 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1902 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1903 // so we will tweak plugin's attributes to support the expected behavior.
1904 KeepSizeAttributesBeforeFullscreen();
1905 SetSizeAttributesForFullscreen();
1906 container_->element().requestFullScreen();
1907 } else {
1908 container_->element().document().cancelFullScreen();
1910 return true;
1913 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1914 bool flash_fullscreen) {
1915 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1917 if (flash_fullscreen == flash_fullscreen_) {
1918 // Manually clear callback when fullscreen fails with mouselock pending.
1919 if (!flash_fullscreen && is_mouselock_pending)
1920 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1921 return;
1924 UpdateLayer(false);
1926 bool old_plugin_focus = PluginHasFocus();
1927 flash_fullscreen_ = flash_fullscreen;
1928 if (is_mouselock_pending && !IsMouseLocked()) {
1929 if (!IsProcessingUserGesture() &&
1930 !module_->permissions().HasPermission(
1931 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1932 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1933 } else {
1934 // Open a user gesture here so the Webkit user gesture checks will succeed
1935 // for out-of-process plugins.
1936 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1937 if (!LockMouse())
1938 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1942 if (PluginHasFocus() != old_plugin_focus)
1943 SendFocusChangeNotification();
1946 bool PepperPluginInstanceImpl::IsViewAccelerated() {
1947 if (!container_)
1948 return false;
1950 WebDocument document = container_->element().document();
1951 WebLocalFrame* frame = document.frame();
1952 if (!frame)
1953 return false;
1954 WebView* view = frame->view();
1955 if (!view)
1956 return false;
1958 return view->isAcceleratedCompositingActive();
1961 bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1962 blink::WebCanvas* canvas) {
1963 #if defined(ENABLE_PRINTING)
1964 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1965 if (enter.failed())
1966 return false;
1968 BufferAutoMapper mapper(enter.object());
1969 if (!mapper.data() || !mapper.size()) {
1970 NOTREACHED();
1971 return false;
1974 printing::PdfMetafileSkia* metafile =
1975 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1976 if (metafile)
1977 return metafile->InitFromData(mapper.data(), mapper.size());
1979 NOTREACHED();
1980 #endif // ENABLE_PRINTING
1981 return false;
1984 void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
1985 if (!container_)
1986 return;
1987 if (throttler_ && throttler_->IsHiddenForPlaceholder())
1988 return;
1990 gpu::Mailbox mailbox;
1991 uint32 sync_point = 0;
1992 if (bound_graphics_3d_.get()) {
1993 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
1994 DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
1996 bool want_3d_layer = !mailbox.IsZero();
1997 bool want_2d_layer = !!bound_graphics_2d_platform_;
1998 bool want_texture_layer = want_3d_layer || want_2d_layer;
1999 bool want_compositor_layer = !!bound_compositor_;
2001 if (!device_changed && (want_texture_layer == !!texture_layer_.get()) &&
2002 (want_3d_layer == layer_is_hardware_) &&
2003 (want_compositor_layer == !!compositor_layer_.get()) &&
2004 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
2005 UpdateLayerTransform();
2006 return;
2009 if (texture_layer_.get() || compositor_layer_.get()) {
2010 if (!layer_bound_to_fullscreen_)
2011 container_->setWebLayer(NULL);
2012 else if (fullscreen_container_)
2013 fullscreen_container_->SetLayer(NULL);
2014 web_layer_.reset();
2015 if (texture_layer_) {
2016 texture_layer_->ClearClient();
2017 texture_layer_ = NULL;
2019 compositor_layer_ = NULL;
2022 if (want_texture_layer) {
2023 bool opaque = false;
2024 if (want_3d_layer) {
2025 DCHECK(bound_graphics_3d_.get());
2026 texture_layer_ = cc::TextureLayer::CreateForMailbox(
2027 cc_blink::WebLayerImpl::LayerSettings(), NULL);
2028 opaque = bound_graphics_3d_->IsOpaque();
2029 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
2030 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
2031 } else {
2032 DCHECK(bound_graphics_2d_platform_);
2033 texture_layer_ = cc::TextureLayer::CreateForMailbox(
2034 cc_blink::WebLayerImpl::LayerSettings(), this);
2035 bound_graphics_2d_platform_->AttachedToNewLayer();
2036 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2037 texture_layer_->SetFlipped(false);
2040 // Ignore transparency in fullscreen, since that's what Flash always
2041 // wants to do, and that lets it not recreate a context if
2042 // wmode=transparent was specified.
2043 opaque = opaque || fullscreen_container_;
2044 texture_layer_->SetContentsOpaque(opaque);
2045 web_layer_.reset(new cc_blink::WebLayerImpl(texture_layer_));
2046 } else if (want_compositor_layer) {
2047 compositor_layer_ = bound_compositor_->layer();
2048 web_layer_.reset(new cc_blink::WebLayerImpl(compositor_layer_));
2051 if (web_layer_) {
2052 if (fullscreen_container_) {
2053 fullscreen_container_->SetLayer(web_layer_.get());
2054 } else {
2055 container_->setWebLayer(web_layer_.get());
2059 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2060 layer_is_hardware_ = want_3d_layer;
2061 UpdateLayerTransform();
2064 bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2065 cc::TextureMailbox* mailbox,
2066 scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2067 bool use_shared_memory) {
2068 if (!bound_graphics_2d_platform_)
2069 return false;
2070 return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2071 release_callback);
2074 void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2076 void PepperPluginInstanceImpl::OnThrottleStateChange() {
2077 SendDidChangeView();
2079 bool is_throttled = throttler_->IsThrottled();
2080 render_frame()->Send(new ViewHostMsg_PluginInstanceThrottleStateChange(
2081 module_->GetPluginChildId(), pp_instance_, is_throttled));
2084 void PepperPluginInstanceImpl::OnHiddenForPlaceholder(bool hidden) {
2085 if (hidden) {
2086 container_->setWebLayer(nullptr);
2087 } else {
2088 UpdateLayer(true /* device_changed */);
2092 void PepperPluginInstanceImpl::AddLatencyInfo(
2093 const std::vector<ui::LatencyInfo>& latency_info) {
2094 if (render_frame_ && render_frame_->GetRenderWidget()) {
2095 RenderWidgetCompositor* compositor =
2096 render_frame_->GetRenderWidget()->compositor();
2097 if (compositor) {
2098 for (size_t i = 0; i < latency_info.size(); i++) {
2099 scoped_ptr<cc::SwapPromise> swap_promise(
2100 new cc::LatencyInfoSwapPromise(latency_info[i]));
2101 compositor->QueueSwapPromise(swap_promise.Pass());
2107 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2108 DCHECK(live_plugin_objects_.find(plugin_object) ==
2109 live_plugin_objects_.end());
2110 live_plugin_objects_.insert(plugin_object);
2113 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2114 // Don't actually verify that the object is in the set since during module
2115 // deletion we'll be in the process of freeing them.
2116 live_plugin_objects_.erase(plugin_object);
2119 bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2120 PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2121 // Give a lot of slack so tests won't be flaky.
2122 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2123 return pending_user_gesture_token_.hasGestures() &&
2124 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2127 WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2128 if (!IsProcessingUserGesture())
2129 pending_user_gesture_token_ = WebUserGestureToken();
2130 return pending_user_gesture_token_;
2133 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2134 if (TrackedCallback::IsPending(lock_mouse_callback_))
2135 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2138 void PepperPluginInstanceImpl::OnMouseLockLost() {
2139 if (LoadMouseLockInterface())
2140 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2143 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2144 const blink::WebMouseEvent& event) {
2145 // |cursor_info| is ignored since it is hidden when the mouse is locked.
2146 blink::WebCursorInfo cursor_info;
2147 HandleInputEvent(event, &cursor_info);
2150 void PepperPluginInstanceImpl::SimulateInputEvent(
2151 const InputEventData& input_event) {
2152 WebView* web_view = container()->element().document().frame()->view();
2153 if (!web_view) {
2154 NOTREACHED();
2155 return;
2158 bool handled = SimulateIMEEvent(input_event);
2159 if (handled)
2160 return;
2162 std::vector<linked_ptr<WebInputEvent> > events =
2163 CreateSimulatedWebInputEvents(
2164 input_event,
2165 view_data_.rect.point.x + view_data_.rect.size.width / 2,
2166 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2167 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2168 it != events.end();
2169 ++it) {
2170 web_view->handleInputEvent(*it->get());
2174 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2175 const InputEventData& input_event) {
2176 switch (input_event.event_type) {
2177 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2178 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2179 SimulateImeSetCompositionEvent(input_event);
2180 break;
2181 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2182 DCHECK(input_event.character_text.empty());
2183 SimulateImeSetCompositionEvent(input_event);
2184 break;
2185 case PP_INPUTEVENT_TYPE_IME_TEXT:
2186 if (!render_frame_)
2187 return false;
2188 render_frame_->SimulateImeConfirmComposition(
2189 base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2190 break;
2191 default:
2192 return false;
2194 return true;
2197 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2198 const InputEventData& input_event) {
2199 if (!render_frame_)
2200 return;
2202 std::vector<size_t> offsets;
2203 offsets.push_back(input_event.composition_selection_start);
2204 offsets.push_back(input_event.composition_selection_end);
2205 offsets.insert(offsets.end(),
2206 input_event.composition_segment_offsets.begin(),
2207 input_event.composition_segment_offsets.end());
2209 base::string16 utf16_text =
2210 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2212 std::vector<blink::WebCompositionUnderline> underlines;
2213 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2214 blink::WebCompositionUnderline underline;
2215 underline.startOffset = offsets[i];
2216 underline.endOffset = offsets[i + 1];
2217 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2218 underline.thick = true;
2219 underlines.push_back(underline);
2222 render_frame_->SimulateImeSetComposition(
2223 utf16_text, underlines, offsets[0], offsets[1]);
2226 ContentDecryptorDelegate*
2227 PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2228 if (content_decryptor_delegate_)
2229 return content_decryptor_delegate_.get();
2231 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2232 static_cast<const PPP_ContentDecryptor_Private*>(
2233 module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2234 if (!plugin_decryption_interface)
2235 return NULL;
2237 content_decryptor_delegate_.reset(
2238 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2239 return content_decryptor_delegate_.get();
2242 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2243 PP_Resource device) {
2244 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2245 // The Graphics3D instance can't be destroyed until we call
2246 // UpdateLayer().
2247 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2248 if (bound_graphics_3d_.get()) {
2249 bound_graphics_3d_->BindToInstance(false);
2250 bound_graphics_3d_ = NULL;
2252 if (bound_graphics_2d_platform_) {
2253 bound_graphics_2d_platform_->BindToInstance(NULL);
2254 bound_graphics_2d_platform_ = NULL;
2256 if (bound_compositor_) {
2257 bound_compositor_->BindToInstance(NULL);
2258 bound_compositor_ = NULL;
2261 // Special-case clearing the current device.
2262 if (!device) {
2263 UpdateLayer(true);
2264 InvalidateRect(gfx::Rect());
2265 return PP_TRUE;
2268 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2269 // to/from fullscreen with PPB_Fullscreen.
2270 if ((fullscreen_container_ && !flash_fullscreen_) ||
2271 desired_fullscreen_state_ != view_data_.is_fullscreen)
2272 return PP_FALSE;
2274 const ppapi::host::PpapiHost* ppapi_host =
2275 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2276 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2277 PepperGraphics2DHost* graphics_2d = NULL;
2278 PepperCompositorHost* compositor = NULL;
2279 if (host) {
2280 if (host->IsGraphics2DHost()) {
2281 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2282 } else if (host->IsCompositorHost()) {
2283 compositor = static_cast<PepperCompositorHost*>(host);
2284 } else {
2285 DLOG(ERROR) <<
2286 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2290 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2291 PPB_Graphics3D_Impl* graphics_3d =
2292 enter_3d.succeeded()
2293 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2294 : NULL;
2296 if (compositor) {
2297 if (compositor->BindToInstance(this)) {
2298 bound_compositor_ = compositor;
2299 UpdateLayer(true);
2300 return PP_TRUE;
2302 } else if (graphics_2d) {
2303 if (graphics_2d->BindToInstance(this)) {
2304 bound_graphics_2d_platform_ = graphics_2d;
2305 UpdateLayer(true);
2306 return PP_TRUE;
2308 } else if (graphics_3d) {
2309 // Make sure graphics can only be bound to the instance it is
2310 // associated with.
2311 if (graphics_3d->pp_instance() == pp_instance() &&
2312 graphics_3d->BindToInstance(true)) {
2313 bound_graphics_3d_ = graphics_3d;
2314 UpdateLayer(true);
2315 return PP_TRUE;
2319 // The instance cannot be bound or the device is not a valid resource type.
2320 return PP_FALSE;
2323 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2324 return PP_FromBool(full_frame());
2327 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2328 return &view_data_;
2331 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2332 return PP_FromBool(flash_fullscreen_);
2335 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2336 if (!container_)
2337 return PP_MakeUndefined();
2338 RecordFlashJavaScriptUse();
2339 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2340 PepperTryCatchVar try_catch(this, &converter, NULL);
2341 WebLocalFrame* frame = container_->element().document().frame();
2342 if (!frame) {
2343 try_catch.SetException("No frame exists for window object.");
2344 return PP_MakeUndefined();
2347 ScopedPPVar result =
2348 try_catch.FromV8(frame->mainWorldScriptContext()->Global());
2349 DCHECK(!try_catch.HasException());
2350 return result.Release();
2353 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2354 if (!container_)
2355 return PP_MakeUndefined();
2356 RecordFlashJavaScriptUse();
2357 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2358 PepperTryCatchVar try_catch(this, &converter, NULL);
2359 ScopedPPVar result = try_catch.FromV8(container_->v8ObjectForElement());
2360 DCHECK(!try_catch.HasException());
2361 return result.Release();
2364 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2365 PP_Var script_var,
2366 PP_Var* exception) {
2367 if (!container_)
2368 return PP_MakeUndefined();
2369 if (is_deleted_ && blink::WebPluginScriptForbiddenScope::isForbidden())
2370 return PP_MakeUndefined();
2371 RecordFlashJavaScriptUse();
2373 // Executing the script may remove the plugin from the DOM, so we need to keep
2374 // a reference to ourselves so that we can still process the result after the
2375 // WebBindings::evaluate() below.
2376 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2377 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2378 PepperTryCatchVar try_catch(this, &converter, exception);
2380 // Check for an exception due to the context being destroyed.
2381 if (try_catch.HasException())
2382 return PP_MakeUndefined();
2384 WebLocalFrame* frame = container_->element().document().frame();
2385 if (!frame) {
2386 try_catch.SetException("No frame to execute script in.");
2387 return PP_MakeUndefined();
2390 StringVar* script_string_var = StringVar::FromPPVar(script_var);
2391 if (!script_string_var) {
2392 try_catch.SetException("Script param to ExecuteScript must be a string.");
2393 return PP_MakeUndefined();
2396 std::string script_string = script_string_var->value();
2397 blink::WebScriptSource script(
2398 blink::WebString::fromUTF8(script_string.c_str()));
2399 v8::Local<v8::Value> result;
2400 if (IsProcessingUserGesture()) {
2401 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2402 result = frame->executeScriptAndReturnValue(script);
2403 } else {
2404 result = frame->executeScriptAndReturnValue(script);
2407 ScopedPPVar var_result = try_catch.FromV8(result);
2408 if (try_catch.HasException())
2409 return PP_MakeUndefined();
2411 return var_result.Release();
2414 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2415 PP_Instance instance) {
2416 RenderThreadImpl* thread = RenderThreadImpl::current();
2417 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2420 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2421 PP_Instance instance) {
2422 RenderThreadImpl* thread = RenderThreadImpl::current();
2423 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2426 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2427 if (!render_frame_)
2428 return PP_MakeUndefined();
2429 return StringVar::StringToPPVar(
2430 render_frame_->render_view()->webkit_preferences().default_encoding);
2433 // These PPB_ContentDecryptor_Private calls are responses to
2434 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2435 // Therefore, |content_decryptor_delegate_| must have been initialized when
2436 // the following methods are called.
2437 void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2438 uint32 promise_id) {
2439 content_decryptor_delegate_->OnPromiseResolved(promise_id);
2442 void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2443 PP_Instance instance,
2444 uint32 promise_id,
2445 PP_Var session_id_var) {
2446 content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2447 session_id_var);
2450 void PepperPluginInstanceImpl::PromiseRejected(
2451 PP_Instance instance,
2452 uint32 promise_id,
2453 PP_CdmExceptionCode exception_code,
2454 uint32 system_code,
2455 PP_Var error_description_var) {
2456 content_decryptor_delegate_->OnPromiseRejected(
2457 promise_id, exception_code, system_code, error_description_var);
2460 void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2461 PP_Var session_id_var,
2462 PP_CdmMessageType message_type,
2463 PP_Var message_var,
2464 PP_Var legacy_destination_url) {
2465 content_decryptor_delegate_->OnSessionMessage(
2466 session_id_var, message_type, message_var, legacy_destination_url);
2469 void PepperPluginInstanceImpl::SessionKeysChange(
2470 PP_Instance instance,
2471 PP_Var session_id_var,
2472 PP_Bool has_additional_usable_key,
2473 uint32_t key_count,
2474 const struct PP_KeyInformation key_information[]) {
2475 content_decryptor_delegate_->OnSessionKeysChange(
2476 session_id_var, has_additional_usable_key, key_count, key_information);
2479 void PepperPluginInstanceImpl::SessionExpirationChange(
2480 PP_Instance instance,
2481 PP_Var session_id_var,
2482 PP_Time new_expiry_time) {
2483 content_decryptor_delegate_->OnSessionExpirationChange(session_id_var,
2484 new_expiry_time);
2487 void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2488 PP_Var session_id_var) {
2489 content_decryptor_delegate_->OnSessionClosed(session_id_var);
2492 void PepperPluginInstanceImpl::LegacySessionError(
2493 PP_Instance instance,
2494 PP_Var session_id_var,
2495 PP_CdmExceptionCode exception_code,
2496 uint32 system_code,
2497 PP_Var error_description_var) {
2498 content_decryptor_delegate_->OnLegacySessionError(
2499 session_id_var, exception_code, system_code, error_description_var);
2502 void PepperPluginInstanceImpl::DeliverBlock(
2503 PP_Instance instance,
2504 PP_Resource decrypted_block,
2505 const PP_DecryptedBlockInfo* block_info) {
2506 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2509 void PepperPluginInstanceImpl::DecoderInitializeDone(
2510 PP_Instance instance,
2511 PP_DecryptorStreamType decoder_type,
2512 uint32_t request_id,
2513 PP_Bool success) {
2514 content_decryptor_delegate_->DecoderInitializeDone(
2515 decoder_type, request_id, success);
2518 void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2519 PP_Instance instance,
2520 PP_DecryptorStreamType decoder_type,
2521 uint32_t request_id) {
2522 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2523 request_id);
2526 void PepperPluginInstanceImpl::DecoderResetDone(
2527 PP_Instance instance,
2528 PP_DecryptorStreamType decoder_type,
2529 uint32_t request_id) {
2530 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2533 void PepperPluginInstanceImpl::DeliverFrame(
2534 PP_Instance instance,
2535 PP_Resource decrypted_frame,
2536 const PP_DecryptedFrameInfo* frame_info) {
2537 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2540 void PepperPluginInstanceImpl::DeliverSamples(
2541 PP_Instance instance,
2542 PP_Resource audio_frames,
2543 const PP_DecryptedSampleInfo* sample_info) {
2544 content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2547 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2548 PP_Instance instance) {
2549 if (!LoadFindInterface())
2550 return;
2551 bool is_main_frame =
2552 render_frame_ &&
2553 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2554 if (!is_main_frame)
2555 return;
2556 render_frame_->render_view()->set_plugin_find_handler(this);
2559 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2560 PP_Instance instance,
2561 int32_t total,
2562 PP_Bool final_result) {
2563 DCHECK_NE(find_identifier_, -1);
2564 if (render_frame_) {
2565 render_frame_->reportFindInPageMatchCount(
2566 find_identifier_, total, PP_ToBool(final_result));
2570 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2571 int32_t index) {
2572 DCHECK_NE(find_identifier_, -1);
2573 if (render_frame_) {
2574 render_frame_->reportFindInPageSelection(
2575 find_identifier_, index + 1, blink::WebRect());
2579 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2580 const PP_Rect* tickmarks,
2581 uint32_t count) {
2582 if (!render_frame_ || !render_frame_->GetWebFrame())
2583 return;
2585 blink::WebVector<blink::WebRect> tickmarks_converted(
2586 static_cast<size_t>(count));
2587 for (uint32 i = 0; i < count; ++i) {
2588 tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2589 tickmarks[i].point.y,
2590 tickmarks[i].size.width,
2591 tickmarks[i].size.height);
2593 blink::WebFrame* frame = render_frame_->GetWebFrame();
2594 frame->setTickmarks(tickmarks_converted);
2597 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2598 return PP_FromBool(view_data_.is_fullscreen);
2601 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2602 PP_Bool fullscreen) {
2603 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2606 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2607 PP_Size* size) {
2608 if (flash_fullscreen_) {
2609 // Workaround for Flash rendering bug: Flash is assuming the fullscreen view
2610 // size will be equal to the physical screen size. However, the fullscreen
2611 // view is sized by the browser UI, and may not be the same size as the
2612 // screen or the desktop. Therefore, report the view size as the screen
2613 // size when in fullscreen mode. http://crbug.com/506016
2614 // TODO(miu): Remove this workaround once Flash has been fixed.
2615 *size = view_data_.rect.size;
2616 } else {
2617 // All other cases: Report the screen size.
2618 blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2619 *size = PP_MakeSize(info.rect.width, info.rect.height);
2621 return PP_TRUE;
2624 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2625 PP_Instance instance,
2626 ppapi::SingletonResourceID id) {
2627 // Flash APIs and some others aren't implemented in-process.
2628 switch (id) {
2629 case ppapi::BROKER_SINGLETON_ID:
2630 case ppapi::BROWSER_FONT_SINGLETON_ID:
2631 case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2632 case ppapi::FLASH_FILE_SINGLETON_ID:
2633 case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2634 case ppapi::FLASH_SINGLETON_ID:
2635 case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2636 case ppapi::NETWORK_PROXY_SINGLETON_ID:
2637 case ppapi::PDF_SINGLETON_ID:
2638 case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2639 NOTIMPLEMENTED();
2640 return NULL;
2641 case ppapi::GAMEPAD_SINGLETON_ID:
2642 return gamepad_impl_.get();
2643 case ppapi::UMA_SINGLETON_ID: {
2644 if (!uma_private_impl_.get()) {
2645 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2646 if (host_impl->in_process_router()) {
2647 uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2648 host_impl->in_process_router()->GetPluginConnection(instance),
2649 instance);
2652 return uma_private_impl_.get();
2656 NOTREACHED();
2657 return NULL;
2660 int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2661 uint32_t event_classes) {
2662 input_event_mask_ |= event_classes;
2663 filtered_input_event_mask_ &= ~(event_classes);
2664 RequestInputEventsHelper(event_classes);
2665 return ValidateRequestInputEvents(false, event_classes);
2668 int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2669 PP_Instance instance,
2670 uint32_t event_classes) {
2671 filtered_input_event_mask_ |= event_classes;
2672 input_event_mask_ &= ~(event_classes);
2673 RequestInputEventsHelper(event_classes);
2674 return ValidateRequestInputEvents(true, event_classes);
2677 void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2678 uint32_t event_classes) {
2679 input_event_mask_ &= ~(event_classes);
2680 filtered_input_event_mask_ &= ~(event_classes);
2681 RequestInputEventsHelper(event_classes);
2684 void PepperPluginInstanceImpl::StartTrackingLatency(PP_Instance instance) {
2685 if (module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
2686 is_tracking_latency_ = true;
2689 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2690 PP_Var message) {
2691 PostMessageToJavaScript(message);
2694 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2695 PP_MouseCursor_Type type,
2696 PP_Resource image,
2697 const PP_Point* hot_spot) {
2698 if (!ValidateSetCursorParams(type, image, hot_spot))
2699 return PP_FALSE;
2701 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2702 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2703 return PP_TRUE;
2706 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2707 if (enter.failed())
2708 return PP_FALSE;
2709 PPB_ImageData_Impl* image_data =
2710 static_cast<PPB_ImageData_Impl*>(enter.object());
2712 ImageDataAutoMapper auto_mapper(image_data);
2713 if (!auto_mapper.is_valid())
2714 return PP_FALSE;
2716 scoped_ptr<WebCursorInfo> custom_cursor(
2717 new WebCursorInfo(WebCursorInfo::TypeCustom));
2718 custom_cursor->hotSpot.x = hot_spot->x;
2719 custom_cursor->hotSpot.y = hot_spot->y;
2721 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2722 // Make a deep copy, so that the cursor remains valid even after the original
2723 // image data gets freed.
2724 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2725 return PP_FALSE;
2728 DoSetCursor(custom_cursor.release());
2729 return PP_TRUE;
2732 int32_t PepperPluginInstanceImpl::LockMouse(
2733 PP_Instance instance,
2734 scoped_refptr<TrackedCallback> callback) {
2735 if (TrackedCallback::IsPending(lock_mouse_callback_))
2736 return PP_ERROR_INPROGRESS;
2738 if (IsMouseLocked())
2739 return PP_OK;
2741 if (!CanAccessMainFrame())
2742 return PP_ERROR_NOACCESS;
2744 if (!IsProcessingUserGesture())
2745 return PP_ERROR_NO_USER_GESTURE;
2747 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2748 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2749 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2750 // Open a user gesture here so the Webkit user gesture checks will succeed
2751 // for out-of-process plugins.
2752 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2753 if (!LockMouse())
2754 return PP_ERROR_FAILED;
2757 // Either mouselock succeeded or a Flash fullscreen is pending.
2758 lock_mouse_callback_ = callback;
2759 return PP_OK_COMPLETIONPENDING;
2762 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2763 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2766 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2767 PP_TextInput_Type type) {
2768 if (!render_frame_)
2769 return;
2770 int itype = type;
2771 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2772 itype = ui::TEXT_INPUT_TYPE_NONE;
2773 SetTextInputType(static_cast<ui::TextInputType>(itype));
2776 void PepperPluginInstanceImpl::UpdateCaretPosition(
2777 PP_Instance instance,
2778 const PP_Rect& caret,
2779 const PP_Rect& bounding_box) {
2780 if (!render_frame_)
2781 return;
2782 text_input_caret_ = PP_ToGfxRect(caret);
2783 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2784 text_input_caret_set_ = true;
2785 render_frame_->PepperCaretPositionChanged(this);
2788 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2789 if (render_frame_)
2790 render_frame_->PepperCancelComposition(this);
2793 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2794 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2795 // It can be optimized so that it won't call it back until the information
2796 // is really needed.
2798 // Avoid calling in nested context or else this will reenter the plugin. This
2799 // uses a weak pointer rather than exploiting the fact that this class is
2800 // refcounted because we don't actually want this operation to affect the
2801 // lifetime of the instance.
2802 base::ThreadTaskRunnerHandle::Get()->PostTask(
2803 FROM_HERE, base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2804 weak_factory_.GetWeakPtr(),
2805 static_cast<size_t>(kExtraCharsForTextInput)));
2808 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2809 const char* text,
2810 uint32_t caret,
2811 uint32_t anchor) {
2812 if (!render_frame_)
2813 return;
2814 surrounding_text_ = text;
2815 selection_caret_ = caret;
2816 selection_anchor_ = anchor;
2817 render_frame_->PepperSelectionChanged(this);
2820 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2821 PP_Instance instance,
2822 PP_Var relative,
2823 PP_URLComponents_Dev* components) {
2824 StringVar* relative_string = StringVar::FromPPVar(relative);
2825 if (!relative_string)
2826 return PP_MakeNull();
2828 WebElement plugin_element = container()->element();
2829 GURL document_url = plugin_element.document().baseURL();
2830 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2831 document_url.Resolve(relative_string->value()), components);
2834 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2835 PP_Var url) {
2836 StringVar* url_string = StringVar::FromPPVar(url);
2837 if (!url_string)
2838 return PP_FALSE;
2840 blink::WebSecurityOrigin security_origin;
2841 if (!SecurityOriginForInstance(instance, &security_origin))
2842 return PP_FALSE;
2844 GURL gurl(url_string->value());
2845 if (!gurl.is_valid())
2846 return PP_FALSE;
2848 return PP_FromBool(security_origin.canRequest(gurl));
2851 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2852 PP_Instance instance,
2853 PP_Instance target) {
2854 blink::WebSecurityOrigin our_origin;
2855 if (!SecurityOriginForInstance(instance, &our_origin))
2856 return PP_FALSE;
2858 blink::WebSecurityOrigin target_origin;
2859 if (!SecurityOriginForInstance(instance, &target_origin))
2860 return PP_FALSE;
2862 return PP_FromBool(our_origin.canAccess(target_origin));
2865 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2866 PP_Instance instance,
2867 PP_URLComponents_Dev* components) {
2868 blink::WebDocument document = container()->element().document();
2869 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2870 components);
2873 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2874 PP_Instance instance,
2875 PP_URLComponents_Dev* components) {
2876 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2879 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2880 PP_Instance instance,
2881 PP_URLComponents_Dev* components) {
2882 blink::WebDocument document = container()->element().document();
2883 if (!full_frame_)
2884 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2885 components);
2886 WebLocalFrame* frame = document.frame();
2887 if (!frame)
2888 return PP_MakeUndefined();
2889 const WebURLRequest& request = frame->dataSource()->originalRequest();
2890 WebString referer = request.httpHeaderField("Referer");
2891 if (referer.isEmpty())
2892 return PP_MakeUndefined();
2893 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2894 components);
2897 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2898 scoped_refptr<PluginModule> module) {
2899 // Save the original module and switch over to the new one now that this
2900 // plugin is using the IPC-based proxy.
2901 original_module_ = module_;
2902 module_ = module;
2904 // For NaCl instances, remember the NaCl plugin instance interface, so we
2905 // can shut it down by calling its DidDestroy in our Delete() method.
2906 original_instance_interface_.reset(instance_interface_.release());
2908 base::Callback<const void*(const char*)> get_plugin_interface_func =
2909 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2910 PPP_Instance_Combined* ppp_instance_combined =
2911 PPP_Instance_Combined::Create(get_plugin_interface_func);
2912 if (!ppp_instance_combined) {
2913 // The proxy must support at least one usable PPP_Instance interface.
2914 // While this could be a failure to implement the interface in the NaCl
2915 // module, it is more likely that the NaCl process has crashed. Either
2916 // way, report that module initialization failed.
2917 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2920 instance_interface_.reset(ppp_instance_combined);
2921 // Clear all PPP interfaces we may have cached.
2922 plugin_find_interface_ = NULL;
2923 plugin_input_event_interface_ = NULL;
2924 checked_for_plugin_input_event_interface_ = false;
2925 plugin_mouse_lock_interface_ = NULL;
2926 plugin_pdf_interface_ = NULL;
2927 checked_for_plugin_pdf_interface_ = false;
2928 plugin_private_interface_ = NULL;
2929 plugin_textinput_interface_ = NULL;
2931 // Re-send the DidCreate event via the proxy.
2932 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2933 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2934 if (!instance_interface_->DidCreate(
2935 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2936 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2937 if (message_channel_)
2938 message_channel_->Start();
2940 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2941 // event. This way, SendDidChangeView will send the "current" view
2942 // immediately (before other events like HandleDocumentLoad).
2943 sent_initial_did_change_view_ = false;
2944 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2945 SendDidChangeView();
2947 DCHECK(external_document_load_);
2948 external_document_load_ = false;
2949 if (!external_document_response_.isNull()) {
2950 document_loader_ = NULL;
2951 // Pass the response to the new proxy.
2952 HandleDocumentLoad(external_document_response_);
2953 external_document_response_ = blink::WebURLResponse();
2954 // Replay any document load events we've received to the real loader.
2955 external_document_loader_->ReplayReceivedData(document_loader_);
2956 external_document_loader_.reset(NULL);
2959 return PP_EXTERNAL_PLUGIN_OK;
2962 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2963 DCHECK(module);
2964 return module == module_.get() || module == original_module_.get();
2967 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2968 return HostGlobals::Get()->GetInstance(instance_id);
2971 RenderView* PepperPluginInstanceImpl::GetRenderView() {
2972 return render_frame_ ? render_frame_->render_view() : NULL;
2975 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2976 return container_;
2979 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
2981 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
2982 return HostGlobals::Get()->GetVarTracker();
2985 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
2987 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
2988 return module_->path();
2991 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
2992 float scale) {
2993 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
2995 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
2996 return 0;
2998 scoped_refptr<PPB_ImageData_Impl> image_data(
2999 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
3000 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
3001 image_skia_rep.pixel_width(),
3002 image_skia_rep.pixel_height(),
3003 false)) {
3004 return 0;
3007 ImageDataAutoMapper mapper(image_data.get());
3008 if (!mapper.is_valid())
3009 return 0;
3011 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
3012 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
3013 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
3014 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
3016 return image_data->GetReference();
3019 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
3020 const base::FilePath& file_path,
3021 ppapi::PpapiPermissions permissions,
3022 const IPC::ChannelHandle& channel_handle,
3023 base::ProcessId plugin_pid,
3024 int plugin_child_id) {
3025 // Create a new module for each instance of the external plugin that is using
3026 // the IPC based out-of-process proxy. We can't use the existing module,
3027 // because it is configured for the in-process plugin, and we must keep it
3028 // that way to allow the page to create other instances.
3029 scoped_refptr<PluginModule> external_plugin_module(
3030 module_->CreateModuleForExternalPluginInstance());
3032 RendererPpapiHostImpl* renderer_ppapi_host =
3033 external_plugin_module->CreateOutOfProcessModule(render_frame_,
3034 file_path,
3035 permissions,
3036 channel_handle,
3037 plugin_pid,
3038 plugin_child_id,
3039 true);
3040 if (!renderer_ppapi_host) {
3041 DLOG(ERROR) << "CreateExternalPluginModule() failed";
3042 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
3045 // Finally, switch the instance to the proxy.
3046 return external_plugin_module->InitAsProxiedExternalPlugin(this);
3049 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3050 always_on_top_ = on_top;
3053 void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
3054 cursor_.reset(cursor);
3055 if (fullscreen_container_) {
3056 fullscreen_container_->DidChangeCursor(*cursor);
3057 } else if (render_frame_) {
3058 render_frame_->PepperDidChangeCursor(this, *cursor);
3062 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3063 WebLocalFrame* frame = container()->element().document().frame();
3064 return frame->view()->mainFrame()->document().isPluginDocument();
3067 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3068 bool delay_report) {
3069 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3070 // Keep a reference on the stack. See NOTE above.
3071 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3073 // We check whether we are trying to switch to the state we're already going
3074 // to (i.e. if we're already switching to fullscreen but the fullscreen
3075 // container isn't ready yet, don't do anything more).
3076 if (fullscreen == FlashIsFullscreenOrPending())
3077 return true;
3079 if (!render_frame_)
3080 return false;
3081 if (fullscreen && !render_frame_->render_view()
3082 ->renderer_preferences()
3083 .plugin_fullscreen_allowed)
3084 return false;
3086 // Unbind current 2D or 3D graphics context.
3087 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3088 if (fullscreen) {
3089 DCHECK(!fullscreen_container_);
3090 fullscreen_container_ =
3091 render_frame_->CreatePepperFullscreenContainer(this);
3092 UpdateLayer(false);
3093 } else {
3094 DCHECK(fullscreen_container_);
3095 fullscreen_container_->Destroy();
3096 fullscreen_container_ = NULL;
3097 UpdateFlashFullscreenState(false);
3098 if (!delay_report) {
3099 ReportGeometry();
3100 } else {
3101 base::ThreadTaskRunnerHandle::Get()->PostTask(
3102 FROM_HERE,
3103 base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3107 return true;
3110 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3111 if (flash_fullscreen_)
3112 return true;
3114 return container_->isRectTopmost(rect);
3117 int32_t PepperPluginInstanceImpl::Navigate(
3118 const ppapi::URLRequestInfoData& request,
3119 const char* target,
3120 bool from_user_action) {
3121 if (!container_)
3122 return PP_ERROR_FAILED;
3124 WebDocument document = container_->element().document();
3125 WebLocalFrame* frame = document.frame();
3126 if (!frame)
3127 return PP_ERROR_FAILED;
3129 ppapi::URLRequestInfoData completed_request = request;
3131 WebURLRequest web_request;
3132 if (!CreateWebURLRequest(
3133 pp_instance_, &completed_request, frame, &web_request)) {
3134 return PP_ERROR_FAILED;
3136 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3137 if (IsProcessingUserGesture())
3138 web_request.setHasUserGesture(true);
3140 GURL gurl(web_request.url());
3141 if (gurl.SchemeIs(url::kJavaScriptScheme)) {
3142 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3143 // allowed for security reasons.
3144 WebFrame* target_frame =
3145 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3146 if (target_frame != frame)
3147 return PP_ERROR_NOACCESS;
3149 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3150 // need that?
3151 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
3152 WebString result = container_->executeScriptURL(gurl, false);
3153 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3156 // Only GETs and POSTs are supported.
3157 if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3158 return PP_ERROR_BADARGUMENT;
3160 WebString target_str = WebString::fromUTF8(target);
3161 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
3162 container_->loadFrameRequest(web_request, target_str, false, NULL);
3163 return PP_OK;
3166 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3167 const base::FilePath& path) {
3168 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3169 PepperFileRefRendererHost* file_ref_host(
3170 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3171 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3172 scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3175 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3176 if (message_channel_)
3177 message_channel_->SetReadOnlyProperty(key, value);
3180 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3181 if (!container_)
3182 return false;
3183 blink::WebDocument containing_document = container_->element().document();
3185 if (!containing_document.frame() || !containing_document.frame()->view() ||
3186 !containing_document.frame()->view()->mainFrame()) {
3187 return false;
3189 blink::WebDocument main_document =
3190 containing_document.frame()->view()->mainFrame()->document();
3192 return containing_document.securityOrigin().canAccess(
3193 main_document.securityOrigin());
3196 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3197 WebElement element = container_->element();
3198 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3199 height_before_fullscreen_ =
3200 element.getAttribute(WebString::fromUTF8(kHeight));
3201 border_before_fullscreen_ =
3202 element.getAttribute(WebString::fromUTF8(kBorder));
3203 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3206 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3207 if (!render_frame_)
3208 return;
3210 // TODO(miu): Revisit this logic. If the style must be modified for correct
3211 // behavior, the width and height should probably be set to 100%, rather than
3212 // a fixed screen size.
3214 blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3215 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3216 std::string width = base::IntToString(screen_size_for_fullscreen_.width());
3217 std::string height = base::IntToString(screen_size_for_fullscreen_.height());
3219 WebElement element = container_->element();
3220 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3221 element.setAttribute(WebString::fromUTF8(kHeight),
3222 WebString::fromUTF8(height));
3223 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3225 // There should be no style settings that matter in fullscreen mode,
3226 // so just replace them instead of appending.
3227 // NOTE: "position: fixed" and "display: block" reset the plugin and
3228 // using %% settings might not work without them (e.g. if the plugin is a
3229 // child of a container element).
3230 std::string style;
3231 style += StringPrintf("width: %s !important; ", width.c_str());
3232 style += StringPrintf("height: %s !important; ", height.c_str());
3233 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3234 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3237 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3238 screen_size_for_fullscreen_ = gfx::Size();
3239 WebElement element = container_->element();
3240 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3241 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3242 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3243 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3246 bool PepperPluginInstanceImpl::IsMouseLocked() {
3247 return GetMouseLockDispatcher()->IsMouseLockedTo(
3248 GetOrCreateLockTargetAdapter());
3251 bool PepperPluginInstanceImpl::LockMouse() {
3252 return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3255 MouseLockDispatcher::LockTarget*
3256 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3257 if (!lock_target_.get()) {
3258 lock_target_.reset(new PluginInstanceLockTarget(this));
3260 return lock_target_.get();
3263 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3264 if (flash_fullscreen_) {
3265 RenderWidgetFullscreenPepper* container =
3266 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3267 return container->mouse_lock_dispatcher();
3268 } else if (render_frame_) {
3269 return render_frame_->render_view()->mouse_lock_dispatcher();
3271 return NULL;
3274 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3275 if (lock_target_.get()) {
3276 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3277 lock_target_.reset();
3281 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3282 const blink::WebURLResponse& response,
3283 int pending_host_id,
3284 const ppapi::URLResponseInfoData& data) {
3285 if (is_deleted_)
3286 return;
3288 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3290 if (host_impl->in_process_router()) {
3291 // Running in-process, we can just create the resource and call the
3292 // PPP_Instance function directly.
3293 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3294 new ppapi::proxy::URLLoaderResource(
3295 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3296 pp_instance(),
3297 pending_host_id,
3298 data));
3300 PP_Resource loader_pp_resource = loader_resource->GetReference();
3301 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3302 loader_pp_resource))
3303 loader_resource->Close();
3304 // We don't pass a ref into the plugin, if it wants one, it will have taken
3305 // an additional one.
3306 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3307 loader_pp_resource);
3308 } else {
3309 // Running out-of-process. Initiate an IPC call to notify the plugin
3310 // process.
3311 ppapi::proxy::HostDispatcher* dispatcher =
3312 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3313 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3314 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3318 void PepperPluginInstanceImpl::RecordFlashJavaScriptUse() {
3319 if (initialized_ && !javascript_used_ && is_flash_plugin_) {
3320 javascript_used_ = true;
3321 RenderThread::Get()->RecordAction(
3322 base::UserMetricsAction("Flash.JavaScriptUsed"));
3326 } // namespace content