cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / renderer / pepper / pepper_plugin_instance_impl.cc
blobe22101ba7c5f8660dd9d5d8a401b6c1139100266
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/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "base/memory/linked_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/stl_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/strings/utf_offset_string_conversions.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "cc/base/latency_info_swap_promise.h"
20 #include "cc/blink/web_layer_impl.h"
21 #include "cc/layers/texture_layer.h"
22 #include "cc/trees/layer_tree_host.h"
23 #include "content/common/content_constants_internal.h"
24 #include "content/common/input/web_input_event_traits.h"
25 #include "content/public/common/content_constants.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/page_zoom.h"
28 #include "content/public/renderer/content_renderer_client.h"
29 #include "content/renderer/gpu/render_widget_compositor.h"
30 #include "content/renderer/pepper/content_decryptor_delegate.h"
31 #include "content/renderer/pepper/event_conversion.h"
32 #include "content/renderer/pepper/fullscreen_container.h"
33 #include "content/renderer/pepper/gfx_conversion.h"
34 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
35 #include "content/renderer/pepper/host_globals.h"
36 #include "content/renderer/pepper/message_channel.h"
37 #include "content/renderer/pepper/pepper_browser_connection.h"
38 #include "content/renderer/pepper/pepper_compositor_host.h"
39 #include "content/renderer/pepper/pepper_file_ref_renderer_host.h"
40 #include "content/renderer/pepper/pepper_graphics_2d_host.h"
41 #include "content/renderer/pepper/pepper_in_process_router.h"
42 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
43 #include "content/renderer/pepper/pepper_plugin_instance_throttler.h"
44 #include "content/renderer/pepper/pepper_try_catch.h"
45 #include "content/renderer/pepper/pepper_url_loader_host.h"
46 #include "content/renderer/pepper/plugin_module.h"
47 #include "content/renderer/pepper/plugin_object.h"
48 #include "content/renderer/pepper/ppapi_preferences_builder.h"
49 #include "content/renderer/pepper/ppb_buffer_impl.h"
50 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
51 #include "content/renderer/pepper/ppb_image_data_impl.h"
52 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
53 #include "content/renderer/pepper/url_request_info_util.h"
54 #include "content/renderer/pepper/url_response_info_util.h"
55 #include "content/renderer/render_frame_impl.h"
56 #include "content/renderer/render_thread_impl.h"
57 #include "content/renderer/render_view_impl.h"
58 #include "content/renderer/render_widget.h"
59 #include "content/renderer/render_widget_fullscreen_pepper.h"
60 #include "content/renderer/sad_plugin.h"
61 #include "media/base/audio_hardware_config.h"
62 #include "ppapi/c/dev/ppb_zoom_dev.h"
63 #include "ppapi/c/dev/ppp_selection_dev.h"
64 #include "ppapi/c/dev/ppp_text_input_dev.h"
65 #include "ppapi/c/dev/ppp_zoom_dev.h"
66 #include "ppapi/c/pp_rect.h"
67 #include "ppapi/c/ppb_audio_config.h"
68 #include "ppapi/c/ppb_core.h"
69 #include "ppapi/c/ppb_gamepad.h"
70 #include "ppapi/c/ppp_input_event.h"
71 #include "ppapi/c/ppp_instance.h"
72 #include "ppapi/c/ppp_messaging.h"
73 #include "ppapi/c/ppp_mouse_lock.h"
74 #include "ppapi/c/private/ppb_find_private.h"
75 #include "ppapi/c/private/ppp_find_private.h"
76 #include "ppapi/c/private/ppp_instance_private.h"
77 #include "ppapi/c/private/ppp_pdf.h"
78 #include "ppapi/host/ppapi_host.h"
79 #include "ppapi/proxy/ppapi_messages.h"
80 #include "ppapi/proxy/serialized_var.h"
81 #include "ppapi/proxy/uma_private_resource.h"
82 #include "ppapi/proxy/url_loader_resource.h"
83 #include "ppapi/shared_impl/ppapi_permissions.h"
84 #include "ppapi/shared_impl/ppapi_preferences.h"
85 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
86 #include "ppapi/shared_impl/ppb_input_event_shared.h"
87 #include "ppapi/shared_impl/ppb_url_util_shared.h"
88 #include "ppapi/shared_impl/ppb_view_shared.h"
89 #include "ppapi/shared_impl/ppp_instance_combined.h"
90 #include "ppapi/shared_impl/resource.h"
91 #include "ppapi/shared_impl/scoped_pp_resource.h"
92 #include "ppapi/shared_impl/scoped_pp_var.h"
93 #include "ppapi/shared_impl/time_conversion.h"
94 #include "ppapi/shared_impl/url_request_info_data.h"
95 #include "ppapi/shared_impl/var.h"
96 #include "ppapi/thunk/enter.h"
97 #include "ppapi/thunk/ppb_buffer_api.h"
98 #include "printing/metafile_skia_wrapper.h"
99 #include "printing/pdf_metafile_skia.h"
100 #include "skia/ext/platform_canvas.h"
101 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
102 #include "third_party/WebKit/public/platform/WebGamepads.h"
103 #include "third_party/WebKit/public/platform/WebRect.h"
104 #include "third_party/WebKit/public/platform/WebString.h"
105 #include "third_party/WebKit/public/platform/WebURL.h"
106 #include "third_party/WebKit/public/platform/WebURLError.h"
107 #include "third_party/WebKit/public/platform/WebURLRequest.h"
108 #include "third_party/WebKit/public/web/WebBindings.h"
109 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
110 #include "third_party/WebKit/public/web/WebDataSource.h"
111 #include "third_party/WebKit/public/web/WebDocument.h"
112 #include "third_party/WebKit/public/web/WebElement.h"
113 #include "third_party/WebKit/public/web/WebInputEvent.h"
114 #include "third_party/WebKit/public/web/WebLocalFrame.h"
115 #include "third_party/WebKit/public/web/WebPluginContainer.h"
116 #include "third_party/WebKit/public/web/WebPrintParams.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 #if defined(OS_WIN)
134 #include "base/metrics/histogram.h"
135 #include "base/win/windows_version.h"
136 #include "skia/ext/platform_canvas.h"
137 #endif
139 using base::StringPrintf;
140 using ppapi::InputEventData;
141 using ppapi::PpapiGlobals;
142 using ppapi::PPB_InputEvent_Shared;
143 using ppapi::PPB_View_Shared;
144 using ppapi::PPP_Instance_Combined;
145 using ppapi::Resource;
146 using ppapi::ScopedPPResource;
147 using ppapi::ScopedPPVar;
148 using ppapi::StringVar;
149 using ppapi::TrackedCallback;
150 using ppapi::thunk::EnterResourceNoLock;
151 using ppapi::thunk::PPB_Buffer_API;
152 using ppapi::thunk::PPB_Gamepad_API;
153 using ppapi::thunk::PPB_Graphics2D_API;
154 using ppapi::thunk::PPB_Graphics3D_API;
155 using ppapi::thunk::PPB_ImageData_API;
156 using ppapi::Var;
157 using ppapi::ArrayBufferVar;
158 using ppapi::ViewData;
159 using blink::WebBindings;
160 using blink::WebCanvas;
161 using blink::WebCursorInfo;
162 using blink::WebDocument;
163 using blink::WebElement;
164 using blink::WebFrame;
165 using blink::WebInputEvent;
166 using blink::WebLocalFrame;
167 using blink::WebPlugin;
168 using blink::WebPluginContainer;
169 using blink::WebPrintParams;
170 using blink::WebPrintScalingOption;
171 using blink::WebScopedUserGesture;
172 using blink::WebString;
173 using blink::WebURLError;
174 using blink::WebURLLoader;
175 using blink::WebURLLoaderClient;
176 using blink::WebURLRequest;
177 using blink::WebURLResponse;
178 using blink::WebUserGestureIndicator;
179 using blink::WebUserGestureToken;
180 using blink::WebView;
182 namespace content {
184 namespace {
186 // Check PP_TextInput_Type and ui::TextInputType are kept in sync.
187 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NONE) == int(PP_TEXTINPUT_TYPE_NONE),
188 mismatching_enums);
189 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TEXT) == int(PP_TEXTINPUT_TYPE_TEXT),
190 mismatching_enums);
191 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_PASSWORD) ==
192 int(PP_TEXTINPUT_TYPE_PASSWORD),
193 mismatching_enums);
194 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_SEARCH) == int(PP_TEXTINPUT_TYPE_SEARCH),
195 mismatching_enums);
196 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_EMAIL) == int(PP_TEXTINPUT_TYPE_EMAIL),
197 mismatching_enums);
198 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NUMBER) == int(PP_TEXTINPUT_TYPE_NUMBER),
199 mismatching_enums);
200 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TELEPHONE) ==
201 int(PP_TEXTINPUT_TYPE_TELEPHONE),
202 mismatching_enums);
203 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_URL) == int(PP_TEXTINPUT_TYPE_URL),
204 mismatching_enums);
206 // The default text input type is to regard the plugin always accept text input.
207 // This is for allowing users to use input methods even on completely-IME-
208 // unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
209 // Plugins need to explicitly opt out the text input mode if they know
210 // that they don't accept texts.
211 const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
213 #define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
214 COMPILE_ASSERT(static_cast<int>(WebCursorInfo::webkit_name) == \
215 static_cast<int>(np_name), \
216 mismatching_enums)
218 #define COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(webkit_name, pp_name) \
219 COMPILE_ASSERT(static_cast<int>(webkit_name) == static_cast<int>(pp_name), \
220 mismatching_enums)
222 // <embed>/<object> attributes.
223 const char kWidth[] = "width";
224 const char kHeight[] = "height";
225 const char kBorder[] = "border"; // According to w3c, deprecated.
226 const char kStyle[] = "style";
228 COMPILE_ASSERT_MATCHING_ENUM(TypePointer, PP_MOUSECURSOR_TYPE_POINTER);
229 COMPILE_ASSERT_MATCHING_ENUM(TypeCross, PP_MOUSECURSOR_TYPE_CROSS);
230 COMPILE_ASSERT_MATCHING_ENUM(TypeHand, PP_MOUSECURSOR_TYPE_HAND);
231 COMPILE_ASSERT_MATCHING_ENUM(TypeIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
232 COMPILE_ASSERT_MATCHING_ENUM(TypeWait, PP_MOUSECURSOR_TYPE_WAIT);
233 COMPILE_ASSERT_MATCHING_ENUM(TypeHelp, PP_MOUSECURSOR_TYPE_HELP);
234 COMPILE_ASSERT_MATCHING_ENUM(TypeEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
235 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
236 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastResize,
237 PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
238 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestResize,
239 PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
240 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
241 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastResize,
242 PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
243 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestResize,
244 PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
245 COMPILE_ASSERT_MATCHING_ENUM(TypeWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
246 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
247 PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
248 COMPILE_ASSERT_MATCHING_ENUM(TypeEastWestResize,
249 PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
250 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
251 PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
252 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
253 PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
254 COMPILE_ASSERT_MATCHING_ENUM(TypeColumnResize,
255 PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
256 COMPILE_ASSERT_MATCHING_ENUM(TypeRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
257 COMPILE_ASSERT_MATCHING_ENUM(TypeMiddlePanning,
258 PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
259 COMPILE_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
260 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthPanning,
261 PP_MOUSECURSOR_TYPE_NORTHPANNING);
262 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
263 PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
264 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
265 PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
266 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthPanning,
267 PP_MOUSECURSOR_TYPE_SOUTHPANNING);
268 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
269 PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
270 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
271 PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
272 COMPILE_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
273 COMPILE_ASSERT_MATCHING_ENUM(TypeMove, PP_MOUSECURSOR_TYPE_MOVE);
274 COMPILE_ASSERT_MATCHING_ENUM(TypeVerticalText,
275 PP_MOUSECURSOR_TYPE_VERTICALTEXT);
276 COMPILE_ASSERT_MATCHING_ENUM(TypeCell, PP_MOUSECURSOR_TYPE_CELL);
277 COMPILE_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
278 COMPILE_ASSERT_MATCHING_ENUM(TypeAlias, PP_MOUSECURSOR_TYPE_ALIAS);
279 COMPILE_ASSERT_MATCHING_ENUM(TypeProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
280 COMPILE_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
281 COMPILE_ASSERT_MATCHING_ENUM(TypeCopy, PP_MOUSECURSOR_TYPE_COPY);
282 COMPILE_ASSERT_MATCHING_ENUM(TypeNone, PP_MOUSECURSOR_TYPE_NONE);
283 COMPILE_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
284 COMPILE_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
285 COMPILE_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
286 COMPILE_ASSERT_MATCHING_ENUM(TypeGrab, PP_MOUSECURSOR_TYPE_GRAB);
287 COMPILE_ASSERT_MATCHING_ENUM(TypeGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
288 // Do not assert WebCursorInfo::TypeCustom == PP_CURSORTYPE_CUSTOM;
289 // PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
291 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(blink::WebPrintScalingOptionNone,
292 PP_PRINTSCALINGOPTION_NONE);
293 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
294 blink::WebPrintScalingOptionFitToPrintableArea,
295 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
296 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
297 blink::WebPrintScalingOptionSourceSize,
298 PP_PRINTSCALINGOPTION_SOURCE_SIZE);
300 // Sets |*security_origin| to be the WebKit security origin associated with the
301 // document containing the given plugin instance. On success, returns true. If
302 // the instance is invalid, returns false and |*security_origin| will be
303 // unchanged.
304 bool SecurityOriginForInstance(PP_Instance instance_id,
305 blink::WebSecurityOrigin* security_origin) {
306 PepperPluginInstanceImpl* instance =
307 HostGlobals::Get()->GetInstance(instance_id);
308 if (!instance)
309 return false;
311 WebElement plugin_element = instance->container()->element();
312 *security_origin = plugin_element.document().securityOrigin();
313 return true;
316 // Convert the given vector to an array of C-strings. The strings in the
317 // returned vector are only guaranteed valid so long as the vector of strings
318 // is not modified.
319 scoped_ptr<const char* []> StringVectorToArgArray(
320 const std::vector<std::string>& vector) {
321 scoped_ptr<const char * []> array(new const char* [vector.size()]);
322 for (size_t i = 0; i < vector.size(); ++i)
323 array[i] = vector[i].c_str();
324 return array.Pass();
327 // Returns true if this is a "system reserved" key which should not be sent to
328 // a plugin. Some poorly behaving plugins (like Flash) incorrectly report that
329 // they handle all keys sent to them. This can prevent keystrokes from working
330 // for things like screen brightness and volume control.
331 bool IsReservedSystemInputEvent(const blink::WebInputEvent& event) {
332 #if defined(OS_CHROMEOS)
333 if (event.type != WebInputEvent::KeyDown &&
334 event.type != WebInputEvent::KeyUp)
335 return false;
336 const blink::WebKeyboardEvent& key_event =
337 static_cast<const blink::WebKeyboardEvent&>(event);
338 switch (key_event.windowsKeyCode) {
339 case ui::VKEY_BRIGHTNESS_DOWN:
340 case ui::VKEY_BRIGHTNESS_UP:
341 case ui::VKEY_KBD_BRIGHTNESS_DOWN:
342 case ui::VKEY_KBD_BRIGHTNESS_UP:
343 case ui::VKEY_VOLUME_MUTE:
344 case ui::VKEY_VOLUME_DOWN:
345 case ui::VKEY_VOLUME_UP:
346 return true;
347 default:
348 return false;
350 #endif // defined(OS_CHROMEOS)
351 return false;
354 class PluginInstanceLockTarget : public MouseLockDispatcher::LockTarget {
355 public:
356 PluginInstanceLockTarget(PepperPluginInstanceImpl* plugin)
357 : plugin_(plugin) {}
359 void OnLockMouseACK(bool succeeded) override {
360 plugin_->OnLockMouseACK(succeeded);
363 void OnMouseLockLost() override { plugin_->OnMouseLockLost(); }
365 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
366 plugin_->HandleMouseLockedInputEvent(event);
367 return true;
370 private:
371 PepperPluginInstanceImpl* plugin_;
374 void InitLatencyInfo(ui::LatencyInfo* new_latency,
375 const ui::LatencyInfo* old_latency,
376 blink::WebInputEvent::Type type,
377 int64 input_sequence) {
378 new_latency->AddLatencyNumber(
379 ui::INPUT_EVENT_LATENCY_BEGIN_PLUGIN_COMPONENT,
381 input_sequence);
382 new_latency->TraceEventType(WebInputEventTraits::GetName(type));
383 if (old_latency) {
384 new_latency->CopyLatencyFrom(*old_latency,
385 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
386 new_latency->CopyLatencyFrom(*old_latency,
387 ui::INPUT_EVENT_LATENCY_UI_COMPONENT);
391 } // namespace
393 // static
394 PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
395 RenderFrameImpl* render_frame,
396 PluginModule* module,
397 WebPluginContainer* container,
398 const GURL& plugin_url) {
399 base::Callback<const void*(const char*)> get_plugin_interface_func =
400 base::Bind(&PluginModule::GetPluginInterface, module);
401 PPP_Instance_Combined* ppp_instance_combined =
402 PPP_Instance_Combined::Create(get_plugin_interface_func);
403 if (!ppp_instance_combined)
404 return NULL;
406 return new PepperPluginInstanceImpl(render_frame,
407 module,
408 ppp_instance_combined,
409 container,
410 plugin_url);
413 PepperPluginInstanceImpl::ExternalDocumentLoader::ExternalDocumentLoader()
414 : finished_loading_(false) {}
416 PepperPluginInstanceImpl::ExternalDocumentLoader::~ExternalDocumentLoader() {}
418 void PepperPluginInstanceImpl::ExternalDocumentLoader::ReplayReceivedData(
419 WebURLLoaderClient* document_loader) {
420 for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
421 ++it) {
422 document_loader->didReceiveData(
423 NULL, it->c_str(), it->length(), 0 /* encoded_data_length */);
425 if (finished_loading_) {
426 document_loader->didFinishLoading(
427 NULL,
428 0 /* finish_time */,
429 blink::WebURLLoaderClient::kUnknownEncodedDataLength);
431 if (error_.get()) {
432 document_loader->didFail(NULL, *error_);
436 void PepperPluginInstanceImpl::ExternalDocumentLoader::didReceiveData(
437 WebURLLoader* loader,
438 const char* data,
439 int data_length,
440 int encoded_data_length) {
441 data_.push_back(std::string(data, data_length));
444 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFinishLoading(
445 WebURLLoader* loader,
446 double finish_time,
447 int64_t total_encoded_data_length) {
448 DCHECK(!finished_loading_);
449 finished_loading_ = true;
452 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFail(
453 WebURLLoader* loader,
454 const WebURLError& error) {
455 DCHECK(!error_.get());
456 error_.reset(new WebURLError(error));
459 PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
460 : Resource(ppapi::Resource::Untracked()) {}
462 PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
464 PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
465 return this;
468 void PepperPluginInstanceImpl::GamepadImpl::Sample(
469 PP_Instance instance,
470 PP_GamepadsSampleData* data) {
471 blink::WebGamepads webkit_data;
472 RenderThreadImpl::current()->SampleGamepads(&webkit_data);
473 ConvertWebKitGamepadData(bit_cast<ppapi::WebKitGamepads>(webkit_data), data);
476 PepperPluginInstanceImpl::PepperPluginInstanceImpl(
477 RenderFrameImpl* render_frame,
478 PluginModule* module,
479 ppapi::PPP_Instance_Combined* instance_interface,
480 WebPluginContainer* container,
481 const GURL& plugin_url)
482 : RenderFrameObserver(render_frame),
483 render_frame_(render_frame),
484 module_(module),
485 instance_interface_(instance_interface),
486 pp_instance_(0),
487 container_(container),
488 layer_bound_to_fullscreen_(false),
489 layer_is_hardware_(false),
490 plugin_url_(plugin_url),
491 power_saver_enabled_(false),
492 plugin_throttled_(false),
493 full_frame_(false),
494 sent_initial_did_change_view_(false),
495 bound_graphics_2d_platform_(NULL),
496 bound_compositor_(NULL),
497 has_webkit_focus_(false),
498 has_content_area_focus_(false),
499 find_identifier_(-1),
500 plugin_find_interface_(NULL),
501 plugin_input_event_interface_(NULL),
502 plugin_mouse_lock_interface_(NULL),
503 plugin_pdf_interface_(NULL),
504 plugin_private_interface_(NULL),
505 plugin_textinput_interface_(NULL),
506 plugin_zoom_interface_(NULL),
507 checked_for_plugin_input_event_interface_(false),
508 checked_for_plugin_pdf_interface_(false),
509 gamepad_impl_(new GamepadImpl()),
510 uma_private_impl_(NULL),
511 plugin_print_interface_(NULL),
512 plugin_graphics_3d_interface_(NULL),
513 always_on_top_(false),
514 fullscreen_container_(NULL),
515 flash_fullscreen_(false),
516 desired_fullscreen_state_(false),
517 message_channel_(NULL),
518 sad_plugin_(NULL),
519 input_event_mask_(0),
520 filtered_input_event_mask_(0),
521 text_input_type_(kPluginDefaultTextInputType),
522 text_input_caret_(0, 0, 0, 0),
523 text_input_caret_bounds_(0, 0, 0, 0),
524 text_input_caret_set_(false),
525 selection_caret_(0),
526 selection_anchor_(0),
527 pending_user_gesture_(0.0),
528 document_loader_(NULL),
529 external_document_load_(false),
530 isolate_(v8::Isolate::GetCurrent()),
531 is_deleted_(false),
532 last_input_number_(0),
533 is_tracking_latency_(false),
534 view_change_weak_ptr_factory_(this),
535 weak_factory_(this) {
536 pp_instance_ = HostGlobals::Get()->AddInstance(this);
538 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
539 module_->InstanceCreated(this);
541 if (render_frame) { // NULL in tests
542 render_frame->render_view()->PepperInstanceCreated(this);
543 // Bind a callback now so that we can inform the RenderViewImpl when we are
544 // destroyed. This works around a temporary problem stemming from work to
545 // move parts of RenderViewImpl in to RenderFrameImpl (see
546 // crbug.com/245126). If destruction happens in this order:
547 // 1) RenderFrameImpl
548 // 2) PepperPluginInstanceImpl
549 // 3) RenderViewImpl
550 // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
551 // to the RenderViewImpl. But when the instance is destroyed, it still
552 // needs to inform the RenderViewImpl that it has gone away, otherwise
553 // between (2) and (3), the RenderViewImpl will still have the dead
554 // instance in its active set, and so might make calls on the deleted
555 // instance. See crbug.com/343576 for more information. Once the plugin
556 // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
557 // can be a little bit simplified by instead making a direct call on
558 // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
559 instance_deleted_callback_ =
560 base::Bind(&RenderViewImpl::PepperInstanceDeleted,
561 render_frame->render_view()->AsWeakPtr(),
562 base::Unretained(this));
563 view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
565 // Set the initial focus.
566 SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
568 if (!module_->IsProxied()) {
569 PepperBrowserConnection* browser_connection =
570 PepperBrowserConnection::Get(render_frame_);
571 browser_connection->DidCreateInProcessInstance(
572 pp_instance(),
573 render_frame_->GetRoutingID(),
574 container_->element().document().url(),
575 GetPluginURL());
579 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
580 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
582 if (GetContentClient()->renderer() && // NULL in unit tests.
583 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
584 external_document_load_ = true;
586 power_saver_enabled_ = CommandLine::ForCurrentProcess()->HasSwitch(
587 switches::kEnablePluginPowerSaver) &&
588 IsPeripheralContent();
590 if (power_saver_enabled_) {
591 throttler_.reset(new PepperPluginInstanceThrottler(
592 base::Bind(&PepperPluginInstanceImpl::SetPluginThrottled,
593 weak_factory_.GetWeakPtr(), true /* throttled */)));
597 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
598 DCHECK(!fullscreen_container_);
600 // Notify all the plugin objects of deletion. This will prevent blink from
601 // calling into the plugin any more.
603 // Swap out the set so we can delete from it (the objects will try to
604 // unregister themselves inside the delete call).
605 PluginObjectSet plugin_object_copy;
606 live_plugin_objects_.swap(plugin_object_copy);
607 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
608 i != plugin_object_copy.end();
609 ++i) {
610 (*i)->InstanceDeleted();
613 if (message_channel_)
614 message_channel_->InstanceDeleted();
615 message_channel_object_.Reset();
617 if (TrackedCallback::IsPending(lock_mouse_callback_))
618 lock_mouse_callback_->Abort();
620 if (!instance_deleted_callback_.is_null())
621 instance_deleted_callback_.Run();
623 if (!module_->IsProxied() && render_frame_) {
624 PepperBrowserConnection* browser_connection =
625 PepperBrowserConnection::Get(render_frame_);
626 browser_connection->DidDeleteInProcessInstance(pp_instance());
629 UnSetAndDeleteLockTargetAdapter();
630 module_->InstanceDeleted(this);
631 // If we switched from the NaCl plugin module, notify it too.
632 if (original_module_.get())
633 original_module_->InstanceDeleted(this);
635 // This should be last since some of the above "instance deleted" calls will
636 // want to look up in the global map to get info off of our object.
637 HostGlobals::Get()->InstanceDeleted(pp_instance_);
640 // NOTE: Any of these methods that calls into the plugin needs to take into
641 // account that the plugin may use Var to remove the <embed> from the DOM, which
642 // will make the PepperWebPluginImpl drop its reference, usually the last one.
643 // If a method needs to access a member of the instance after the call has
644 // returned, then it needs to keep its own reference on the stack.
646 v8::Local<v8::Object> PepperPluginInstanceImpl::GetMessageChannelObject() {
647 return v8::Local<v8::Object>::New(isolate_, message_channel_object_);
650 void PepperPluginInstanceImpl::MessageChannelDestroyed() {
651 message_channel_ = NULL;
652 message_channel_object_.Reset();
655 v8::Local<v8::Context> PepperPluginInstanceImpl::GetMainWorldContext() {
656 if (!container_)
657 return v8::Handle<v8::Context>();
659 if (container_->element().isNull())
660 return v8::Handle<v8::Context>();
662 if (container_->element().document().isNull())
663 return v8::Handle<v8::Context>();
665 if (!container_->element().document().frame())
666 return v8::Handle<v8::Context>();
668 v8::Local<v8::Context> context =
669 container_->element().document().frame()->mainWorldScriptContext();
670 DCHECK(context->GetIsolate() == isolate_);
671 return context;
674 void PepperPluginInstanceImpl::Delete() {
675 is_deleted_ = true;
677 if (render_frame_ &&
678 render_frame_->render_view()->plugin_find_handler() == this) {
679 render_frame_->render_view()->set_plugin_find_handler(NULL);
682 // Keep a reference on the stack. See NOTE above.
683 scoped_refptr<PepperPluginInstanceImpl> ref(this);
684 // Force the MessageChannel to release its "passthrough object" which should
685 // release our last reference to the "InstanceObject" and will probably
686 // destroy it. We want to do this prior to calling DidDestroy in case the
687 // destructor of the instance object tries to use the instance.
688 if (message_channel_)
689 message_channel_->SetPassthroughObject(v8::Handle<v8::Object>());
690 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
691 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
692 // since there is little that it can do at this point.
693 if (original_instance_interface_)
694 original_instance_interface_->DidDestroy(pp_instance());
695 else
696 instance_interface_->DidDestroy(pp_instance());
697 // Ensure we don't attempt to call functions on the destroyed instance.
698 original_instance_interface_.reset();
699 instance_interface_.reset();
701 if (fullscreen_container_) {
702 fullscreen_container_->Destroy();
703 fullscreen_container_ = NULL;
706 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
707 // leaks the graphics 2D, it may actually get cleaned up after our
708 // destruction, so we need its pointers to be up-to-date.
709 BindGraphics(pp_instance(), 0);
710 container_ = NULL;
713 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
715 void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
716 const gfx::Rect& plugin_rect,
717 const gfx::Rect& paint_rect) {
718 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
719 if (module()->is_crashed()) {
720 // Crashed plugin painting.
721 if (!sad_plugin_) // Lazily initialize bitmap.
722 sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
723 if (sad_plugin_)
724 PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
725 return;
728 if (bound_graphics_2d_platform_)
729 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
732 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
733 if (fullscreen_container_) {
734 if (rect.IsEmpty())
735 fullscreen_container_->Invalidate();
736 else
737 fullscreen_container_->InvalidateRect(rect);
738 } else {
739 if (!container_ || view_data_.rect.size.width == 0 ||
740 view_data_.rect.size.height == 0)
741 return; // Nothing to do.
742 if (rect.IsEmpty())
743 container_->invalidate();
744 else
745 container_->invalidateRect(rect);
748 cc::Layer* layer =
749 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
750 if (layer) {
751 if (rect.IsEmpty()) {
752 layer->SetNeedsDisplay();
753 } else {
754 layer->SetNeedsDisplayRect(rect);
759 void PepperPluginInstanceImpl::ScrollRect(int dx,
760 int dy,
761 const gfx::Rect& rect) {
762 cc::Layer* layer =
763 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
764 if (layer) {
765 InvalidateRect(rect);
766 } else if (fullscreen_container_) {
767 fullscreen_container_->ScrollRect(dx, dy, rect);
768 } else {
769 if (full_frame_ && !IsViewAccelerated()) {
770 container_->scrollRect(rect);
771 } else {
772 // Can't do optimized scrolling since there could be other elements on top
773 // of us or the view renders via the accelerated compositor which is
774 // incompatible with the move and backfill scrolling model.
775 InvalidateRect(rect);
780 void PepperPluginInstanceImpl::CommitBackingTexture() {
781 if (!texture_layer_.get())
782 return;
783 gpu::Mailbox mailbox;
784 uint32 sync_point = 0;
785 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
786 DCHECK(!mailbox.IsZero());
787 DCHECK_NE(sync_point, 0u);
788 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
789 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
790 texture_layer_->SetNeedsDisplay();
793 void PepperPluginInstanceImpl::InstanceCrashed() {
794 // Force free all resources and vars.
795 HostGlobals::Get()->InstanceCrashed(pp_instance());
797 // Free any associated graphics.
798 SetFullscreen(false);
799 FlashSetFullscreen(false, false);
800 // Unbind current 2D or 3D graphics context.
801 BindGraphics(pp_instance(), 0);
802 InvalidateRect(gfx::Rect());
804 if (content_decryptor_delegate_) {
805 content_decryptor_delegate_->InstanceCrashed();
806 content_decryptor_delegate_.reset();
809 if (render_frame_)
810 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
811 UnSetAndDeleteLockTargetAdapter();
814 static void SetGPUHistogram(const ppapi::Preferences& prefs,
815 const std::vector<std::string>& arg_names,
816 const std::vector<std::string>& arg_values) {
817 // Calculate a histogram to let us determine how likely people are to try to
818 // run Stage3D content on machines that have it blacklisted.
819 #if defined(OS_WIN)
820 bool needs_gpu = false;
821 bool is_xp = base::win::GetVersion() <= base::win::VERSION_XP;
823 for (size_t i = 0; i < arg_names.size(); i++) {
824 if (arg_names[i] == "wmode") {
825 // In theory content other than Flash could have a "wmode" argument,
826 // but that's pretty unlikely.
827 if (arg_values[i] == "direct" || arg_values[i] == "gpu")
828 needs_gpu = true;
829 break;
832 // 0 : No 3D content and GPU is blacklisted
833 // 1 : No 3D content and GPU is not blacklisted
834 // 2 : 3D content but GPU is blacklisted
835 // 3 : 3D content and GPU is not blacklisted
836 // 4 : No 3D content and GPU is blacklisted on XP
837 // 5 : No 3D content and GPU is not blacklisted on XP
838 // 6 : 3D content but GPU is blacklisted on XP
839 // 7 : 3D content and GPU is not blacklisted on XP
840 UMA_HISTOGRAM_ENUMERATION(
841 "Flash.UsesGPU", is_xp * 4 + needs_gpu * 2 + prefs.is_webgl_supported, 8);
842 #endif
845 bool PepperPluginInstanceImpl::Initialize(
846 const std::vector<std::string>& arg_names,
847 const std::vector<std::string>& arg_values,
848 bool full_frame) {
849 if (!render_frame_)
850 return false;
851 message_channel_ = MessageChannel::Create(this, &message_channel_object_);
853 full_frame_ = full_frame;
855 UpdateTouchEventRequest();
856 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
858 SetGPUHistogram(ppapi::Preferences(PpapiPreferencesBuilder::Build(
859 render_frame_->render_view()->webkit_preferences())),
860 arg_names,
861 arg_values);
863 argn_ = arg_names;
864 argv_ = arg_values;
865 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
866 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
867 bool success = PP_ToBool(instance_interface_->DidCreate(
868 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
869 // If this is a plugin that hosts external plugins, we should delay messages
870 // so that the child plugin that's created later will receive all the
871 // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
873 // A host for external plugins will call ResetAsProxied later, at which point
874 // we can Start() the MessageChannel.
875 if (success && (!module_->renderer_ppapi_host()->IsExternalPluginHost())) {
876 if (message_channel_)
877 message_channel_->Start();
879 return success;
882 bool PepperPluginInstanceImpl::HandleDocumentLoad(
883 const blink::WebURLResponse& response) {
884 DCHECK(!document_loader_);
885 if (external_document_load_) {
886 // The external proxy isn't available, so save the response and record
887 // document load notifications for later replay.
888 external_document_response_ = response;
889 external_document_loader_.reset(new ExternalDocumentLoader());
890 document_loader_ = external_document_loader_.get();
891 return true;
894 if (module()->is_crashed()) {
895 // Don't create a resource for a crashed plugin.
896 container()->element().document().frame()->stopLoading();
897 return false;
900 DCHECK(!document_loader_);
902 // Create a loader resource host for this load. Note that we have to set
903 // the document_loader before issuing the in-process
904 // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
905 // call into the instance and expect it to be valid.
906 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
907 PepperURLLoaderHost* loader_host =
908 new PepperURLLoaderHost(host_impl, true, pp_instance(), 0);
909 // TODO(teravest): Remove set_document_loader() from instance and clean up
910 // this relationship.
911 set_document_loader(loader_host);
912 loader_host->didReceiveResponse(NULL, response);
914 // This host will be pending until the resource object attaches to it.
916 // PpapiHost now owns the pointer to loader_host, so we don't have to worry
917 // about managing it.
918 int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
919 scoped_ptr<ppapi::host::ResourceHost>(loader_host));
920 DCHECK(pending_host_id);
922 DataFromWebURLResponse(
923 host_impl,
924 pp_instance(),
925 response,
926 base::Bind(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
927 weak_factory_.GetWeakPtr(),
928 response,
929 pending_host_id));
931 // If the load was not abandoned, document_loader_ will now be set. It's
932 // possible that the load was canceled by now and document_loader_ was
933 // already nulled out.
934 return true;
937 bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
938 PP_InputEvent_Type type,
939 const base::string16& text) {
940 std::vector<blink::WebCompositionUnderline> empty;
941 return SendCompositionEventWithUnderlineInformationToPlugin(
942 type,
943 text,
944 empty,
945 static_cast<int>(text.size()),
946 static_cast<int>(text.size()));
949 bool
950 PepperPluginInstanceImpl::SendCompositionEventWithUnderlineInformationToPlugin(
951 PP_InputEvent_Type type,
952 const base::string16& text,
953 const std::vector<blink::WebCompositionUnderline>& underlines,
954 int selection_start,
955 int selection_end) {
956 // Keep a reference on the stack. See NOTE above.
957 scoped_refptr<PepperPluginInstanceImpl> ref(this);
959 if (!LoadInputEventInterface())
960 return false;
962 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
963 if (!(filtered_input_event_mask_ & event_class) &&
964 !(input_event_mask_ & event_class))
965 return false;
967 ppapi::InputEventData event;
968 event.event_type = type;
969 event.event_time_stamp =
970 ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
972 // Convert UTF16 text to UTF8 with offset conversion.
973 std::vector<size_t> utf16_offsets;
974 utf16_offsets.push_back(selection_start);
975 utf16_offsets.push_back(selection_end);
976 for (size_t i = 0; i < underlines.size(); ++i) {
977 utf16_offsets.push_back(underlines[i].startOffset);
978 utf16_offsets.push_back(underlines[i].endOffset);
980 std::vector<size_t> utf8_offsets(utf16_offsets);
981 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
983 // Set the converted selection range.
984 event.composition_selection_start =
985 (utf8_offsets[0] == std::string::npos ? event.character_text.size()
986 : utf8_offsets[0]);
987 event.composition_selection_end =
988 (utf8_offsets[1] == std::string::npos ? event.character_text.size()
989 : utf8_offsets[1]);
991 // Set the converted segmentation points.
992 // Be sure to add 0 and size(), and remove duplication or errors.
993 std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
994 offset_set.insert(0);
995 offset_set.insert(event.character_text.size());
996 offset_set.erase(std::string::npos);
997 event.composition_segment_offsets.assign(offset_set.begin(),
998 offset_set.end());
1000 // Set the composition target.
1001 for (size_t i = 0; i < underlines.size(); ++i) {
1002 if (underlines[i].thick) {
1003 std::vector<uint32_t>::iterator it =
1004 std::find(event.composition_segment_offsets.begin(),
1005 event.composition_segment_offsets.end(),
1006 utf8_offsets[2 * i + 2]);
1007 if (it != event.composition_segment_offsets.end()) {
1008 event.composition_target_segment =
1009 it - event.composition_segment_offsets.begin();
1010 break;
1015 // Send the event.
1016 bool handled = false;
1017 if (filtered_input_event_mask_ & event_class)
1018 event.is_filtered = true;
1019 else
1020 handled = true; // Unfiltered events are assumed to be handled.
1021 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1022 new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
1023 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1024 pp_instance(), event_resource->pp_resource()));
1025 return handled;
1028 void PepperPluginInstanceImpl::RequestInputEventsHelper(
1029 uint32_t event_classes) {
1030 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
1031 UpdateTouchEventRequest();
1032 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
1033 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
1036 bool PepperPluginInstanceImpl::HandleCompositionStart(
1037 const base::string16& text) {
1038 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1039 text);
1042 bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1043 const base::string16& text,
1044 const std::vector<blink::WebCompositionUnderline>& underlines,
1045 int selection_start,
1046 int selection_end) {
1047 return SendCompositionEventWithUnderlineInformationToPlugin(
1048 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
1049 text,
1050 underlines,
1051 selection_start,
1052 selection_end);
1055 bool PepperPluginInstanceImpl::HandleCompositionEnd(
1056 const base::string16& text) {
1057 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1058 text);
1061 bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1062 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1065 void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1066 gfx::Range* range) const {
1067 std::vector<size_t> offsets;
1068 offsets.push_back(selection_anchor_);
1069 offsets.push_back(selection_caret_);
1070 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1071 range->set_start(offsets[0] == base::string16::npos ? text->size()
1072 : offsets[0]);
1073 range->set_end(offsets[1] == base::string16::npos ? text->size()
1074 : offsets[1]);
1077 bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1078 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1079 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1082 gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1083 if (!text_input_caret_set_) {
1084 // If it is never set by the plugin, use the bottom left corner.
1085 return gfx::Rect(view_data_.rect.point.x,
1086 view_data_.rect.point.y + view_data_.rect.size.height,
1091 // TODO(kinaba) Take CSS transformation into accont.
1092 // TODO(kinaba) Take bounding_box into account. On some platforms, an
1093 // "exclude rectangle" where candidate window must avoid the region can be
1094 // passed to IME. Currently, we pass only the caret rectangle because
1095 // it is the only information supported uniformly in Chromium.
1096 gfx::Rect caret(text_input_caret_);
1097 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1098 return caret;
1101 bool PepperPluginInstanceImpl::HandleInputEvent(
1102 const blink::WebInputEvent& event,
1103 WebCursorInfo* cursor_info) {
1104 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1106 if (event.type == blink::WebInputEvent::MouseUp && power_saver_enabled_)
1107 power_saver_enabled_ = false;
1109 if (plugin_throttled_) {
1110 if (event.type == blink::WebInputEvent::MouseUp)
1111 SetPluginThrottled(false /* throttled */);
1113 return true;
1116 if (!render_frame_)
1117 return false;
1118 if (WebInputEvent::isMouseEventType(event.type)) {
1119 render_frame_->PepperDidReceiveMouseEvent(this);
1122 // Don't dispatch input events to crashed plugins.
1123 if (module()->is_crashed())
1124 return false;
1126 // Don't send reserved system key events to plugins.
1127 if (IsReservedSystemInputEvent(event))
1128 return false;
1130 // Keep a reference on the stack. See NOTE above.
1131 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1133 bool rv = false;
1134 if (LoadInputEventInterface()) {
1135 PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
1136 if (!event_class)
1137 return false;
1139 if ((filtered_input_event_mask_ & event_class) ||
1140 (input_event_mask_ & event_class)) {
1141 // Actually send the event.
1142 std::vector<ppapi::InputEventData> events;
1143 CreateInputEventData(event, &events);
1145 // Allow the user gesture to be pending after the plugin handles the
1146 // event. This allows out-of-process plugins to respond to the user
1147 // gesture after processing has finished here.
1148 if (WebUserGestureIndicator::isProcessingUserGesture()) {
1149 pending_user_gesture_ =
1150 ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
1151 pending_user_gesture_token_ =
1152 WebUserGestureIndicator::currentUserGestureToken();
1153 pending_user_gesture_token_.setOutOfProcess();
1156 const ui::LatencyInfo* current_event_latency_info = NULL;
1157 if (render_frame_->GetRenderWidget()) {
1158 current_event_latency_info =
1159 render_frame_->GetRenderWidget()->current_event_latency_info();
1162 // Each input event may generate more than one PP_InputEvent.
1163 for (size_t i = 0; i < events.size(); i++) {
1164 if (is_tracking_latency_) {
1165 InitLatencyInfo(&events[i].latency_info,
1166 current_event_latency_info,
1167 event.type,
1168 last_input_number_++);
1170 if (filtered_input_event_mask_ & event_class)
1171 events[i].is_filtered = true;
1172 else
1173 rv = true; // Unfiltered events are assumed to be handled.
1174 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1175 new PPB_InputEvent_Shared(
1176 ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1178 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1179 pp_instance(), event_resource->pp_resource()));
1184 if (cursor_)
1185 *cursor_info = *cursor_;
1186 return rv;
1189 void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1190 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1191 if (is_deleted_)
1192 return;
1193 ppapi::proxy::HostDispatcher* dispatcher =
1194 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1195 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1196 // The dispatcher should always be valid, and MessageChannel should never
1197 // send an 'object' var over PPP_Messaging.
1198 NOTREACHED();
1199 return;
1201 dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1202 ppapi::API_ID_PPP_MESSAGING,
1203 pp_instance(),
1204 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1205 pp_instance())));
1208 bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1209 ScopedPPVar* result) {
1210 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
1211 if (is_deleted_)
1212 return false;
1213 ppapi::proxy::HostDispatcher* dispatcher =
1214 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1215 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1216 // The dispatcher should always be valid, and MessageChannel should never
1217 // send an 'object' var over PPP_Messaging.
1218 NOTREACHED();
1219 return false;
1221 ppapi::proxy::ReceiveSerializedVarReturnValue msg_reply;
1222 bool was_handled = false;
1223 dispatcher->Send(new PpapiMsg_PPPMessageHandler_HandleBlockingMessage(
1224 ppapi::API_ID_PPP_MESSAGING,
1225 pp_instance(),
1226 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1227 pp_instance()),
1228 &msg_reply,
1229 &was_handled));
1230 *result = ScopedPPVar(ScopedPPVar::PassRef(), msg_reply.Return(dispatcher));
1231 TRACE_EVENT0("ppapi",
1232 "PepperPluginInstanceImpl::HandleBlockingMessage return.");
1233 return was_handled;
1236 PP_Var PepperPluginInstanceImpl::GetInstanceObject(v8::Isolate* isolate) {
1237 // Keep a reference on the stack. See NOTE above.
1238 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1240 DCHECK_EQ(isolate, isolate_);
1242 // If the plugin supports the private instance interface, try to retrieve its
1243 // instance object.
1244 if (LoadPrivateInterface())
1245 return plugin_private_interface_->GetInstanceObject(pp_instance());
1246 return PP_MakeUndefined();
1249 void PepperPluginInstanceImpl::ViewChanged(
1250 const gfx::Rect& position,
1251 const gfx::Rect& clip,
1252 const std::vector<gfx::Rect>& cut_outs_rects) {
1253 // WebKit can give weird (x,y) positions for empty clip rects (since the
1254 // position technically doesn't matter). But we want to make these
1255 // consistent since this is given to the plugin, so force everything to 0
1256 // in the "everything is clipped" case.
1257 gfx::Rect new_clip;
1258 if (!clip.IsEmpty())
1259 new_clip = clip;
1261 cut_outs_rects_ = cut_outs_rects;
1263 view_data_.rect = PP_FromGfxRect(position);
1264 view_data_.clip_rect = PP_FromGfxRect(clip);
1265 view_data_.device_scale = container_->deviceScaleFactor();
1266 view_data_.css_scale =
1267 container_->pageZoomFactor() * container_->pageScaleFactor();
1269 gfx::Size scroll_offset =
1270 container_->element().document().frame()->scrollOffset();
1271 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1272 scroll_offset.height());
1274 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1275 WebElement element = container_->element();
1276 WebDocument document = element.document();
1277 bool is_fullscreen_element = (element == document.fullScreenElement());
1278 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1279 render_frame()->GetRenderWidget()->is_fullscreen() &&
1280 is_fullscreen_element) {
1281 // Entered fullscreen. Only possible via SetFullscreen().
1282 view_data_.is_fullscreen = true;
1283 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1284 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1285 // so desired_fullscreen_state might be out-of-date.
1286 desired_fullscreen_state_ = false;
1287 view_data_.is_fullscreen = false;
1289 // This operation will cause the plugin to re-layout which will send more
1290 // DidChangeView updates. Schedule an asynchronous update and suppress
1291 // notifications until that completes to avoid sending intermediate sizes
1292 // to the plugins.
1293 ScheduleAsyncDidChangeView();
1295 // Reset the size attributes that we hacked to fill in the screen and
1296 // retrigger ViewChanged. Make sure we don't forward duplicates of
1297 // this view to the plugin.
1298 ResetSizeAttributesAfterFullscreen();
1299 return;
1303 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1305 SendDidChangeView();
1308 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1309 if (has_webkit_focus_ == has_focus)
1310 return;
1312 bool old_plugin_focus = PluginHasFocus();
1313 has_webkit_focus_ = has_focus;
1314 if (PluginHasFocus() != old_plugin_focus)
1315 SendFocusChangeNotification();
1318 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1319 if (has_content_area_focus_ == has_focus)
1320 return;
1322 bool old_plugin_focus = PluginHasFocus();
1323 has_content_area_focus_ = has_focus;
1324 if (PluginHasFocus() != old_plugin_focus)
1325 SendFocusChangeNotification();
1328 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1329 if (is_visible == view_data_.is_page_visible)
1330 return; // Nothing to do.
1331 view_data_.is_page_visible = is_visible;
1333 // If the initial DidChangeView notification hasn't been sent to the plugin,
1334 // let it pass the visibility state for us, instead of sending a notification
1335 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1336 // hasn't been called for the first time. In that case, most of the fields in
1337 // |view_data_| haven't been properly initialized.
1338 if (sent_initial_did_change_view_)
1339 SendDidChangeView();
1342 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1343 if (bound_graphics_2d_platform_)
1344 bound_graphics_2d_platform_->ViewInitiatedPaint();
1345 else if (bound_graphics_3d_.get())
1346 bound_graphics_3d_->ViewInitiatedPaint();
1347 else if (bound_compositor_)
1348 bound_compositor_->ViewInitiatedPaint();
1351 void PepperPluginInstanceImpl::ViewFlushedPaint() {
1352 // Keep a reference on the stack. See NOTE above.
1353 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1354 if (bound_graphics_2d_platform_)
1355 bound_graphics_2d_platform_->ViewFlushedPaint();
1356 else if (bound_graphics_3d_.get())
1357 bound_graphics_3d_->ViewFlushedPaint();
1358 else if (bound_compositor_)
1359 bound_compositor_->ViewFlushedPaint();
1362 void PepperPluginInstanceImpl::SetSelectedText(
1363 const base::string16& selected_text) {
1364 selected_text_ = selected_text;
1365 gfx::Range range(0, selected_text.length());
1366 render_frame_->SetSelectedText(selected_text, 0, range);
1369 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1370 link_under_cursor_ = base::UTF8ToUTF16(url);
1373 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1374 text_input_type_ = type;
1375 render_frame_->PepperTextInputTypeChanged(this);
1378 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1379 if (message_channel_)
1380 message_channel_->PostMessageToJavaScript(message);
1383 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1384 PP_Instance instance,
1385 void* user_data,
1386 const PPP_MessageHandler_0_2* handler,
1387 PP_Resource message_loop) {
1388 // Not supported in-process.
1389 NOTIMPLEMENTED();
1390 return PP_ERROR_FAILED;
1393 int32_t PepperPluginInstanceImpl::RegisterMessageHandler_1_1_Deprecated(
1394 PP_Instance instance,
1395 void* user_data,
1396 const PPP_MessageHandler_0_1_Deprecated* handler,
1397 PP_Resource message_loop) {
1398 // Not supported in-process.
1399 NOTIMPLEMENTED();
1400 return PP_ERROR_FAILED;
1403 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1404 // Not supported in-process.
1405 NOTIMPLEMENTED();
1408 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1409 return selected_text_;
1412 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1413 const gfx::Point& point) {
1414 // Keep a reference on the stack. See NOTE above.
1415 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1416 if (!LoadPdfInterface()) {
1417 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1418 // return |link_under_cursor_| here because this is only ever called with
1419 // the current mouse coordinates.
1420 return link_under_cursor_;
1423 PP_Point p;
1424 p.x = point.x();
1425 p.y = point.y();
1426 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1427 // If the plugin returns undefined for this function it has switched to
1428 // providing us with the link under the cursor eagerly.
1429 if (rv.type == PP_VARTYPE_UNDEFINED)
1430 return link_under_cursor_;
1431 StringVar* string = StringVar::FromPPVar(rv);
1432 base::string16 link;
1433 if (string)
1434 link = base::UTF8ToUTF16(string->value());
1435 // Release the ref the plugin transfered to us.
1436 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1437 return link;
1440 void PepperPluginInstanceImpl::RequestSurroundingText(
1441 size_t desired_number_of_characters) {
1442 // Keep a reference on the stack. See NOTE above.
1443 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1444 if (!LoadTextInputInterface())
1445 return;
1446 plugin_textinput_interface_->RequestSurroundingText(
1447 pp_instance(), desired_number_of_characters);
1450 void PepperPluginInstanceImpl::Zoom(double factor, bool text_only) {
1451 // Keep a reference on the stack. See NOTE above.
1452 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1453 if (!LoadZoomInterface())
1454 return;
1455 plugin_zoom_interface_->Zoom(pp_instance(), factor, PP_FromBool(text_only));
1458 bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1459 bool case_sensitive,
1460 int identifier) {
1461 // Keep a reference on the stack. See NOTE above.
1462 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1463 if (!LoadFindInterface())
1464 return false;
1465 find_identifier_ = identifier;
1466 return PP_ToBool(
1467 plugin_find_interface_->StartFind(pp_instance(),
1468 base::UTF16ToUTF8(search_text).c_str(),
1469 PP_FromBool(case_sensitive)));
1472 void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1473 // Keep a reference on the stack. See NOTE above.
1474 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1475 if (LoadFindInterface())
1476 plugin_find_interface_->SelectFindResult(pp_instance(),
1477 PP_FromBool(forward));
1480 void PepperPluginInstanceImpl::StopFind() {
1481 // Keep a reference on the stack. See NOTE above.
1482 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1483 if (!LoadFindInterface())
1484 return;
1485 find_identifier_ = -1;
1486 plugin_find_interface_->StopFind(pp_instance());
1489 bool PepperPluginInstanceImpl::LoadFindInterface() {
1490 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1491 return false;
1492 if (!plugin_find_interface_) {
1493 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1494 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1497 return !!plugin_find_interface_;
1500 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1501 if (!checked_for_plugin_input_event_interface_) {
1502 checked_for_plugin_input_event_interface_ = true;
1503 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1504 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1506 return !!plugin_input_event_interface_;
1509 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1510 if (!plugin_mouse_lock_interface_) {
1511 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1512 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1515 return !!plugin_mouse_lock_interface_;
1518 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1519 if (!checked_for_plugin_pdf_interface_) {
1520 checked_for_plugin_pdf_interface_ = true;
1521 plugin_pdf_interface_ = static_cast<const PPP_Pdf_1*>(
1522 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1525 return !!plugin_pdf_interface_;
1528 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1529 // Only check for the interface if the plugin has dev permission.
1530 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1531 return false;
1532 if (!plugin_print_interface_) {
1533 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1534 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1536 return !!plugin_print_interface_;
1539 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1540 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1541 // call GetInstanceObject. This is necessary to ensure that the properties
1542 // the trusted plugin exposes (readyState and lastError) work properly. Note
1543 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1544 // so it's correct to never look up PPP_InstancePrivate for them.
1546 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1547 // to the "real" module.
1548 scoped_refptr<PluginModule> module =
1549 original_module_.get() ? original_module_ : module_;
1550 // Only check for the interface if the plugin has private permission.
1551 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1552 return false;
1553 if (!plugin_private_interface_) {
1554 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1555 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1558 return !!plugin_private_interface_;
1561 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1562 if (!plugin_textinput_interface_) {
1563 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1564 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1567 return !!plugin_textinput_interface_;
1570 bool PepperPluginInstanceImpl::LoadZoomInterface() {
1571 if (!plugin_zoom_interface_) {
1572 plugin_zoom_interface_ = static_cast<const PPP_Zoom_Dev*>(
1573 module_->GetPluginInterface(PPP_ZOOM_DEV_INTERFACE));
1576 return !!plugin_zoom_interface_;
1579 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1580 if (!bound_graphics_2d_platform_ || !texture_layer_.get()) {
1581 // Currently the transform is only applied for Graphics2D.
1582 return;
1584 // Set the UV coordinates of the texture based on the size of the Graphics2D
1585 // context. By default a texture gets scaled to the size of the layer. But
1586 // if the size of the Graphics2D context doesn't match the size of the plugin
1587 // then it will be incorrectly stretched. This also affects how the plugin
1588 // is painted when it is being resized. If the Graphics2D contents are
1589 // stretched when a plugin is resized while waiting for a new frame from the
1590 // plugin to be rendered, then flickering behavior occurs as in
1591 // crbug.com/353453.
1592 gfx::SizeF graphics_2d_size_in_dip =
1593 gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1594 bound_graphics_2d_platform_->GetScale());
1595 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1596 view_data_.rect.size.height);
1598 texture_layer_->SetUV(
1599 gfx::PointF(0.0f, 0.0f),
1600 gfx::PointF(
1601 plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1602 plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1605 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1606 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1609 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1610 // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1611 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1612 // drop its reference, usually the last one. This is similar to possible
1613 // plugin behavior described at the NOTE above Delete().
1614 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1616 if (!render_frame_)
1617 return;
1619 bool has_focus = PluginHasFocus();
1620 render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1622 // instance_interface_ may have been cleared in Delete() if the
1623 // PepperWebPluginImpl is destroyed.
1624 if (instance_interface_)
1625 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1628 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1629 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1630 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1631 container_->requestTouchEventType(
1632 raw_touch
1633 ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1634 : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1637 bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1638 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1639 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1642 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1643 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1644 return; // Already scheduled.
1645 base::MessageLoop::current()->PostTask(
1646 FROM_HERE,
1647 base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1648 view_change_weak_ptr_factory_.GetWeakPtr()));
1651 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1652 // The bound callback that owns the weak pointer is still valid until after
1653 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1654 // invalidate them here.
1655 // NOTE: If we ever want to have more than one pending callback, it should
1656 // use a different factory, or we should have a different strategy here.
1657 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1658 SendDidChangeView();
1661 void PepperPluginInstanceImpl::SendDidChangeView() {
1662 // Don't send DidChangeView to crashed plugins.
1663 if (module()->is_crashed())
1664 return;
1666 // When plugin is throttled, send ViewData indicating it's in the background.
1667 const ppapi::ViewData& view_data =
1668 plugin_throttled_ ? empty_view_data_ : view_data_;
1670 if (view_change_weak_ptr_factory_.HasWeakPtrs() ||
1671 (sent_initial_did_change_view_ &&
1672 last_sent_view_data_.Equals(view_data)))
1673 return; // Nothing to update.
1675 sent_initial_did_change_view_ = true;
1676 last_sent_view_data_ = view_data;
1677 ScopedPPResource resource(
1678 ScopedPPResource::PassRef(),
1679 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data))
1680 ->GetReference());
1682 UpdateLayerTransform();
1684 if (bound_graphics_2d_platform_ &&
1685 (!view_data.is_page_visible ||
1686 PP_ToGfxRect(view_data.clip_rect).IsEmpty())) {
1687 bound_graphics_2d_platform_->ClearCache();
1690 // It's possible that Delete() has been called but the renderer hasn't
1691 // released its reference to this object yet.
1692 if (instance_interface_) {
1693 instance_interface_->DidChangeView(
1694 pp_instance(), resource, &view_data.rect, &view_data.clip_rect);
1698 void PepperPluginInstanceImpl::ReportGeometry() {
1699 // If this call was delayed, we may have transitioned back to fullscreen in
1700 // the mean time, so only report the geometry if we are actually in normal
1701 // mode.
1702 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1703 container_->reportGeometry();
1706 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1707 PP_PrintOutputFormat_Dev* format) {
1708 // Keep a reference on the stack. See NOTE above.
1709 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1710 if (!LoadPrintInterface())
1711 return false;
1712 uint32_t supported_formats =
1713 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1714 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1715 *format = PP_PRINTOUTPUTFORMAT_PDF;
1716 return true;
1718 return false;
1721 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1722 PP_PrintOutputFormat_Dev format;
1723 return GetPreferredPrintOutputFormat(&format);
1726 bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1727 DCHECK(plugin_print_interface_);
1728 if (!plugin_print_interface_)
1729 return false;
1730 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1733 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1734 // Keep a reference on the stack. See NOTE above.
1735 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1736 PP_PrintOutputFormat_Dev format;
1737 if (!GetPreferredPrintOutputFormat(&format)) {
1738 // PrintBegin should not have been called since SupportsPrintInterface
1739 // would have returned false;
1740 NOTREACHED();
1741 return 0;
1743 int num_pages = 0;
1744 PP_PrintSettings_Dev print_settings;
1745 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1746 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1747 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1748 print_settings.dpi = print_params.printerDPI;
1749 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1750 print_settings.grayscale = PP_FALSE;
1751 print_settings.print_scaling_option =
1752 static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1753 print_settings.format = format;
1754 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1755 if (!num_pages)
1756 return 0;
1757 current_print_settings_ = print_settings;
1758 canvas_.clear();
1759 ranges_.clear();
1760 return num_pages;
1763 bool PepperPluginInstanceImpl::PrintPage(int page_number,
1764 blink::WebCanvas* canvas) {
1765 #if defined(ENABLE_PRINTING)
1766 DCHECK(plugin_print_interface_);
1767 PP_PrintPageNumberRange_Dev page_range;
1768 page_range.first_page_number = page_range.last_page_number = page_number;
1769 // The canvas only has a metafile on it for print preview.
1770 bool save_for_later =
1771 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1772 #if defined(OS_MACOSX)
1773 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1774 #endif // defined(OS_MACOSX)
1775 if (save_for_later) {
1776 ranges_.push_back(page_range);
1777 canvas_ = skia::SharePtr(canvas);
1778 return true;
1779 } else {
1780 return PrintPageHelper(&page_range, 1, canvas);
1782 #else // ENABLE_PRINTING
1783 return false;
1784 #endif
1787 bool PepperPluginInstanceImpl::PrintPageHelper(
1788 PP_PrintPageNumberRange_Dev* page_ranges,
1789 int num_ranges,
1790 blink::WebCanvas* canvas) {
1791 // Keep a reference on the stack. See NOTE above.
1792 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1793 DCHECK(plugin_print_interface_);
1794 if (!plugin_print_interface_)
1795 return false;
1796 PP_Resource print_output = plugin_print_interface_->PrintPages(
1797 pp_instance(), page_ranges, num_ranges);
1798 if (!print_output)
1799 return false;
1801 bool ret = false;
1803 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1804 ret = PrintPDFOutput(print_output, canvas);
1806 // Now we need to release the print output resource.
1807 PluginModule::GetCore()->ReleaseResource(print_output);
1809 return ret;
1812 void PepperPluginInstanceImpl::PrintEnd() {
1813 // Keep a reference on the stack. See NOTE above.
1814 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1815 if (!ranges_.empty())
1816 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1817 canvas_.clear();
1818 ranges_.clear();
1820 DCHECK(plugin_print_interface_);
1821 if (plugin_print_interface_)
1822 plugin_print_interface_->End(pp_instance());
1824 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1825 #if defined(OS_MACOSX)
1826 last_printed_page_ = NULL;
1827 #endif // defined(OS_MACOSX)
1830 bool PepperPluginInstanceImpl::CanRotateView() {
1831 if (!LoadPdfInterface())
1832 return false;
1834 return true;
1837 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1838 if (!LoadPdfInterface())
1839 return;
1840 PP_PrivatePageTransformType transform_type =
1841 type == WebPlugin::RotationType90Clockwise
1842 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1843 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1844 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1845 // NOTE: plugin instance may have been deleted.
1848 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1849 return fullscreen_container_ != NULL;
1852 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1853 return desired_fullscreen_state_;
1856 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1857 // Keep a reference on the stack. See NOTE above.
1858 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1860 // Check whether we are trying to switch to the state we're already going
1861 // to (i.e. if we're already switching to fullscreen but the fullscreen
1862 // container isn't ready yet, don't do anything more).
1863 if (fullscreen == IsFullscreenOrPending())
1864 return false;
1866 if (!render_frame_)
1867 return false;
1868 if (fullscreen && !render_frame_->render_view()
1869 ->renderer_preferences()
1870 .plugin_fullscreen_allowed)
1871 return false;
1873 // Check whether we are trying to switch while the state is in transition.
1874 // The 2nd request gets dropped while messing up the internal state, so
1875 // disallow this.
1876 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1877 return false;
1879 if (fullscreen && !IsProcessingUserGesture())
1880 return false;
1882 VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1883 desired_fullscreen_state_ = fullscreen;
1885 if (fullscreen) {
1886 // Create the user gesture in case we're processing one that's pending.
1887 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1888 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1889 // so we will tweak plugin's attributes to support the expected behavior.
1890 KeepSizeAttributesBeforeFullscreen();
1891 SetSizeAttributesForFullscreen();
1892 container_->element().requestFullScreen();
1893 } else {
1894 container_->element().document().cancelFullScreen();
1896 return true;
1899 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1900 bool flash_fullscreen) {
1901 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1903 if (flash_fullscreen == flash_fullscreen_) {
1904 // Manually clear callback when fullscreen fails with mouselock pending.
1905 if (!flash_fullscreen && is_mouselock_pending)
1906 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1907 return;
1910 UpdateLayer(false);
1912 bool old_plugin_focus = PluginHasFocus();
1913 flash_fullscreen_ = flash_fullscreen;
1914 if (is_mouselock_pending && !IsMouseLocked()) {
1915 if (!IsProcessingUserGesture() &&
1916 !module_->permissions().HasPermission(
1917 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1918 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1919 } else {
1920 // Open a user gesture here so the Webkit user gesture checks will succeed
1921 // for out-of-process plugins.
1922 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1923 if (!LockMouse())
1924 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1928 if (PluginHasFocus() != old_plugin_focus)
1929 SendFocusChangeNotification();
1932 bool PepperPluginInstanceImpl::IsViewAccelerated() {
1933 if (!container_)
1934 return false;
1936 WebDocument document = container_->element().document();
1937 WebLocalFrame* frame = document.frame();
1938 if (!frame)
1939 return false;
1940 WebView* view = frame->view();
1941 if (!view)
1942 return false;
1944 return view->isAcceleratedCompositingActive();
1947 bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1948 blink::WebCanvas* canvas) {
1949 #if defined(ENABLE_PRINTING)
1950 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1951 if (enter.failed())
1952 return false;
1954 BufferAutoMapper mapper(enter.object());
1955 if (!mapper.data() || !mapper.size()) {
1956 NOTREACHED();
1957 return false;
1960 printing::PdfMetafileSkia* metafile =
1961 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1962 if (metafile)
1963 return metafile->InitFromData(mapper.data(), mapper.size());
1965 NOTREACHED();
1966 #endif // ENABLE_PRINTING
1967 return false;
1970 void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
1971 if (!container_)
1972 return;
1974 gpu::Mailbox mailbox;
1975 uint32 sync_point = 0;
1976 if (bound_graphics_3d_.get()) {
1977 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
1978 DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
1980 bool want_3d_layer = !mailbox.IsZero();
1981 bool want_2d_layer = !!bound_graphics_2d_platform_;
1982 bool want_texture_layer = want_3d_layer || want_2d_layer;
1983 bool want_compositor_layer = !!bound_compositor_;
1985 if (!device_changed && (want_texture_layer == !!texture_layer_.get()) &&
1986 (want_3d_layer == layer_is_hardware_) &&
1987 (want_compositor_layer == !!compositor_layer_.get()) &&
1988 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
1989 UpdateLayerTransform();
1990 return;
1993 if (texture_layer_.get() || compositor_layer_.get()) {
1994 if (!layer_bound_to_fullscreen_)
1995 container_->setWebLayer(NULL);
1996 else if (fullscreen_container_)
1997 fullscreen_container_->SetLayer(NULL);
1998 web_layer_.reset();
1999 texture_layer_ = NULL;
2000 compositor_layer_ = NULL;
2003 if (want_texture_layer) {
2004 bool opaque = false;
2005 if (want_3d_layer) {
2006 DCHECK(bound_graphics_3d_.get());
2007 texture_layer_ = cc::TextureLayer::CreateForMailbox(NULL);
2008 opaque = bound_graphics_3d_->IsOpaque();
2009 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
2010 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
2011 } else {
2012 DCHECK(bound_graphics_2d_platform_);
2013 texture_layer_ = cc::TextureLayer::CreateForMailbox(this);
2014 bound_graphics_2d_platform_->AttachedToNewLayer();
2015 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2016 texture_layer_->SetFlipped(false);
2019 // Ignore transparency in fullscreen, since that's what Flash always
2020 // wants to do, and that lets it not recreate a context if
2021 // wmode=transparent was specified.
2022 opaque = opaque || fullscreen_container_;
2023 texture_layer_->SetContentsOpaque(opaque);
2024 web_layer_.reset(new cc_blink::WebLayerImpl(texture_layer_));
2025 } else if (want_compositor_layer) {
2026 compositor_layer_ = bound_compositor_->layer();
2027 web_layer_.reset(new cc_blink::WebLayerImpl(compositor_layer_));
2030 if (web_layer_) {
2031 if (fullscreen_container_) {
2032 fullscreen_container_->SetLayer(web_layer_.get());
2033 } else {
2034 container_->setWebLayer(web_layer_.get());
2038 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2039 layer_is_hardware_ = want_3d_layer;
2040 UpdateLayerTransform();
2043 bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2044 cc::TextureMailbox* mailbox,
2045 scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2046 bool use_shared_memory) {
2047 if (!bound_graphics_2d_platform_)
2048 return false;
2049 return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2050 release_callback);
2053 void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2055 void PepperPluginInstanceImpl::AddLatencyInfo(
2056 const std::vector<ui::LatencyInfo>& latency_info) {
2057 if (render_frame_ && render_frame_->GetRenderWidget()) {
2058 RenderWidgetCompositor* compositor =
2059 render_frame_->GetRenderWidget()->compositor();
2060 if (compositor) {
2061 for (size_t i = 0; i < latency_info.size(); i++) {
2062 scoped_ptr<cc::SwapPromise> swap_promise(
2063 new cc::LatencyInfoSwapPromise(latency_info[i]));
2064 compositor->QueueSwapPromise(swap_promise.Pass());
2070 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2071 DCHECK(live_plugin_objects_.find(plugin_object) ==
2072 live_plugin_objects_.end());
2073 live_plugin_objects_.insert(plugin_object);
2076 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2077 // Don't actually verify that the object is in the set since during module
2078 // deletion we'll be in the process of freeing them.
2079 live_plugin_objects_.erase(plugin_object);
2082 bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2083 PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2084 // Give a lot of slack so tests won't be flaky.
2085 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2086 return pending_user_gesture_token_.hasGestures() &&
2087 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2090 WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2091 if (!IsProcessingUserGesture())
2092 pending_user_gesture_token_ = WebUserGestureToken();
2093 return pending_user_gesture_token_;
2096 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2097 if (TrackedCallback::IsPending(lock_mouse_callback_))
2098 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2101 void PepperPluginInstanceImpl::OnMouseLockLost() {
2102 if (LoadMouseLockInterface())
2103 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2106 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2107 const blink::WebMouseEvent& event) {
2108 // |cursor_info| is ignored since it is hidden when the mouse is locked.
2109 blink::WebCursorInfo cursor_info;
2110 HandleInputEvent(event, &cursor_info);
2113 void PepperPluginInstanceImpl::SimulateInputEvent(
2114 const InputEventData& input_event) {
2115 WebView* web_view = container()->element().document().frame()->view();
2116 if (!web_view) {
2117 NOTREACHED();
2118 return;
2121 bool handled = SimulateIMEEvent(input_event);
2122 if (handled)
2123 return;
2125 std::vector<linked_ptr<WebInputEvent> > events =
2126 CreateSimulatedWebInputEvents(
2127 input_event,
2128 view_data_.rect.point.x + view_data_.rect.size.width / 2,
2129 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2130 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2131 it != events.end();
2132 ++it) {
2133 web_view->handleInputEvent(*it->get());
2137 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2138 const InputEventData& input_event) {
2139 switch (input_event.event_type) {
2140 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2141 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2142 SimulateImeSetCompositionEvent(input_event);
2143 break;
2144 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2145 DCHECK(input_event.character_text.empty());
2146 SimulateImeSetCompositionEvent(input_event);
2147 break;
2148 case PP_INPUTEVENT_TYPE_IME_TEXT:
2149 if (!render_frame_)
2150 return false;
2151 render_frame_->SimulateImeConfirmComposition(
2152 base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2153 break;
2154 default:
2155 return false;
2157 return true;
2160 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2161 const InputEventData& input_event) {
2162 if (!render_frame_)
2163 return;
2165 std::vector<size_t> offsets;
2166 offsets.push_back(input_event.composition_selection_start);
2167 offsets.push_back(input_event.composition_selection_end);
2168 offsets.insert(offsets.end(),
2169 input_event.composition_segment_offsets.begin(),
2170 input_event.composition_segment_offsets.end());
2172 base::string16 utf16_text =
2173 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2175 std::vector<blink::WebCompositionUnderline> underlines;
2176 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2177 blink::WebCompositionUnderline underline;
2178 underline.startOffset = offsets[i];
2179 underline.endOffset = offsets[i + 1];
2180 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2181 underline.thick = true;
2182 underlines.push_back(underline);
2185 render_frame_->SimulateImeSetComposition(
2186 utf16_text, underlines, offsets[0], offsets[1]);
2189 ContentDecryptorDelegate*
2190 PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2191 if (content_decryptor_delegate_)
2192 return content_decryptor_delegate_.get();
2194 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2195 static_cast<const PPP_ContentDecryptor_Private*>(
2196 module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2197 if (!plugin_decryption_interface)
2198 return NULL;
2200 content_decryptor_delegate_.reset(
2201 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2202 return content_decryptor_delegate_.get();
2205 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2206 PP_Resource device) {
2207 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2208 // The Graphics3D instance can't be destroyed until we call
2209 // UpdateLayer().
2210 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2211 if (bound_graphics_3d_.get()) {
2212 bound_graphics_3d_->BindToInstance(false);
2213 bound_graphics_3d_ = NULL;
2215 if (bound_graphics_2d_platform_) {
2216 bound_graphics_2d_platform_->BindToInstance(NULL);
2217 bound_graphics_2d_platform_ = NULL;
2219 if (bound_compositor_) {
2220 bound_compositor_->BindToInstance(NULL);
2221 bound_compositor_ = NULL;
2224 // Special-case clearing the current device.
2225 if (!device) {
2226 UpdateLayer(true);
2227 InvalidateRect(gfx::Rect());
2228 return PP_TRUE;
2231 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2232 // to/from fullscreen with PPB_Fullscreen.
2233 if ((fullscreen_container_ && !flash_fullscreen_) ||
2234 desired_fullscreen_state_ != view_data_.is_fullscreen)
2235 return PP_FALSE;
2237 const ppapi::host::PpapiHost* ppapi_host =
2238 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2239 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2240 PepperGraphics2DHost* graphics_2d = NULL;
2241 PepperCompositorHost* compositor = NULL;
2242 if (host) {
2243 if (host->IsGraphics2DHost()) {
2244 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2245 } else if (host->IsCompositorHost()) {
2246 compositor = static_cast<PepperCompositorHost*>(host);
2247 } else {
2248 DLOG(ERROR) <<
2249 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2253 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2254 PPB_Graphics3D_Impl* graphics_3d =
2255 enter_3d.succeeded()
2256 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2257 : NULL;
2259 if (compositor) {
2260 if (compositor->BindToInstance(this)) {
2261 bound_compositor_ = compositor;
2262 UpdateLayer(true);
2263 return PP_TRUE;
2265 } else if (graphics_2d) {
2266 if (graphics_2d->BindToInstance(this)) {
2267 bound_graphics_2d_platform_ = graphics_2d;
2268 UpdateLayer(true);
2269 return PP_TRUE;
2271 } else if (graphics_3d) {
2272 // Make sure graphics can only be bound to the instance it is
2273 // associated with.
2274 if (graphics_3d->pp_instance() == pp_instance() &&
2275 graphics_3d->BindToInstance(true)) {
2276 bound_graphics_3d_ = graphics_3d;
2277 UpdateLayer(true);
2278 return PP_TRUE;
2282 // The instance cannot be bound or the device is not a valid resource type.
2283 return PP_FALSE;
2286 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2287 return PP_FromBool(full_frame());
2290 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2291 return &view_data_;
2294 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2295 return PP_FromBool(flash_fullscreen_);
2298 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2299 if (!container_)
2300 return PP_MakeUndefined();
2302 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2303 PepperTryCatchVar try_catch(this, &converter, NULL);
2304 WebLocalFrame* frame = container_->element().document().frame();
2305 if (!frame) {
2306 try_catch.SetException("No frame exists for window object.");
2307 return PP_MakeUndefined();
2310 ScopedPPVar result =
2311 try_catch.FromV8(frame->mainWorldScriptContext()->Global());
2312 DCHECK(!try_catch.HasException());
2313 return result.Release();
2316 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2317 if (!container_)
2318 return PP_MakeUndefined();
2319 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2320 PepperTryCatchVar try_catch(this, &converter, NULL);
2321 ScopedPPVar result = try_catch.FromV8(container_->v8ObjectForElement());
2322 DCHECK(!try_catch.HasException());
2323 return result.Release();
2326 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2327 PP_Var script_var,
2328 PP_Var* exception) {
2329 if (!container_)
2330 return PP_MakeUndefined();
2332 // Executing the script may remove the plugin from the DOM, so we need to keep
2333 // a reference to ourselves so that we can still process the result after the
2334 // WebBindings::evaluate() below.
2335 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2336 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2337 PepperTryCatchVar try_catch(this, &converter, exception);
2339 // Check for an exception due to the context being destroyed.
2340 if (try_catch.HasException())
2341 return PP_MakeUndefined();
2343 WebLocalFrame* frame = container_->element().document().frame();
2344 if (!frame) {
2345 try_catch.SetException("No frame to execute script in.");
2346 return PP_MakeUndefined();
2349 StringVar* script_string_var = StringVar::FromPPVar(script_var);
2350 if (!script_string_var) {
2351 try_catch.SetException("Script param to ExecuteScript must be a string.");
2352 return PP_MakeUndefined();
2355 std::string script_string = script_string_var->value();
2356 blink::WebScriptSource script(
2357 blink::WebString::fromUTF8(script_string.c_str()));
2358 v8::Handle<v8::Value> result;
2359 if (IsProcessingUserGesture()) {
2360 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2361 result = frame->executeScriptAndReturnValue(script);
2362 } else {
2363 result = frame->executeScriptAndReturnValue(script);
2366 // Check for an exception due to the context being destroyed.
2367 if (try_catch.HasException())
2368 return PP_MakeUndefined();
2370 ScopedPPVar var_result = try_catch.FromV8(result);
2371 if (try_catch.HasException())
2372 return PP_MakeUndefined();
2374 return var_result.Release();
2377 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2378 PP_Instance instance) {
2379 RenderThreadImpl* thread = RenderThreadImpl::current();
2380 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2383 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2384 PP_Instance instance) {
2385 RenderThreadImpl* thread = RenderThreadImpl::current();
2386 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2389 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2390 if (!render_frame_)
2391 return PP_MakeUndefined();
2392 return StringVar::StringToPPVar(
2393 render_frame_->render_view()->webkit_preferences().default_encoding);
2396 // These PPB_ContentDecryptor_Private calls are responses to
2397 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2398 // Therefore, |content_decryptor_delegate_| must have been initialized when
2399 // the following methods are called.
2400 void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2401 uint32 promise_id) {
2402 content_decryptor_delegate_->OnPromiseResolved(promise_id);
2405 void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2406 PP_Instance instance,
2407 uint32 promise_id,
2408 PP_Var web_session_id_var) {
2409 content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2410 web_session_id_var);
2413 void PepperPluginInstanceImpl::PromiseResolvedWithKeyIds(PP_Instance instance,
2414 uint32 promise_id,
2415 PP_Var key_ids_var) {
2416 content_decryptor_delegate_->OnPromiseResolvedWithKeyIds(promise_id,
2417 key_ids_var);
2420 void PepperPluginInstanceImpl::PromiseRejected(
2421 PP_Instance instance,
2422 uint32 promise_id,
2423 PP_CdmExceptionCode exception_code,
2424 uint32 system_code,
2425 PP_Var error_description_var) {
2426 content_decryptor_delegate_->OnPromiseRejected(
2427 promise_id, exception_code, system_code, error_description_var);
2430 void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2431 PP_Var web_session_id_var,
2432 PP_Var message_var,
2433 PP_Var destination_url_var) {
2434 content_decryptor_delegate_->OnSessionMessage(
2435 web_session_id_var, message_var, destination_url_var);
2438 void PepperPluginInstanceImpl::SessionKeysChange(
2439 PP_Instance instance,
2440 PP_Var web_session_id_var,
2441 PP_Bool has_additional_usable_key) {
2442 content_decryptor_delegate_->OnSessionKeysChange(web_session_id_var,
2443 has_additional_usable_key);
2446 void PepperPluginInstanceImpl::SessionExpirationChange(
2447 PP_Instance instance,
2448 PP_Var web_session_id_var,
2449 PP_Time new_expiry_time) {
2450 content_decryptor_delegate_->OnSessionExpirationChange(web_session_id_var,
2451 new_expiry_time);
2454 void PepperPluginInstanceImpl::SessionReady(PP_Instance instance,
2455 PP_Var web_session_id_var) {
2456 content_decryptor_delegate_->OnSessionReady(web_session_id_var);
2459 void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2460 PP_Var web_session_id_var) {
2461 content_decryptor_delegate_->OnSessionClosed(web_session_id_var);
2464 void PepperPluginInstanceImpl::SessionError(PP_Instance instance,
2465 PP_Var web_session_id_var,
2466 PP_CdmExceptionCode exception_code,
2467 uint32 system_code,
2468 PP_Var error_description_var) {
2469 content_decryptor_delegate_->OnSessionError(
2470 web_session_id_var, exception_code, system_code, error_description_var);
2473 void PepperPluginInstanceImpl::DeliverBlock(
2474 PP_Instance instance,
2475 PP_Resource decrypted_block,
2476 const PP_DecryptedBlockInfo* block_info) {
2477 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2480 void PepperPluginInstanceImpl::DecoderInitializeDone(
2481 PP_Instance instance,
2482 PP_DecryptorStreamType decoder_type,
2483 uint32_t request_id,
2484 PP_Bool success) {
2485 content_decryptor_delegate_->DecoderInitializeDone(
2486 decoder_type, request_id, success);
2489 void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2490 PP_Instance instance,
2491 PP_DecryptorStreamType decoder_type,
2492 uint32_t request_id) {
2493 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2494 request_id);
2497 void PepperPluginInstanceImpl::DecoderResetDone(
2498 PP_Instance instance,
2499 PP_DecryptorStreamType decoder_type,
2500 uint32_t request_id) {
2501 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2504 void PepperPluginInstanceImpl::DeliverFrame(
2505 PP_Instance instance,
2506 PP_Resource decrypted_frame,
2507 const PP_DecryptedFrameInfo* frame_info) {
2508 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2511 void PepperPluginInstanceImpl::DeliverSamples(
2512 PP_Instance instance,
2513 PP_Resource audio_frames,
2514 const PP_DecryptedSampleInfo* sample_info) {
2515 content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2518 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2519 PP_Instance instance) {
2520 if (!LoadFindInterface())
2521 return;
2522 bool is_main_frame =
2523 render_frame_ &&
2524 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2525 if (!is_main_frame)
2526 return;
2527 render_frame_->render_view()->set_plugin_find_handler(this);
2530 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2531 PP_Instance instance,
2532 int32_t total,
2533 PP_Bool final_result) {
2534 DCHECK_NE(find_identifier_, -1);
2535 if (render_frame_) {
2536 render_frame_->reportFindInPageMatchCount(
2537 find_identifier_, total, PP_ToBool(final_result));
2541 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2542 int32_t index) {
2543 DCHECK_NE(find_identifier_, -1);
2544 if (render_frame_) {
2545 render_frame_->reportFindInPageSelection(
2546 find_identifier_, index + 1, blink::WebRect());
2550 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2551 const PP_Rect* tickmarks,
2552 uint32_t count) {
2553 if (!render_frame_ || !render_frame_->GetWebFrame())
2554 return;
2556 blink::WebVector<blink::WebRect> tickmarks_converted(
2557 static_cast<size_t>(count));
2558 for (uint32 i = 0; i < count; ++i) {
2559 tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2560 tickmarks[i].point.y,
2561 tickmarks[i].size.width,
2562 tickmarks[i].size.height);
2565 blink::WebFrame* frame = render_frame_->GetWebFrame();
2566 frame->setTickmarks(tickmarks_converted);
2569 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2570 return PP_FromBool(view_data_.is_fullscreen);
2573 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2574 PP_Bool fullscreen) {
2575 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2578 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2579 PP_Size* size) {
2580 blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2581 *size = PP_MakeSize(info.rect.width, info.rect.height);
2582 return PP_TRUE;
2585 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2586 PP_Instance instance,
2587 ppapi::SingletonResourceID id) {
2588 // Flash APIs and some others aren't implemented in-process.
2589 switch (id) {
2590 case ppapi::BROKER_SINGLETON_ID:
2591 case ppapi::BROWSER_FONT_SINGLETON_ID:
2592 case ppapi::FILE_MAPPING_SINGLETON_ID:
2593 case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2594 case ppapi::FLASH_FILE_SINGLETON_ID:
2595 case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2596 case ppapi::FLASH_SINGLETON_ID:
2597 case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2598 case ppapi::NETWORK_PROXY_SINGLETON_ID:
2599 case ppapi::PDF_SINGLETON_ID:
2600 case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2601 NOTIMPLEMENTED();
2602 return NULL;
2603 case ppapi::GAMEPAD_SINGLETON_ID:
2604 return gamepad_impl_.get();
2605 case ppapi::UMA_SINGLETON_ID: {
2606 if (!uma_private_impl_.get()) {
2607 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2608 if (host_impl->in_process_router()) {
2609 uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2610 host_impl->in_process_router()->GetPluginConnection(instance),
2611 instance);
2614 return uma_private_impl_.get();
2618 NOTREACHED();
2619 return NULL;
2622 int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2623 uint32_t event_classes) {
2624 input_event_mask_ |= event_classes;
2625 filtered_input_event_mask_ &= ~(event_classes);
2626 RequestInputEventsHelper(event_classes);
2627 return ValidateRequestInputEvents(false, event_classes);
2630 int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2631 PP_Instance instance,
2632 uint32_t event_classes) {
2633 filtered_input_event_mask_ |= event_classes;
2634 input_event_mask_ &= ~(event_classes);
2635 RequestInputEventsHelper(event_classes);
2636 return ValidateRequestInputEvents(true, event_classes);
2639 void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2640 uint32_t event_classes) {
2641 input_event_mask_ &= ~(event_classes);
2642 filtered_input_event_mask_ &= ~(event_classes);
2643 RequestInputEventsHelper(event_classes);
2646 void PepperPluginInstanceImpl::StartTrackingLatency(PP_Instance instance) {
2647 if (module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
2648 is_tracking_latency_ = true;
2651 void PepperPluginInstanceImpl::ZoomChanged(PP_Instance instance,
2652 double factor) {
2653 // We only want to tell the page to change its zoom if the whole page is the
2654 // plugin. If we're in an iframe, then don't do anything.
2655 if (!IsFullPagePlugin())
2656 return;
2657 container()->zoomLevelChanged(content::ZoomFactorToZoomLevel(factor));
2660 void PepperPluginInstanceImpl::ZoomLimitsChanged(PP_Instance instance,
2661 double minimum_factor,
2662 double maximum_factor) {
2663 if (!render_frame_)
2664 return;
2665 if (minimum_factor > maximum_factor) {
2666 NOTREACHED();
2667 return;
2669 double minimum_level = ZoomFactorToZoomLevel(minimum_factor);
2670 double maximum_level = ZoomFactorToZoomLevel(maximum_factor);
2671 render_frame_->render_view()->webview()->zoomLimitsChanged(minimum_level,
2672 maximum_level);
2675 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2676 PP_Var message) {
2677 PostMessageToJavaScript(message);
2680 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2681 PP_MouseCursor_Type type,
2682 PP_Resource image,
2683 const PP_Point* hot_spot) {
2684 if (!ValidateSetCursorParams(type, image, hot_spot))
2685 return PP_FALSE;
2687 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2688 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2689 return PP_TRUE;
2692 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2693 if (enter.failed())
2694 return PP_FALSE;
2695 PPB_ImageData_Impl* image_data =
2696 static_cast<PPB_ImageData_Impl*>(enter.object());
2698 ImageDataAutoMapper auto_mapper(image_data);
2699 if (!auto_mapper.is_valid())
2700 return PP_FALSE;
2702 scoped_ptr<WebCursorInfo> custom_cursor(
2703 new WebCursorInfo(WebCursorInfo::TypeCustom));
2704 custom_cursor->hotSpot.x = hot_spot->x;
2705 custom_cursor->hotSpot.y = hot_spot->y;
2707 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2708 // Make a deep copy, so that the cursor remains valid even after the original
2709 // image data gets freed.
2710 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2711 return PP_FALSE;
2714 DoSetCursor(custom_cursor.release());
2715 return PP_TRUE;
2718 int32_t PepperPluginInstanceImpl::LockMouse(
2719 PP_Instance instance,
2720 scoped_refptr<TrackedCallback> callback) {
2721 if (TrackedCallback::IsPending(lock_mouse_callback_))
2722 return PP_ERROR_INPROGRESS;
2724 if (IsMouseLocked())
2725 return PP_OK;
2727 if (!CanAccessMainFrame())
2728 return PP_ERROR_NOACCESS;
2730 if (!IsProcessingUserGesture())
2731 return PP_ERROR_NO_USER_GESTURE;
2733 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2734 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2735 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2736 // Open a user gesture here so the Webkit user gesture checks will succeed
2737 // for out-of-process plugins.
2738 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2739 if (!LockMouse())
2740 return PP_ERROR_FAILED;
2743 // Either mouselock succeeded or a Flash fullscreen is pending.
2744 lock_mouse_callback_ = callback;
2745 return PP_OK_COMPLETIONPENDING;
2748 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2749 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2752 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2753 PP_TextInput_Type type) {
2754 if (!render_frame_)
2755 return;
2756 int itype = type;
2757 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2758 itype = ui::TEXT_INPUT_TYPE_NONE;
2759 SetTextInputType(static_cast<ui::TextInputType>(itype));
2762 void PepperPluginInstanceImpl::UpdateCaretPosition(
2763 PP_Instance instance,
2764 const PP_Rect& caret,
2765 const PP_Rect& bounding_box) {
2766 if (!render_frame_)
2767 return;
2768 text_input_caret_ = PP_ToGfxRect(caret);
2769 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2770 text_input_caret_set_ = true;
2771 render_frame_->PepperCaretPositionChanged(this);
2774 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2775 if (render_frame_)
2776 render_frame_->PepperCancelComposition(this);
2779 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2780 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2781 // It can be optimized so that it won't call it back until the information
2782 // is really needed.
2784 // Avoid calling in nested context or else this will reenter the plugin. This
2785 // uses a weak pointer rather than exploiting the fact that this class is
2786 // refcounted because we don't actually want this operation to affect the
2787 // lifetime of the instance.
2788 base::MessageLoop::current()->PostTask(
2789 FROM_HERE,
2790 base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2791 weak_factory_.GetWeakPtr(),
2792 static_cast<size_t>(kExtraCharsForTextInput)));
2795 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2796 const char* text,
2797 uint32_t caret,
2798 uint32_t anchor) {
2799 if (!render_frame_)
2800 return;
2801 surrounding_text_ = text;
2802 selection_caret_ = caret;
2803 selection_anchor_ = anchor;
2804 render_frame_->PepperSelectionChanged(this);
2807 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2808 PP_Instance instance,
2809 PP_Var relative,
2810 PP_URLComponents_Dev* components) {
2811 StringVar* relative_string = StringVar::FromPPVar(relative);
2812 if (!relative_string)
2813 return PP_MakeNull();
2815 WebElement plugin_element = container()->element();
2816 GURL document_url = plugin_element.document().baseURL();
2817 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2818 document_url.Resolve(relative_string->value()), components);
2821 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2822 PP_Var url) {
2823 StringVar* url_string = StringVar::FromPPVar(url);
2824 if (!url_string)
2825 return PP_FALSE;
2827 blink::WebSecurityOrigin security_origin;
2828 if (!SecurityOriginForInstance(instance, &security_origin))
2829 return PP_FALSE;
2831 GURL gurl(url_string->value());
2832 if (!gurl.is_valid())
2833 return PP_FALSE;
2835 return PP_FromBool(security_origin.canRequest(gurl));
2838 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2839 PP_Instance instance,
2840 PP_Instance target) {
2841 blink::WebSecurityOrigin our_origin;
2842 if (!SecurityOriginForInstance(instance, &our_origin))
2843 return PP_FALSE;
2845 blink::WebSecurityOrigin target_origin;
2846 if (!SecurityOriginForInstance(instance, &target_origin))
2847 return PP_FALSE;
2849 return PP_FromBool(our_origin.canAccess(target_origin));
2852 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2853 PP_Instance instance,
2854 PP_URLComponents_Dev* components) {
2855 blink::WebDocument document = container()->element().document();
2856 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2857 components);
2860 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2861 PP_Instance instance,
2862 PP_URLComponents_Dev* components) {
2863 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2866 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2867 PP_Instance instance,
2868 PP_URLComponents_Dev* components) {
2869 blink::WebDocument document = container()->element().document();
2870 if (!full_frame_)
2871 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2872 components);
2873 WebLocalFrame* frame = document.frame();
2874 if (!frame)
2875 return PP_MakeUndefined();
2876 const WebURLRequest& request = frame->dataSource()->originalRequest();
2877 WebString referer = request.httpHeaderField("Referer");
2878 if (referer.isEmpty())
2879 return PP_MakeUndefined();
2880 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2881 components);
2884 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2885 scoped_refptr<PluginModule> module) {
2886 // Save the original module and switch over to the new one now that this
2887 // plugin is using the IPC-based proxy.
2888 original_module_ = module_;
2889 module_ = module;
2891 // For NaCl instances, remember the NaCl plugin instance interface, so we
2892 // can shut it down by calling its DidDestroy in our Delete() method.
2893 original_instance_interface_.reset(instance_interface_.release());
2895 base::Callback<const void*(const char*)> get_plugin_interface_func =
2896 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2897 PPP_Instance_Combined* ppp_instance_combined =
2898 PPP_Instance_Combined::Create(get_plugin_interface_func);
2899 if (!ppp_instance_combined) {
2900 // The proxy must support at least one usable PPP_Instance interface.
2901 // While this could be a failure to implement the interface in the NaCl
2902 // module, it is more likely that the NaCl process has crashed. Either
2903 // way, report that module initialization failed.
2904 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2907 instance_interface_.reset(ppp_instance_combined);
2908 // Clear all PPP interfaces we may have cached.
2909 plugin_find_interface_ = NULL;
2910 plugin_input_event_interface_ = NULL;
2911 checked_for_plugin_input_event_interface_ = false;
2912 plugin_mouse_lock_interface_ = NULL;
2913 plugin_pdf_interface_ = NULL;
2914 checked_for_plugin_pdf_interface_ = false;
2915 plugin_private_interface_ = NULL;
2916 plugin_textinput_interface_ = NULL;
2917 plugin_zoom_interface_ = NULL;
2919 // Re-send the DidCreate event via the proxy.
2920 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2921 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2922 if (!instance_interface_->DidCreate(
2923 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2924 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2925 if (message_channel_)
2926 message_channel_->Start();
2928 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2929 // event. This way, SendDidChangeView will send the "current" view
2930 // immediately (before other events like HandleDocumentLoad).
2931 sent_initial_did_change_view_ = false;
2932 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2933 SendDidChangeView();
2935 DCHECK(external_document_load_);
2936 external_document_load_ = false;
2937 if (!external_document_response_.isNull()) {
2938 document_loader_ = NULL;
2939 // Pass the response to the new proxy.
2940 HandleDocumentLoad(external_document_response_);
2941 external_document_response_ = blink::WebURLResponse();
2942 // Replay any document load events we've received to the real loader.
2943 external_document_loader_->ReplayReceivedData(document_loader_);
2944 external_document_loader_.reset(NULL);
2947 return PP_EXTERNAL_PLUGIN_OK;
2950 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2951 DCHECK(module);
2952 return module == module_.get() || module == original_module_.get();
2955 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2956 return HostGlobals::Get()->GetInstance(instance_id);
2959 RenderView* PepperPluginInstanceImpl::GetRenderView() {
2960 return render_frame_ ? render_frame_->render_view() : NULL;
2963 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2964 return container_;
2967 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
2969 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
2970 return HostGlobals::Get()->GetVarTracker();
2973 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
2975 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
2976 return module_->path();
2979 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
2980 float scale) {
2981 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
2983 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
2984 return 0;
2986 scoped_refptr<PPB_ImageData_Impl> image_data(
2987 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
2988 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
2989 image_skia_rep.pixel_width(),
2990 image_skia_rep.pixel_height(),
2991 false)) {
2992 return 0;
2995 ImageDataAutoMapper mapper(image_data.get());
2996 if (!mapper.is_valid())
2997 return 0;
2999 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
3000 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
3001 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
3002 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
3004 return image_data->GetReference();
3007 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
3008 const base::FilePath& file_path,
3009 ppapi::PpapiPermissions permissions,
3010 const IPC::ChannelHandle& channel_handle,
3011 base::ProcessId plugin_pid,
3012 int plugin_child_id) {
3013 // Create a new module for each instance of the external plugin that is using
3014 // the IPC based out-of-process proxy. We can't use the existing module,
3015 // because it is configured for the in-process plugin, and we must keep it
3016 // that way to allow the page to create other instances.
3017 scoped_refptr<PluginModule> external_plugin_module(
3018 module_->CreateModuleForExternalPluginInstance());
3020 RendererPpapiHostImpl* renderer_ppapi_host =
3021 external_plugin_module->CreateOutOfProcessModule(render_frame_,
3022 file_path,
3023 permissions,
3024 channel_handle,
3025 plugin_pid,
3026 plugin_child_id,
3027 true);
3028 if (!renderer_ppapi_host) {
3029 DLOG(ERROR) << "CreateExternalPluginModule() failed";
3030 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
3033 // Finally, switch the instance to the proxy.
3034 return external_plugin_module->InitAsProxiedExternalPlugin(this);
3037 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3038 always_on_top_ = on_top;
3041 void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
3042 cursor_.reset(cursor);
3043 if (fullscreen_container_) {
3044 fullscreen_container_->DidChangeCursor(*cursor);
3045 } else if (render_frame_) {
3046 render_frame_->PepperDidChangeCursor(this, *cursor);
3050 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3051 WebLocalFrame* frame = container()->element().document().frame();
3052 return frame->view()->mainFrame()->document().isPluginDocument();
3055 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3056 bool delay_report) {
3057 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3058 // Keep a reference on the stack. See NOTE above.
3059 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3061 // We check whether we are trying to switch to the state we're already going
3062 // to (i.e. if we're already switching to fullscreen but the fullscreen
3063 // container isn't ready yet, don't do anything more).
3064 if (fullscreen == FlashIsFullscreenOrPending())
3065 return true;
3067 if (!render_frame_)
3068 return false;
3069 if (fullscreen && !render_frame_->render_view()
3070 ->renderer_preferences()
3071 .plugin_fullscreen_allowed)
3072 return false;
3074 // Unbind current 2D or 3D graphics context.
3075 VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3076 if (fullscreen) {
3077 DCHECK(!fullscreen_container_);
3078 fullscreen_container_ =
3079 render_frame_->CreatePepperFullscreenContainer(this);
3080 UpdateLayer(false);
3081 } else {
3082 DCHECK(fullscreen_container_);
3083 fullscreen_container_->Destroy();
3084 fullscreen_container_ = NULL;
3085 UpdateFlashFullscreenState(false);
3086 if (!delay_report) {
3087 ReportGeometry();
3088 } else {
3089 base::MessageLoop::current()->PostTask(
3090 FROM_HERE,
3091 base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3095 return true;
3098 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3099 if (flash_fullscreen_)
3100 return true;
3102 return container_->isRectTopmost(rect);
3105 int32_t PepperPluginInstanceImpl::Navigate(
3106 const ppapi::URLRequestInfoData& request,
3107 const char* target,
3108 bool from_user_action) {
3109 if (!container_)
3110 return PP_ERROR_FAILED;
3112 WebDocument document = container_->element().document();
3113 WebLocalFrame* frame = document.frame();
3114 if (!frame)
3115 return PP_ERROR_FAILED;
3117 ppapi::URLRequestInfoData completed_request = request;
3119 WebURLRequest web_request;
3120 if (!CreateWebURLRequest(
3121 pp_instance_, &completed_request, frame, &web_request)) {
3122 return PP_ERROR_FAILED;
3124 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3125 web_request.setHasUserGesture(from_user_action);
3127 GURL gurl(web_request.url());
3128 if (gurl.SchemeIs(url::kJavaScriptScheme)) {
3129 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3130 // allowed for security reasons.
3131 WebFrame* target_frame =
3132 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3133 if (target_frame != frame)
3134 return PP_ERROR_NOACCESS;
3136 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3137 // need that?
3138 WebString result = container_->executeScriptURL(gurl, from_user_action);
3139 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3142 // Only GETs and POSTs are supported.
3143 if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3144 return PP_ERROR_BADARGUMENT;
3146 WebString target_str = WebString::fromUTF8(target);
3147 container_->loadFrameRequest(web_request, target_str, false, NULL);
3148 return PP_OK;
3151 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3152 const base::FilePath& path) {
3153 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3154 PepperFileRefRendererHost* file_ref_host(
3155 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3156 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3157 scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3160 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3161 if (message_channel_)
3162 message_channel_->SetReadOnlyProperty(key, value);
3165 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3166 if (!container_)
3167 return false;
3168 blink::WebDocument containing_document = container_->element().document();
3170 if (!containing_document.frame() || !containing_document.frame()->view() ||
3171 !containing_document.frame()->view()->mainFrame()) {
3172 return false;
3174 blink::WebDocument main_document =
3175 containing_document.frame()->view()->mainFrame()->document();
3177 return containing_document.securityOrigin().canAccess(
3178 main_document.securityOrigin());
3181 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3182 WebElement element = container_->element();
3183 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3184 height_before_fullscreen_ =
3185 element.getAttribute(WebString::fromUTF8(kHeight));
3186 border_before_fullscreen_ =
3187 element.getAttribute(WebString::fromUTF8(kBorder));
3188 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3191 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3192 if (!render_frame_)
3193 return;
3194 blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3195 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3196 std::string width = StringPrintf("%d", screen_size_for_fullscreen_.width());
3197 std::string height = StringPrintf("%d", screen_size_for_fullscreen_.height());
3199 WebElement element = container_->element();
3200 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3201 element.setAttribute(WebString::fromUTF8(kHeight),
3202 WebString::fromUTF8(height));
3203 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3205 // There should be no style settings that matter in fullscreen mode,
3206 // so just replace them instead of appending.
3207 // NOTE: "position: fixed" and "display: block" reset the plugin and
3208 // using %% settings might not work without them (e.g. if the plugin is a
3209 // child of a container element).
3210 std::string style;
3211 style += StringPrintf("width: %s !important; ", width.c_str());
3212 style += StringPrintf("height: %s !important; ", height.c_str());
3213 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3214 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3217 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3218 screen_size_for_fullscreen_ = gfx::Size();
3219 WebElement element = container_->element();
3220 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3221 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3222 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3223 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3226 bool PepperPluginInstanceImpl::IsMouseLocked() {
3227 return GetMouseLockDispatcher()->IsMouseLockedTo(
3228 GetOrCreateLockTargetAdapter());
3231 bool PepperPluginInstanceImpl::LockMouse() {
3232 return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3235 MouseLockDispatcher::LockTarget*
3236 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3237 if (!lock_target_.get()) {
3238 lock_target_.reset(new PluginInstanceLockTarget(this));
3240 return lock_target_.get();
3243 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3244 if (flash_fullscreen_) {
3245 RenderWidgetFullscreenPepper* container =
3246 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3247 return container->mouse_lock_dispatcher();
3248 } else if (render_frame_) {
3249 return render_frame_->render_view()->mouse_lock_dispatcher();
3251 return NULL;
3254 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3255 if (lock_target_.get()) {
3256 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3257 lock_target_.reset();
3261 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3262 const blink::WebURLResponse& response,
3263 int pending_host_id,
3264 const ppapi::URLResponseInfoData& data) {
3265 if (is_deleted_)
3266 return;
3268 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3270 if (host_impl->in_process_router()) {
3271 // Running in-process, we can just create the resource and call the
3272 // PPP_Instance function directly.
3273 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3274 new ppapi::proxy::URLLoaderResource(
3275 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3276 pp_instance(),
3277 pending_host_id,
3278 data));
3280 PP_Resource loader_pp_resource = loader_resource->GetReference();
3281 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3282 loader_pp_resource))
3283 loader_resource->Close();
3284 // We don't pass a ref into the plugin, if it wants one, it will have taken
3285 // an additional one.
3286 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3287 loader_pp_resource);
3288 } else {
3289 // Running out-of-process. Initiate an IPC call to notify the plugin
3290 // process.
3291 ppapi::proxy::HostDispatcher* dispatcher =
3292 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3293 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3294 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3298 bool PepperPluginInstanceImpl::IsPeripheralContent() const {
3299 if (module_->name() != kFlashPluginName)
3300 return false;
3302 // Peripheral plugin content is defined to be peripheral when the plugin
3303 // content's origin differs from the top level frame's origin. For example:
3304 // - Peripheral: a.com -> b.com/plugin.swf
3305 // - Peripheral: a.com -> b.com/iframe.html -> b.com/plugin.swf
3306 // - NOT peripheral: a.com -> b.com/iframe-to-a.html -> a.com/plugin.swf
3308 // TODO(alexmos): Update this to use the origin of the RemoteFrame when 426512
3309 // is fixed. For now, case 3 in the comment above doesn't work in
3310 // --site-per-process mode.
3311 WebFrame* main_frame = render_frame_->GetWebFrame()->view()->mainFrame();
3312 if (main_frame->isWebRemoteFrame())
3313 return true;
3315 GURL main_frame_url = main_frame->document().url();
3316 return plugin_url_.GetOrigin() != main_frame_url.GetOrigin();
3319 void PepperPluginInstanceImpl::SetPluginThrottled(bool throttled) {
3320 // Do not throttle if we've already disabled power saver.
3321 if (!power_saver_enabled_ && throttled)
3322 return;
3324 plugin_throttled_ = throttled;
3325 SendDidChangeView();
3328 } // namespace content