[ServiceWorker] Implement WebServiceWorkerContextClient::openWindow().
[chromium-blink-merge.git] / content / renderer / pepper / pepper_plugin_instance_impl.cc
blobcc76c798800c50ad16e24b59c8ca8c493fbcb7a7
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
7 #include "base/bind.h"
8 #include "base/callback_helpers.h"
9 #include "base/logging.h"
10 #include "base/memory/linked_ptr.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/stl_util.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/strings/utf_offset_string_conversions.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/time/time.h"
17 #include "base/trace_event/trace_event.h"
18 #include "cc/base/latency_info_swap_promise.h"
19 #include "cc/blink/web_layer_impl.h"
20 #include "cc/layers/texture_layer.h"
21 #include "cc/trees/layer_tree_host.h"
22 #include "content/common/content_constants_internal.h"
23 #include "content/common/frame_messages.h"
24 #include "content/common/input/web_input_event_traits.h"
25 #include "content/public/common/content_constants.h"
26 #include "content/public/common/page_zoom.h"
27 #include "content/public/renderer/content_renderer_client.h"
28 #include "content/renderer/gpu/render_widget_compositor.h"
29 #include "content/renderer/pepper/content_decryptor_delegate.h"
30 #include "content/renderer/pepper/event_conversion.h"
31 #include "content/renderer/pepper/fullscreen_container.h"
32 #include "content/renderer/pepper/gfx_conversion.h"
33 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
34 #include "content/renderer/pepper/host_globals.h"
35 #include "content/renderer/pepper/message_channel.h"
36 #include "content/renderer/pepper/pepper_browser_connection.h"
37 #include "content/renderer/pepper/pepper_compositor_host.h"
38 #include "content/renderer/pepper/pepper_file_ref_renderer_host.h"
39 #include "content/renderer/pepper/pepper_graphics_2d_host.h"
40 #include "content/renderer/pepper/pepper_in_process_router.h"
41 #include "content/renderer/pepper/pepper_plugin_instance_metrics.h"
42 #include "content/renderer/pepper/pepper_try_catch.h"
43 #include "content/renderer/pepper/pepper_url_loader_host.h"
44 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
45 #include "content/renderer/pepper/plugin_module.h"
46 #include "content/renderer/pepper/plugin_object.h"
47 #include "content/renderer/pepper/ppapi_preferences_builder.h"
48 #include "content/renderer/pepper/ppb_buffer_impl.h"
49 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
50 #include "content/renderer/pepper/ppb_image_data_impl.h"
51 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
52 #include "content/renderer/pepper/url_request_info_util.h"
53 #include "content/renderer/pepper/url_response_info_util.h"
54 #include "content/renderer/render_frame_impl.h"
55 #include "content/renderer/render_thread_impl.h"
56 #include "content/renderer/render_view_impl.h"
57 #include "content/renderer/render_widget.h"
58 #include "content/renderer/render_widget_fullscreen_pepper.h"
59 #include "content/renderer/sad_plugin.h"
60 #include "media/base/audio_hardware_config.h"
61 #include "ppapi/c/dev/ppb_zoom_dev.h"
62 #include "ppapi/c/dev/ppp_selection_dev.h"
63 #include "ppapi/c/dev/ppp_text_input_dev.h"
64 #include "ppapi/c/dev/ppp_zoom_dev.h"
65 #include "ppapi/c/pp_rect.h"
66 #include "ppapi/c/ppb_audio_config.h"
67 #include "ppapi/c/ppb_core.h"
68 #include "ppapi/c/ppb_gamepad.h"
69 #include "ppapi/c/ppp_input_event.h"
70 #include "ppapi/c/ppp_instance.h"
71 #include "ppapi/c/ppp_messaging.h"
72 #include "ppapi/c/ppp_mouse_lock.h"
73 #include "ppapi/c/private/ppb_find_private.h"
74 #include "ppapi/c/private/ppp_find_private.h"
75 #include "ppapi/c/private/ppp_instance_private.h"
76 #include "ppapi/c/private/ppp_pdf.h"
77 #include "ppapi/host/ppapi_host.h"
78 #include "ppapi/proxy/ppapi_messages.h"
79 #include "ppapi/proxy/serialized_var.h"
80 #include "ppapi/proxy/uma_private_resource.h"
81 #include "ppapi/proxy/url_loader_resource.h"
82 #include "ppapi/shared_impl/ppapi_permissions.h"
83 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
84 #include "ppapi/shared_impl/ppb_input_event_shared.h"
85 #include "ppapi/shared_impl/ppb_url_util_shared.h"
86 #include "ppapi/shared_impl/ppb_view_shared.h"
87 #include "ppapi/shared_impl/ppp_instance_combined.h"
88 #include "ppapi/shared_impl/resource.h"
89 #include "ppapi/shared_impl/scoped_pp_resource.h"
90 #include "ppapi/shared_impl/scoped_pp_var.h"
91 #include "ppapi/shared_impl/time_conversion.h"
92 #include "ppapi/shared_impl/url_request_info_data.h"
93 #include "ppapi/shared_impl/var.h"
94 #include "ppapi/thunk/enter.h"
95 #include "ppapi/thunk/ppb_buffer_api.h"
96 #include "printing/metafile_skia_wrapper.h"
97 #include "printing/pdf_metafile_skia.h"
98 #include "skia/ext/platform_canvas.h"
99 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
100 #include "third_party/WebKit/public/platform/WebGamepads.h"
101 #include "third_party/WebKit/public/platform/WebRect.h"
102 #include "third_party/WebKit/public/platform/WebString.h"
103 #include "third_party/WebKit/public/platform/WebURL.h"
104 #include "third_party/WebKit/public/platform/WebURLError.h"
105 #include "third_party/WebKit/public/platform/WebURLRequest.h"
106 #include "third_party/WebKit/public/web/WebBindings.h"
107 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
108 #include "third_party/WebKit/public/web/WebDataSource.h"
109 #include "third_party/WebKit/public/web/WebDocument.h"
110 #include "third_party/WebKit/public/web/WebInputEvent.h"
111 #include "third_party/WebKit/public/web/WebLocalFrame.h"
112 #include "third_party/WebKit/public/web/WebPluginContainer.h"
113 #include "third_party/WebKit/public/web/WebPrintParams.h"
114 #include "third_party/WebKit/public/web/WebPrintPresetOptions.h"
115 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
116 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
117 #include "third_party/WebKit/public/web/WebScriptSource.h"
118 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
119 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
120 #include "third_party/WebKit/public/web/WebView.h"
121 #include "third_party/khronos/GLES2/gl2.h"
122 #include "ui/gfx/image/image_skia.h"
123 #include "ui/gfx/image/image_skia_rep.h"
124 #include "ui/gfx/range/range.h"
125 #include "v8/include/v8.h"
127 #if defined(OS_CHROMEOS)
128 #include "ui/events/keycodes/keyboard_codes_posix.h"
129 #endif
131 using base::StringPrintf;
132 using ppapi::InputEventData;
133 using ppapi::PpapiGlobals;
134 using ppapi::PPB_InputEvent_Shared;
135 using ppapi::PPB_View_Shared;
136 using ppapi::PPP_Instance_Combined;
137 using ppapi::Resource;
138 using ppapi::ScopedPPResource;
139 using ppapi::ScopedPPVar;
140 using ppapi::StringVar;
141 using ppapi::TrackedCallback;
142 using ppapi::thunk::EnterResourceNoLock;
143 using ppapi::thunk::PPB_Buffer_API;
144 using ppapi::thunk::PPB_Gamepad_API;
145 using ppapi::thunk::PPB_Graphics2D_API;
146 using ppapi::thunk::PPB_Graphics3D_API;
147 using ppapi::thunk::PPB_ImageData_API;
148 using ppapi::Var;
149 using ppapi::ArrayBufferVar;
150 using ppapi::ViewData;
151 using blink::WebBindings;
152 using blink::WebCanvas;
153 using blink::WebCursorInfo;
154 using blink::WebDocument;
155 using blink::WebElement;
156 using blink::WebFrame;
157 using blink::WebInputEvent;
158 using blink::WebLocalFrame;
159 using blink::WebPlugin;
160 using blink::WebPluginContainer;
161 using blink::WebPrintParams;
162 using blink::WebPrintScalingOption;
163 using blink::WebScopedUserGesture;
164 using blink::WebString;
165 using blink::WebURLError;
166 using blink::WebURLLoader;
167 using blink::WebURLLoaderClient;
168 using blink::WebURLRequest;
169 using blink::WebURLResponse;
170 using blink::WebUserGestureIndicator;
171 using blink::WebUserGestureToken;
172 using blink::WebView;
174 namespace content {
176 namespace {
178 #define STATIC_ASSERT_PP_MATCHING_ENUM(a, b) \
179 static_assert(static_cast<int>(a) == static_cast<int>(b), \
180 "mismatching enums: " #a)
182 // Check PP_TextInput_Type and ui::TextInputType are kept in sync.
183 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_NONE,
184 PP_TEXTINPUT_TYPE_NONE);
185 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_TEXT,
186 PP_TEXTINPUT_TYPE_TEXT);
187 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_PASSWORD,
188 PP_TEXTINPUT_TYPE_PASSWORD);
189 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_SEARCH,
190 PP_TEXTINPUT_TYPE_SEARCH);
191 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_EMAIL,
192 PP_TEXTINPUT_TYPE_EMAIL);
193 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_NUMBER,
194 PP_TEXTINPUT_TYPE_NUMBER);
195 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_TELEPHONE,
196 PP_TEXTINPUT_TYPE_TELEPHONE);
197 STATIC_ASSERT_PP_MATCHING_ENUM(ui::TEXT_INPUT_TYPE_URL,
198 PP_TEXTINPUT_TYPE_URL);
200 // The default text input type is to regard the plugin always accept text input.
201 // This is for allowing users to use input methods even on completely-IME-
202 // unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
203 // Plugins need to explicitly opt out the text input mode if they know
204 // that they don't accept texts.
205 const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
207 // <embed>/<object> attributes.
208 const char kWidth[] = "width";
209 const char kHeight[] = "height";
210 const char kBorder[] = "border"; // According to w3c, deprecated.
211 const char kStyle[] = "style";
213 #define STATIC_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
214 static_assert(static_cast<int>(WebCursorInfo::webkit_name) == \
215 static_cast<int>(np_name), \
216 "mismatching enums: " #webkit_name)
218 STATIC_ASSERT_MATCHING_ENUM(TypePointer, PP_MOUSECURSOR_TYPE_POINTER);
219 STATIC_ASSERT_MATCHING_ENUM(TypeCross, PP_MOUSECURSOR_TYPE_CROSS);
220 STATIC_ASSERT_MATCHING_ENUM(TypeHand, PP_MOUSECURSOR_TYPE_HAND);
221 STATIC_ASSERT_MATCHING_ENUM(TypeIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
222 STATIC_ASSERT_MATCHING_ENUM(TypeWait, PP_MOUSECURSOR_TYPE_WAIT);
223 STATIC_ASSERT_MATCHING_ENUM(TypeHelp, PP_MOUSECURSOR_TYPE_HELP);
224 STATIC_ASSERT_MATCHING_ENUM(TypeEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
225 STATIC_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
226 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastResize,
227 PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
228 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestResize,
229 PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
230 STATIC_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
231 STATIC_ASSERT_MATCHING_ENUM(TypeSouthEastResize,
232 PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
233 STATIC_ASSERT_MATCHING_ENUM(TypeSouthWestResize,
234 PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
235 STATIC_ASSERT_MATCHING_ENUM(TypeWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
236 STATIC_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
237 PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
238 STATIC_ASSERT_MATCHING_ENUM(TypeEastWestResize,
239 PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
240 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
241 PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
242 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
243 PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
244 STATIC_ASSERT_MATCHING_ENUM(TypeColumnResize,
245 PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
246 STATIC_ASSERT_MATCHING_ENUM(TypeRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
247 STATIC_ASSERT_MATCHING_ENUM(TypeMiddlePanning,
248 PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
249 STATIC_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
250 STATIC_ASSERT_MATCHING_ENUM(TypeNorthPanning,
251 PP_MOUSECURSOR_TYPE_NORTHPANNING);
252 STATIC_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
253 PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
254 STATIC_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
255 PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
256 STATIC_ASSERT_MATCHING_ENUM(TypeSouthPanning,
257 PP_MOUSECURSOR_TYPE_SOUTHPANNING);
258 STATIC_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
259 PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
260 STATIC_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
261 PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
262 STATIC_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
263 STATIC_ASSERT_MATCHING_ENUM(TypeMove, PP_MOUSECURSOR_TYPE_MOVE);
264 STATIC_ASSERT_MATCHING_ENUM(TypeVerticalText,
265 PP_MOUSECURSOR_TYPE_VERTICALTEXT);
266 STATIC_ASSERT_MATCHING_ENUM(TypeCell, PP_MOUSECURSOR_TYPE_CELL);
267 STATIC_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
268 STATIC_ASSERT_MATCHING_ENUM(TypeAlias, PP_MOUSECURSOR_TYPE_ALIAS);
269 STATIC_ASSERT_MATCHING_ENUM(TypeProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
270 STATIC_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
271 STATIC_ASSERT_MATCHING_ENUM(TypeCopy, PP_MOUSECURSOR_TYPE_COPY);
272 STATIC_ASSERT_MATCHING_ENUM(TypeNone, PP_MOUSECURSOR_TYPE_NONE);
273 STATIC_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
274 STATIC_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
275 STATIC_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
276 STATIC_ASSERT_MATCHING_ENUM(TypeGrab, PP_MOUSECURSOR_TYPE_GRAB);
277 STATIC_ASSERT_MATCHING_ENUM(TypeGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
278 // Do not assert WebCursorInfo::TypeCustom == PP_CURSORTYPE_CUSTOM;
279 // PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
281 STATIC_ASSERT_PP_MATCHING_ENUM(blink::WebPrintScalingOptionNone,
282 PP_PRINTSCALINGOPTION_NONE);
283 STATIC_ASSERT_PP_MATCHING_ENUM(
284 blink::WebPrintScalingOptionFitToPrintableArea,
285 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
286 STATIC_ASSERT_PP_MATCHING_ENUM(
287 blink::WebPrintScalingOptionSourceSize,
288 PP_PRINTSCALINGOPTION_SOURCE_SIZE);
290 // Sets |*security_origin| to be the WebKit security origin associated with the
291 // document containing the given plugin instance. On success, returns true. If
292 // the instance is invalid, returns false and |*security_origin| will be
293 // unchanged.
294 bool SecurityOriginForInstance(PP_Instance instance_id,
295 blink::WebSecurityOrigin* security_origin) {
296 PepperPluginInstanceImpl* instance =
297 HostGlobals::Get()->GetInstance(instance_id);
298 if (!instance)
299 return false;
301 WebElement plugin_element = instance->container()->element();
302 *security_origin = plugin_element.document().securityOrigin();
303 return true;
306 // Convert the given vector to an array of C-strings. The strings in the
307 // returned vector are only guaranteed valid so long as the vector of strings
308 // is not modified.
309 scoped_ptr<const char* []> StringVectorToArgArray(
310 const std::vector<std::string>& vector) {
311 scoped_ptr<const char * []> array(new const char* [vector.size()]);
312 for (size_t i = 0; i < vector.size(); ++i)
313 array[i] = vector[i].c_str();
314 return array.Pass();
317 // Returns true if this is a "system reserved" key which should not be sent to
318 // a plugin. Some poorly behaving plugins (like Flash) incorrectly report that
319 // they handle all keys sent to them. This can prevent keystrokes from working
320 // for things like screen brightness and volume control.
321 bool IsReservedSystemInputEvent(const blink::WebInputEvent& event) {
322 #if defined(OS_CHROMEOS)
323 if (event.type != WebInputEvent::KeyDown &&
324 event.type != WebInputEvent::KeyUp)
325 return false;
326 const blink::WebKeyboardEvent& key_event =
327 static_cast<const blink::WebKeyboardEvent&>(event);
328 switch (key_event.windowsKeyCode) {
329 case ui::VKEY_BRIGHTNESS_DOWN:
330 case ui::VKEY_BRIGHTNESS_UP:
331 case ui::VKEY_KBD_BRIGHTNESS_DOWN:
332 case ui::VKEY_KBD_BRIGHTNESS_UP:
333 case ui::VKEY_VOLUME_MUTE:
334 case ui::VKEY_VOLUME_DOWN:
335 case ui::VKEY_VOLUME_UP:
336 return true;
337 default:
338 return false;
340 #endif // defined(OS_CHROMEOS)
341 return false;
344 class PluginInstanceLockTarget : public MouseLockDispatcher::LockTarget {
345 public:
346 PluginInstanceLockTarget(PepperPluginInstanceImpl* plugin)
347 : plugin_(plugin) {}
349 void OnLockMouseACK(bool succeeded) override {
350 plugin_->OnLockMouseACK(succeeded);
353 void OnMouseLockLost() override { plugin_->OnMouseLockLost(); }
355 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
356 plugin_->HandleMouseLockedInputEvent(event);
357 return true;
360 private:
361 PepperPluginInstanceImpl* plugin_;
364 void InitLatencyInfo(ui::LatencyInfo* new_latency,
365 const ui::LatencyInfo* old_latency,
366 blink::WebInputEvent::Type type,
367 int64 input_sequence) {
368 new_latency->AddLatencyNumber(
369 ui::INPUT_EVENT_LATENCY_BEGIN_PLUGIN_COMPONENT,
371 input_sequence);
372 new_latency->TraceEventType(WebInputEventTraits::GetName(type));
373 if (old_latency) {
374 new_latency->CopyLatencyFrom(*old_latency,
375 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
376 new_latency->CopyLatencyFrom(*old_latency,
377 ui::INPUT_EVENT_LATENCY_UI_COMPONENT);
381 } // namespace
383 // static
384 PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
385 RenderFrameImpl* render_frame,
386 PluginModule* module,
387 WebPluginContainer* container,
388 const GURL& plugin_url) {
389 base::Callback<const void*(const char*)> get_plugin_interface_func =
390 base::Bind(&PluginModule::GetPluginInterface, module);
391 PPP_Instance_Combined* ppp_instance_combined =
392 PPP_Instance_Combined::Create(get_plugin_interface_func);
393 if (!ppp_instance_combined)
394 return NULL;
396 return new PepperPluginInstanceImpl(render_frame,
397 module,
398 ppp_instance_combined,
399 container,
400 plugin_url);
403 PepperPluginInstanceImpl::ExternalDocumentLoader::ExternalDocumentLoader()
404 : finished_loading_(false) {}
406 PepperPluginInstanceImpl::ExternalDocumentLoader::~ExternalDocumentLoader() {}
408 void PepperPluginInstanceImpl::ExternalDocumentLoader::ReplayReceivedData(
409 WebURLLoaderClient* document_loader) {
410 for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
411 ++it) {
412 document_loader->didReceiveData(
413 NULL, it->c_str(), it->length(), 0 /* encoded_data_length */);
415 if (finished_loading_) {
416 document_loader->didFinishLoading(
417 NULL,
418 0 /* finish_time */,
419 blink::WebURLLoaderClient::kUnknownEncodedDataLength);
421 if (error_.get()) {
422 document_loader->didFail(NULL, *error_);
426 void PepperPluginInstanceImpl::ExternalDocumentLoader::didReceiveData(
427 WebURLLoader* loader,
428 const char* data,
429 int data_length,
430 int encoded_data_length) {
431 data_.push_back(std::string(data, data_length));
434 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFinishLoading(
435 WebURLLoader* loader,
436 double finish_time,
437 int64_t total_encoded_data_length) {
438 DCHECK(!finished_loading_);
439 finished_loading_ = true;
442 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFail(
443 WebURLLoader* loader,
444 const WebURLError& error) {
445 DCHECK(!error_.get());
446 error_.reset(new WebURLError(error));
449 PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
450 : Resource(ppapi::Resource::Untracked()) {}
452 PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
454 PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
455 return this;
458 void PepperPluginInstanceImpl::GamepadImpl::Sample(
459 PP_Instance instance,
460 PP_GamepadsSampleData* data) {
461 blink::WebGamepads webkit_data;
462 RenderThreadImpl::current()->SampleGamepads(&webkit_data);
463 ConvertWebKitGamepadData(bit_cast<ppapi::WebKitGamepads>(webkit_data), data);
466 PepperPluginInstanceImpl::PepperPluginInstanceImpl(
467 RenderFrameImpl* render_frame,
468 PluginModule* module,
469 ppapi::PPP_Instance_Combined* instance_interface,
470 WebPluginContainer* container,
471 const GURL& plugin_url)
472 : RenderFrameObserver(render_frame),
473 render_frame_(render_frame),
474 module_(module),
475 instance_interface_(instance_interface),
476 pp_instance_(0),
477 container_(container),
478 layer_bound_to_fullscreen_(false),
479 layer_is_hardware_(false),
480 plugin_url_(plugin_url),
481 is_flash_plugin_(module->name() == kFlashPluginName),
482 has_been_clicked_(false),
483 javascript_used_(false),
484 full_frame_(false),
485 sent_initial_did_change_view_(false),
486 bound_graphics_2d_platform_(NULL),
487 bound_compositor_(NULL),
488 has_webkit_focus_(false),
489 has_content_area_focus_(false),
490 find_identifier_(-1),
491 plugin_find_interface_(NULL),
492 plugin_input_event_interface_(NULL),
493 plugin_mouse_lock_interface_(NULL),
494 plugin_pdf_interface_(NULL),
495 plugin_private_interface_(NULL),
496 plugin_textinput_interface_(NULL),
497 plugin_zoom_interface_(NULL),
498 checked_for_plugin_input_event_interface_(false),
499 checked_for_plugin_pdf_interface_(false),
500 gamepad_impl_(new GamepadImpl()),
501 uma_private_impl_(NULL),
502 plugin_print_interface_(NULL),
503 plugin_graphics_3d_interface_(NULL),
504 always_on_top_(false),
505 fullscreen_container_(NULL),
506 flash_fullscreen_(false),
507 desired_fullscreen_state_(false),
508 message_channel_(NULL),
509 sad_plugin_(NULL),
510 input_event_mask_(0),
511 filtered_input_event_mask_(0),
512 text_input_type_(kPluginDefaultTextInputType),
513 text_input_caret_(0, 0, 0, 0),
514 text_input_caret_bounds_(0, 0, 0, 0),
515 text_input_caret_set_(false),
516 selection_caret_(0),
517 selection_anchor_(0),
518 pending_user_gesture_(0.0),
519 document_loader_(NULL),
520 external_document_load_(false),
521 isolate_(v8::Isolate::GetCurrent()),
522 is_deleted_(false),
523 last_input_number_(0),
524 is_tracking_latency_(false),
525 initialized_(false),
526 view_change_weak_ptr_factory_(this),
527 weak_factory_(this) {
528 pp_instance_ = HostGlobals::Get()->AddInstance(this);
530 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
531 module_->InstanceCreated(this);
533 if (render_frame) { // NULL in tests
534 render_frame->render_view()->PepperInstanceCreated(this);
535 // Bind a callback now so that we can inform the RenderViewImpl when we are
536 // destroyed. This works around a temporary problem stemming from work to
537 // move parts of RenderViewImpl in to RenderFrameImpl (see
538 // crbug.com/245126). If destruction happens in this order:
539 // 1) RenderFrameImpl
540 // 2) PepperPluginInstanceImpl
541 // 3) RenderViewImpl
542 // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
543 // to the RenderViewImpl. But when the instance is destroyed, it still
544 // needs to inform the RenderViewImpl that it has gone away, otherwise
545 // between (2) and (3), the RenderViewImpl will still have the dead
546 // instance in its active set, and so might make calls on the deleted
547 // instance. See crbug.com/343576 for more information. Once the plugin
548 // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
549 // can be a little bit simplified by instead making a direct call on
550 // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
551 instance_deleted_callback_ =
552 base::Bind(&RenderViewImpl::PepperInstanceDeleted,
553 render_frame->render_view()->AsWeakPtr(),
554 base::Unretained(this));
555 view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
557 // Set the initial focus.
558 SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
560 if (!module_->IsProxied()) {
561 PepperBrowserConnection* browser_connection =
562 PepperBrowserConnection::Get(render_frame_);
563 browser_connection->DidCreateInProcessInstance(
564 pp_instance(),
565 render_frame_->GetRoutingID(),
566 container_->element().document().url(),
567 GetPluginURL());
571 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
572 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
574 if (GetContentClient()->renderer() && // NULL in unit tests.
575 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
576 external_document_load_ = true;
579 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
580 DCHECK(!fullscreen_container_);
582 // Notify all the plugin objects of deletion. This will prevent blink from
583 // calling into the plugin any more.
585 // Swap out the set so we can delete from it (the objects will try to
586 // unregister themselves inside the delete call).
587 PluginObjectSet plugin_object_copy;
588 live_plugin_objects_.swap(plugin_object_copy);
589 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
590 i != plugin_object_copy.end();
591 ++i) {
592 (*i)->InstanceDeleted();
595 if (message_channel_)
596 message_channel_->InstanceDeleted();
597 message_channel_object_.Reset();
599 if (TrackedCallback::IsPending(lock_mouse_callback_))
600 lock_mouse_callback_->Abort();
602 if (!instance_deleted_callback_.is_null())
603 instance_deleted_callback_.Run();
605 if (!module_->IsProxied() && render_frame_) {
606 PepperBrowserConnection* browser_connection =
607 PepperBrowserConnection::Get(render_frame_);
608 browser_connection->DidDeleteInProcessInstance(pp_instance());
611 UnSetAndDeleteLockTargetAdapter();
612 module_->InstanceDeleted(this);
613 // If we switched from the NaCl plugin module, notify it too.
614 if (original_module_.get())
615 original_module_->InstanceDeleted(this);
617 // This should be last since some of the above "instance deleted" calls will
618 // want to look up in the global map to get info off of our object.
619 HostGlobals::Get()->InstanceDeleted(pp_instance_);
621 if (throttler_)
622 throttler_->RemoveObserver(this);
625 // NOTE: Any of these methods that calls into the plugin needs to take into
626 // account that the plugin may use Var to remove the <embed> from the DOM, which
627 // will make the PepperWebPluginImpl drop its reference, usually the last one.
628 // If a method needs to access a member of the instance after the call has
629 // returned, then it needs to keep its own reference on the stack.
631 v8::Local<v8::Object> PepperPluginInstanceImpl::GetMessageChannelObject() {
632 return v8::Local<v8::Object>::New(isolate_, message_channel_object_);
635 void PepperPluginInstanceImpl::MessageChannelDestroyed() {
636 message_channel_ = NULL;
637 message_channel_object_.Reset();
640 v8::Local<v8::Context> PepperPluginInstanceImpl::GetMainWorldContext() {
641 if (!container_)
642 return v8::Handle<v8::Context>();
644 if (container_->element().isNull())
645 return v8::Handle<v8::Context>();
647 if (container_->element().document().isNull())
648 return v8::Handle<v8::Context>();
650 if (!container_->element().document().frame())
651 return v8::Handle<v8::Context>();
653 v8::Local<v8::Context> context =
654 container_->element().document().frame()->mainWorldScriptContext();
655 DCHECK(context->GetIsolate() == isolate_);
656 return context;
659 void PepperPluginInstanceImpl::Delete() {
660 is_deleted_ = true;
662 if (render_frame_ &&
663 render_frame_->render_view()->plugin_find_handler() == this) {
664 render_frame_->render_view()->set_plugin_find_handler(NULL);
667 // Keep a reference on the stack. See NOTE above.
668 scoped_refptr<PepperPluginInstanceImpl> ref(this);
669 // Force the MessageChannel to release its "passthrough object" which should
670 // release our last reference to the "InstanceObject" and will probably
671 // destroy it. We want to do this prior to calling DidDestroy in case the
672 // destructor of the instance object tries to use the instance.
673 if (message_channel_)
674 message_channel_->SetPassthroughObject(v8::Handle<v8::Object>());
675 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
676 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
677 // since there is little that it can do at this point.
678 if (original_instance_interface_)
679 original_instance_interface_->DidDestroy(pp_instance());
680 else
681 instance_interface_->DidDestroy(pp_instance());
682 // Ensure we don't attempt to call functions on the destroyed instance.
683 original_instance_interface_.reset();
684 instance_interface_.reset();
686 if (fullscreen_container_) {
687 fullscreen_container_->Destroy();
688 fullscreen_container_ = NULL;
691 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
692 // leaks the graphics 2D, it may actually get cleaned up after our
693 // destruction, so we need its pointers to be up-to-date.
694 BindGraphics(pp_instance(), 0);
695 container_ = NULL;
698 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
700 void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
701 const gfx::Rect& plugin_rect,
702 const gfx::Rect& paint_rect) {
703 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
704 if (module()->is_crashed()) {
705 // Crashed plugin painting.
706 if (!sad_plugin_) // Lazily initialize bitmap.
707 sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
708 if (sad_plugin_)
709 PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
710 return;
713 if (bound_graphics_2d_platform_)
714 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
717 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
718 if (fullscreen_container_) {
719 if (rect.IsEmpty())
720 fullscreen_container_->Invalidate();
721 else
722 fullscreen_container_->InvalidateRect(rect);
723 } else {
724 if (!container_ || view_data_.rect.size.width == 0 ||
725 view_data_.rect.size.height == 0)
726 return; // Nothing to do.
727 if (rect.IsEmpty())
728 container_->invalidate();
729 else
730 container_->invalidateRect(rect);
733 cc::Layer* layer =
734 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
735 if (layer) {
736 if (rect.IsEmpty()) {
737 layer->SetNeedsDisplay();
738 } else {
739 layer->SetNeedsDisplayRect(rect);
744 void PepperPluginInstanceImpl::ScrollRect(int dx,
745 int dy,
746 const gfx::Rect& rect) {
747 cc::Layer* layer =
748 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
749 if (layer) {
750 InvalidateRect(rect);
751 } else if (fullscreen_container_) {
752 fullscreen_container_->ScrollRect(dx, dy, rect);
753 } else {
754 if (full_frame_ && !IsViewAccelerated()) {
755 container_->scrollRect(rect);
756 } else {
757 // Can't do optimized scrolling since there could be other elements on top
758 // of us or the view renders via the accelerated compositor which is
759 // incompatible with the move and backfill scrolling model.
760 InvalidateRect(rect);
765 void PepperPluginInstanceImpl::CommitBackingTexture() {
766 if (!texture_layer_.get())
767 return;
768 gpu::Mailbox mailbox;
769 uint32 sync_point = 0;
770 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
771 DCHECK(!mailbox.IsZero());
772 DCHECK_NE(sync_point, 0u);
773 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
774 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
775 texture_layer_->SetNeedsDisplay();
778 void PepperPluginInstanceImpl::InstanceCrashed() {
779 // Force free all resources and vars.
780 HostGlobals::Get()->InstanceCrashed(pp_instance());
782 // Free any associated graphics.
783 SetFullscreen(false);
784 FlashSetFullscreen(false, false);
785 // Unbind current 2D or 3D graphics context.
786 BindGraphics(pp_instance(), 0);
787 InvalidateRect(gfx::Rect());
789 if (content_decryptor_delegate_) {
790 content_decryptor_delegate_->InstanceCrashed();
791 content_decryptor_delegate_.reset();
794 if (render_frame_)
795 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
796 UnSetAndDeleteLockTargetAdapter();
799 bool PepperPluginInstanceImpl::Initialize(
800 const std::vector<std::string>& arg_names,
801 const std::vector<std::string>& arg_values,
802 bool full_frame,
803 scoped_ptr<PluginInstanceThrottlerImpl> throttler) {
804 DCHECK(!throttler_);
806 if (!render_frame_)
807 return false;
809 if (is_flash_plugin_ && RenderThread::Get()) {
810 RenderThread::Get()->RecordAction(
811 base::UserMetricsAction("Flash.PluginInstanceCreated"));
812 blink::WebRect bounds = container()->element().boundsInViewportSpace();
813 RecordFlashSizeMetric(bounds.width, bounds.height);
816 if (throttler) {
817 throttler_ = throttler.Pass();
818 throttler_->AddObserver(this);
821 message_channel_ = MessageChannel::Create(this, &message_channel_object_);
823 full_frame_ = full_frame;
825 UpdateTouchEventRequest();
826 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
828 SetGPUHistogram(ppapi::Preferences(PpapiPreferencesBuilder::Build(
829 render_frame_->render_view()->webkit_preferences())),
830 arg_names,
831 arg_values);
833 argn_ = arg_names;
834 argv_ = arg_values;
835 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
836 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
837 bool success = PP_ToBool(instance_interface_->DidCreate(
838 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
839 // If this is a plugin that hosts external plugins, we should delay messages
840 // so that the child plugin that's created later will receive all the
841 // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
843 // A host for external plugins will call ResetAsProxied later, at which point
844 // we can Start() the MessageChannel.
845 if (success && (!module_->renderer_ppapi_host()->IsExternalPluginHost())) {
846 if (message_channel_)
847 message_channel_->Start();
849 initialized_ = success;
850 return success;
853 bool PepperPluginInstanceImpl::HandleDocumentLoad(
854 const blink::WebURLResponse& response) {
855 DCHECK(!document_loader_);
856 if (external_document_load_) {
857 // The external proxy isn't available, so save the response and record
858 // document load notifications for later replay.
859 external_document_response_ = response;
860 external_document_loader_.reset(new ExternalDocumentLoader());
861 document_loader_ = external_document_loader_.get();
862 return true;
865 if (module()->is_crashed()) {
866 // Don't create a resource for a crashed plugin.
867 container()->element().document().frame()->stopLoading();
868 return false;
871 DCHECK(!document_loader_);
873 // Create a loader resource host for this load. Note that we have to set
874 // the document_loader before issuing the in-process
875 // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
876 // call into the instance and expect it to be valid.
877 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
878 PepperURLLoaderHost* loader_host =
879 new PepperURLLoaderHost(host_impl, true, pp_instance(), 0);
880 // TODO(teravest): Remove set_document_loader() from instance and clean up
881 // this relationship.
882 set_document_loader(loader_host);
883 loader_host->didReceiveResponse(NULL, response);
885 // This host will be pending until the resource object attaches to it.
887 // PpapiHost now owns the pointer to loader_host, so we don't have to worry
888 // about managing it.
889 int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
890 scoped_ptr<ppapi::host::ResourceHost>(loader_host));
891 DCHECK(pending_host_id);
893 DataFromWebURLResponse(
894 host_impl,
895 pp_instance(),
896 response,
897 base::Bind(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
898 weak_factory_.GetWeakPtr(),
899 response,
900 pending_host_id));
902 // If the load was not abandoned, document_loader_ will now be set. It's
903 // possible that the load was canceled by now and document_loader_ was
904 // already nulled out.
905 return true;
908 bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
909 PP_InputEvent_Type type,
910 const base::string16& text) {
911 std::vector<blink::WebCompositionUnderline> empty;
912 return SendCompositionEventWithUnderlineInformationToPlugin(
913 type,
914 text,
915 empty,
916 static_cast<int>(text.size()),
917 static_cast<int>(text.size()));
920 bool
921 PepperPluginInstanceImpl::SendCompositionEventWithUnderlineInformationToPlugin(
922 PP_InputEvent_Type type,
923 const base::string16& text,
924 const std::vector<blink::WebCompositionUnderline>& underlines,
925 int selection_start,
926 int selection_end) {
927 // Keep a reference on the stack. See NOTE above.
928 scoped_refptr<PepperPluginInstanceImpl> ref(this);
930 if (!LoadInputEventInterface())
931 return false;
933 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
934 if (!(filtered_input_event_mask_ & event_class) &&
935 !(input_event_mask_ & event_class))
936 return false;
938 ppapi::InputEventData event;
939 event.event_type = type;
940 event.event_time_stamp =
941 ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
943 // Convert UTF16 text to UTF8 with offset conversion.
944 std::vector<size_t> utf16_offsets;
945 utf16_offsets.push_back(selection_start);
946 utf16_offsets.push_back(selection_end);
947 for (size_t i = 0; i < underlines.size(); ++i) {
948 utf16_offsets.push_back(underlines[i].startOffset);
949 utf16_offsets.push_back(underlines[i].endOffset);
951 std::vector<size_t> utf8_offsets(utf16_offsets);
952 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
954 // Set the converted selection range.
955 event.composition_selection_start =
956 (utf8_offsets[0] == std::string::npos ? event.character_text.size()
957 : utf8_offsets[0]);
958 event.composition_selection_end =
959 (utf8_offsets[1] == std::string::npos ? event.character_text.size()
960 : utf8_offsets[1]);
962 // Set the converted segmentation points.
963 // Be sure to add 0 and size(), and remove duplication or errors.
964 std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
965 offset_set.insert(0);
966 offset_set.insert(event.character_text.size());
967 offset_set.erase(std::string::npos);
968 event.composition_segment_offsets.assign(offset_set.begin(),
969 offset_set.end());
971 // Set the composition target.
972 for (size_t i = 0; i < underlines.size(); ++i) {
973 if (underlines[i].thick) {
974 std::vector<uint32_t>::iterator it =
975 std::find(event.composition_segment_offsets.begin(),
976 event.composition_segment_offsets.end(),
977 utf8_offsets[2 * i + 2]);
978 if (it != event.composition_segment_offsets.end()) {
979 event.composition_target_segment =
980 it - event.composition_segment_offsets.begin();
981 break;
986 // Send the event.
987 bool handled = false;
988 if (filtered_input_event_mask_ & event_class)
989 event.is_filtered = true;
990 else
991 handled = true; // Unfiltered events are assumed to be handled.
992 scoped_refptr<PPB_InputEvent_Shared> event_resource(
993 new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
994 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
995 pp_instance(), event_resource->pp_resource()));
996 return handled;
999 void PepperPluginInstanceImpl::RequestInputEventsHelper(
1000 uint32_t event_classes) {
1001 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
1002 UpdateTouchEventRequest();
1003 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
1004 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
1007 bool PepperPluginInstanceImpl::HandleCompositionStart(
1008 const base::string16& text) {
1009 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1010 text);
1013 bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1014 const base::string16& text,
1015 const std::vector<blink::WebCompositionUnderline>& underlines,
1016 int selection_start,
1017 int selection_end) {
1018 return SendCompositionEventWithUnderlineInformationToPlugin(
1019 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
1020 text,
1021 underlines,
1022 selection_start,
1023 selection_end);
1026 bool PepperPluginInstanceImpl::HandleCompositionEnd(
1027 const base::string16& text) {
1028 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1029 text);
1032 bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1033 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1036 void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1037 gfx::Range* range) const {
1038 std::vector<size_t> offsets;
1039 offsets.push_back(selection_anchor_);
1040 offsets.push_back(selection_caret_);
1041 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1042 range->set_start(offsets[0] == base::string16::npos ? text->size()
1043 : offsets[0]);
1044 range->set_end(offsets[1] == base::string16::npos ? text->size()
1045 : offsets[1]);
1048 bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1049 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1050 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1053 gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1054 if (!text_input_caret_set_) {
1055 // If it is never set by the plugin, use the bottom left corner.
1056 return gfx::Rect(view_data_.rect.point.x,
1057 view_data_.rect.point.y + view_data_.rect.size.height,
1062 // TODO(kinaba) Take CSS transformation into accont.
1063 // TODO(kinaba) Take bounding_box into account. On some platforms, an
1064 // "exclude rectangle" where candidate window must avoid the region can be
1065 // passed to IME. Currently, we pass only the caret rectangle because
1066 // it is the only information supported uniformly in Chromium.
1067 gfx::Rect caret(text_input_caret_);
1068 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1069 return caret;
1072 bool PepperPluginInstanceImpl::HandleInputEvent(
1073 const blink::WebInputEvent& event,
1074 WebCursorInfo* cursor_info) {
1075 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1077 if (!has_been_clicked_ && is_flash_plugin_ &&
1078 event.type == blink::WebInputEvent::MouseDown &&
1079 (event.modifiers & blink::WebInputEvent::LeftButtonDown)) {
1080 has_been_clicked_ = true;
1081 blink::WebRect bounds = container()->element().boundsInViewportSpace();
1082 RecordFlashClickSizeMetric(bounds.width, bounds.height);
1085 if (throttler_ && throttler_->ConsumeInputEvent(event))
1086 return true;
1088 if (!render_frame_)
1089 return false;
1090 if (WebInputEvent::isMouseEventType(event.type)) {
1091 render_frame_->PepperDidReceiveMouseEvent(this);
1094 // Don't dispatch input events to crashed plugins.
1095 if (module()->is_crashed())
1096 return false;
1098 // Don't send reserved system key events to plugins.
1099 if (IsReservedSystemInputEvent(event))
1100 return false;
1102 // Keep a reference on the stack. See NOTE above.
1103 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1105 bool rv = false;
1106 if (LoadInputEventInterface()) {
1107 PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
1108 if (!event_class)
1109 return false;
1111 if ((filtered_input_event_mask_ & event_class) ||
1112 (input_event_mask_ & event_class)) {
1113 // Actually send the event.
1114 std::vector<ppapi::InputEventData> events;
1115 CreateInputEventData(event, &events);
1117 // Allow the user gesture to be pending after the plugin handles the
1118 // event. This allows out-of-process plugins to respond to the user
1119 // gesture after processing has finished here.
1120 if (WebUserGestureIndicator::isProcessingUserGesture()) {
1121 pending_user_gesture_ =
1122 ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
1123 pending_user_gesture_token_ =
1124 WebUserGestureIndicator::currentUserGestureToken();
1125 pending_user_gesture_token_.setOutOfProcess();
1128 const ui::LatencyInfo* current_event_latency_info = NULL;
1129 if (render_frame_->GetRenderWidget()) {
1130 current_event_latency_info =
1131 render_frame_->GetRenderWidget()->current_event_latency_info();
1134 // Each input event may generate more than one PP_InputEvent.
1135 for (size_t i = 0; i < events.size(); i++) {
1136 if (is_tracking_latency_) {
1137 InitLatencyInfo(&events[i].latency_info,
1138 current_event_latency_info,
1139 event.type,
1140 last_input_number_++);
1142 if (filtered_input_event_mask_ & event_class)
1143 events[i].is_filtered = true;
1144 else
1145 rv = true; // Unfiltered events are assumed to be handled.
1146 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1147 new PPB_InputEvent_Shared(
1148 ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1150 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1151 pp_instance(), event_resource->pp_resource()));
1156 if (cursor_)
1157 *cursor_info = *cursor_;
1158 return rv;
1161 void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1162 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1163 if (is_deleted_)
1164 return;
1165 ppapi::proxy::HostDispatcher* dispatcher =
1166 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1167 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1168 // The dispatcher should always be valid, and MessageChannel should never
1169 // send an 'object' var over PPP_Messaging.
1170 NOTREACHED();
1171 return;
1173 dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1174 ppapi::API_ID_PPP_MESSAGING,
1175 pp_instance(),
1176 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1177 pp_instance())));
1180 bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1181 ScopedPPVar* result) {
1182 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
1183 if (is_deleted_)
1184 return false;
1185 ppapi::proxy::HostDispatcher* dispatcher =
1186 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1187 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1188 // The dispatcher should always be valid, and MessageChannel should never
1189 // send an 'object' var over PPP_Messaging.
1190 NOTREACHED();
1191 return false;
1193 ppapi::proxy::ReceiveSerializedVarReturnValue msg_reply;
1194 bool was_handled = false;
1195 dispatcher->Send(new PpapiMsg_PPPMessageHandler_HandleBlockingMessage(
1196 ppapi::API_ID_PPP_MESSAGING,
1197 pp_instance(),
1198 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1199 pp_instance()),
1200 &msg_reply,
1201 &was_handled));
1202 *result = ScopedPPVar(ScopedPPVar::PassRef(), msg_reply.Return(dispatcher));
1203 TRACE_EVENT0("ppapi",
1204 "PepperPluginInstanceImpl::HandleBlockingMessage return.");
1205 return was_handled;
1208 PP_Var PepperPluginInstanceImpl::GetInstanceObject(v8::Isolate* isolate) {
1209 // Keep a reference on the stack. See NOTE above.
1210 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1212 DCHECK_EQ(isolate, isolate_);
1213 RecordFlashJavaScriptUse();
1215 // If the plugin supports the private instance interface, try to retrieve its
1216 // instance object.
1217 if (LoadPrivateInterface())
1218 return plugin_private_interface_->GetInstanceObject(pp_instance());
1219 return PP_MakeUndefined();
1222 void PepperPluginInstanceImpl::ViewChanged(
1223 const gfx::Rect& position,
1224 const gfx::Rect& clip,
1225 const std::vector<gfx::Rect>& cut_outs_rects) {
1226 // WebKit can give weird (x,y) positions for empty clip rects (since the
1227 // position technically doesn't matter). But we want to make these
1228 // consistent since this is given to the plugin, so force everything to 0
1229 // in the "everything is clipped" case.
1230 gfx::Rect new_clip;
1231 if (!clip.IsEmpty())
1232 new_clip = clip;
1234 cut_outs_rects_ = cut_outs_rects;
1236 view_data_.rect = PP_FromGfxRect(position);
1237 view_data_.clip_rect = PP_FromGfxRect(clip);
1238 view_data_.device_scale = container_->deviceScaleFactor();
1239 view_data_.css_scale =
1240 container_->pageZoomFactor() * container_->pageScaleFactor();
1242 gfx::Size scroll_offset =
1243 container_->element().document().frame()->scrollOffset();
1244 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1245 scroll_offset.height());
1247 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1248 WebElement element = container_->element();
1249 WebDocument document = element.document();
1250 bool is_fullscreen_element = (element == document.fullScreenElement());
1251 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1252 render_frame()->GetRenderWidget()->is_fullscreen() &&
1253 is_fullscreen_element) {
1254 // Entered fullscreen. Only possible via SetFullscreen().
1255 view_data_.is_fullscreen = true;
1256 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1257 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1258 // so desired_fullscreen_state might be out-of-date.
1259 desired_fullscreen_state_ = false;
1260 view_data_.is_fullscreen = false;
1262 // This operation will cause the plugin to re-layout which will send more
1263 // DidChangeView updates. Schedule an asynchronous update and suppress
1264 // notifications until that completes to avoid sending intermediate sizes
1265 // to the plugins.
1266 ScheduleAsyncDidChangeView();
1268 // Reset the size attributes that we hacked to fill in the screen and
1269 // retrigger ViewChanged. Make sure we don't forward duplicates of
1270 // this view to the plugin.
1271 ResetSizeAttributesAfterFullscreen();
1272 return;
1276 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1278 SendDidChangeView();
1281 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1282 if (has_webkit_focus_ == has_focus)
1283 return;
1285 bool old_plugin_focus = PluginHasFocus();
1286 has_webkit_focus_ = has_focus;
1287 if (PluginHasFocus() != old_plugin_focus)
1288 SendFocusChangeNotification();
1291 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1292 if (has_content_area_focus_ == has_focus)
1293 return;
1295 bool old_plugin_focus = PluginHasFocus();
1296 has_content_area_focus_ = has_focus;
1297 if (PluginHasFocus() != old_plugin_focus)
1298 SendFocusChangeNotification();
1301 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1302 if (is_visible == view_data_.is_page_visible)
1303 return; // Nothing to do.
1304 view_data_.is_page_visible = is_visible;
1306 // If the initial DidChangeView notification hasn't been sent to the plugin,
1307 // let it pass the visibility state for us, instead of sending a notification
1308 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1309 // hasn't been called for the first time. In that case, most of the fields in
1310 // |view_data_| haven't been properly initialized.
1311 if (sent_initial_did_change_view_)
1312 SendDidChangeView();
1315 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1316 if (bound_graphics_2d_platform_)
1317 bound_graphics_2d_platform_->ViewInitiatedPaint();
1318 else if (bound_graphics_3d_.get())
1319 bound_graphics_3d_->ViewInitiatedPaint();
1320 else if (bound_compositor_)
1321 bound_compositor_->ViewInitiatedPaint();
1324 void PepperPluginInstanceImpl::SetSelectedText(
1325 const base::string16& selected_text) {
1326 selected_text_ = selected_text;
1327 gfx::Range range(0, selected_text.length());
1328 render_frame_->SetSelectedText(selected_text, 0, range);
1331 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1332 link_under_cursor_ = base::UTF8ToUTF16(url);
1335 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1336 text_input_type_ = type;
1337 render_frame_->PepperTextInputTypeChanged(this);
1340 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1341 if (message_channel_)
1342 message_channel_->PostMessageToJavaScript(message);
1345 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1346 PP_Instance instance,
1347 void* user_data,
1348 const PPP_MessageHandler_0_2* handler,
1349 PP_Resource message_loop) {
1350 // Not supported in-process.
1351 NOTIMPLEMENTED();
1352 return PP_ERROR_FAILED;
1355 int32_t PepperPluginInstanceImpl::RegisterMessageHandler_1_1_Deprecated(
1356 PP_Instance instance,
1357 void* user_data,
1358 const PPP_MessageHandler_0_1_Deprecated* handler,
1359 PP_Resource message_loop) {
1360 // Not supported in-process.
1361 NOTIMPLEMENTED();
1362 return PP_ERROR_FAILED;
1365 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1366 // Not supported in-process.
1367 NOTIMPLEMENTED();
1370 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1371 return selected_text_;
1374 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1375 const gfx::Point& point) {
1376 // Keep a reference on the stack. See NOTE above.
1377 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1378 if (!LoadPdfInterface()) {
1379 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1380 // return |link_under_cursor_| here because this is only ever called with
1381 // the current mouse coordinates.
1382 return link_under_cursor_;
1385 PP_Point p;
1386 p.x = point.x();
1387 p.y = point.y();
1388 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1389 // If the plugin returns undefined for this function it has switched to
1390 // providing us with the link under the cursor eagerly.
1391 if (rv.type == PP_VARTYPE_UNDEFINED)
1392 return link_under_cursor_;
1393 StringVar* string = StringVar::FromPPVar(rv);
1394 base::string16 link;
1395 if (string)
1396 link = base::UTF8ToUTF16(string->value());
1397 // Release the ref the plugin transfered to us.
1398 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1399 return link;
1402 void PepperPluginInstanceImpl::RequestSurroundingText(
1403 size_t desired_number_of_characters) {
1404 // Keep a reference on the stack. See NOTE above.
1405 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1406 if (!LoadTextInputInterface())
1407 return;
1408 plugin_textinput_interface_->RequestSurroundingText(
1409 pp_instance(), desired_number_of_characters);
1412 void PepperPluginInstanceImpl::Zoom(double factor, bool text_only) {
1413 // Keep a reference on the stack. See NOTE above.
1414 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1415 if (!LoadZoomInterface())
1416 return;
1417 plugin_zoom_interface_->Zoom(pp_instance(), factor, PP_FromBool(text_only));
1420 bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1421 bool case_sensitive,
1422 int identifier) {
1423 // Keep a reference on the stack. See NOTE above.
1424 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1425 if (!LoadFindInterface())
1426 return false;
1427 find_identifier_ = identifier;
1428 return PP_ToBool(
1429 plugin_find_interface_->StartFind(pp_instance(),
1430 base::UTF16ToUTF8(search_text).c_str(),
1431 PP_FromBool(case_sensitive)));
1434 void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1435 // Keep a reference on the stack. See NOTE above.
1436 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1437 if (LoadFindInterface())
1438 plugin_find_interface_->SelectFindResult(pp_instance(),
1439 PP_FromBool(forward));
1442 void PepperPluginInstanceImpl::StopFind() {
1443 // Keep a reference on the stack. See NOTE above.
1444 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1445 if (!LoadFindInterface())
1446 return;
1447 find_identifier_ = -1;
1448 plugin_find_interface_->StopFind(pp_instance());
1451 bool PepperPluginInstanceImpl::LoadFindInterface() {
1452 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1453 return false;
1454 if (!plugin_find_interface_) {
1455 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1456 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1459 return !!plugin_find_interface_;
1462 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1463 if (!checked_for_plugin_input_event_interface_) {
1464 checked_for_plugin_input_event_interface_ = true;
1465 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1466 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1468 return !!plugin_input_event_interface_;
1471 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1472 if (!plugin_mouse_lock_interface_) {
1473 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1474 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1477 return !!plugin_mouse_lock_interface_;
1480 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1481 if (!checked_for_plugin_pdf_interface_) {
1482 checked_for_plugin_pdf_interface_ = true;
1483 plugin_pdf_interface_ = static_cast<const PPP_Pdf*>(
1484 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1487 return !!plugin_pdf_interface_;
1490 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1491 // Only check for the interface if the plugin has dev permission.
1492 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1493 return false;
1494 if (!plugin_print_interface_) {
1495 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1496 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1498 return !!plugin_print_interface_;
1501 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1502 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1503 // call GetInstanceObject. This is necessary to ensure that the properties
1504 // the trusted plugin exposes (readyState and lastError) work properly. Note
1505 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1506 // so it's correct to never look up PPP_InstancePrivate for them.
1508 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1509 // to the "real" module.
1510 scoped_refptr<PluginModule> module =
1511 original_module_.get() ? original_module_ : module_;
1512 // Only check for the interface if the plugin has private permission.
1513 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1514 return false;
1515 if (!plugin_private_interface_) {
1516 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1517 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1520 return !!plugin_private_interface_;
1523 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1524 if (!plugin_textinput_interface_) {
1525 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1526 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1529 return !!plugin_textinput_interface_;
1532 bool PepperPluginInstanceImpl::LoadZoomInterface() {
1533 if (!plugin_zoom_interface_) {
1534 plugin_zoom_interface_ = static_cast<const PPP_Zoom_Dev*>(
1535 module_->GetPluginInterface(PPP_ZOOM_DEV_INTERFACE));
1538 return !!plugin_zoom_interface_;
1541 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1542 if (!bound_graphics_2d_platform_ || !texture_layer_.get()) {
1543 // Currently the transform is only applied for Graphics2D.
1544 return;
1546 // Set the UV coordinates of the texture based on the size of the Graphics2D
1547 // context. By default a texture gets scaled to the size of the layer. But
1548 // if the size of the Graphics2D context doesn't match the size of the plugin
1549 // then it will be incorrectly stretched. This also affects how the plugin
1550 // is painted when it is being resized. If the Graphics2D contents are
1551 // stretched when a plugin is resized while waiting for a new frame from the
1552 // plugin to be rendered, then flickering behavior occurs as in
1553 // crbug.com/353453.
1554 gfx::SizeF graphics_2d_size_in_dip =
1555 gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1556 bound_graphics_2d_platform_->GetScale());
1557 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1558 view_data_.rect.size.height);
1560 texture_layer_->SetUV(
1561 gfx::PointF(0.0f, 0.0f),
1562 gfx::PointF(
1563 plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1564 plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1567 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1568 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1571 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1572 // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1573 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1574 // drop its reference, usually the last one. This is similar to possible
1575 // plugin behavior described at the NOTE above Delete().
1576 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1578 if (!render_frame_)
1579 return;
1581 bool has_focus = PluginHasFocus();
1582 render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1584 // instance_interface_ may have been cleared in Delete() if the
1585 // PepperWebPluginImpl is destroyed.
1586 if (instance_interface_)
1587 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1590 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1591 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1592 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1593 container_->requestTouchEventType(
1594 raw_touch
1595 ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1596 : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1599 bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1600 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1601 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1604 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1605 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1606 return; // Already scheduled.
1607 base::MessageLoop::current()->PostTask(
1608 FROM_HERE,
1609 base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1610 view_change_weak_ptr_factory_.GetWeakPtr()));
1613 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1614 // The bound callback that owns the weak pointer is still valid until after
1615 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1616 // invalidate them here.
1617 // NOTE: If we ever want to have more than one pending callback, it should
1618 // use a different factory, or we should have a different strategy here.
1619 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1620 SendDidChangeView();
1623 void PepperPluginInstanceImpl::SendDidChangeView() {
1624 // Don't send DidChangeView to crashed plugins.
1625 if (module()->is_crashed())
1626 return;
1628 ppapi::ViewData view_data = view_data_;
1630 // When plugin content is throttled, fake the page being offscreen. We cannot
1631 // send empty view data here, as some plugins rely on accurate view data.
1632 if (throttler_ && throttler_->IsThrottled()) {
1633 view_data.is_page_visible = false;
1634 view_data.clip_rect.point.x = 0;
1635 view_data.clip_rect.point.y = 0;
1636 view_data.clip_rect.size.width = 0;
1637 view_data.clip_rect.size.height = 0;
1640 if (view_change_weak_ptr_factory_.HasWeakPtrs() ||
1641 (sent_initial_did_change_view_ &&
1642 last_sent_view_data_.Equals(view_data)))
1643 return; // Nothing to update.
1645 sent_initial_did_change_view_ = true;
1646 last_sent_view_data_ = view_data;
1647 ScopedPPResource resource(
1648 ScopedPPResource::PassRef(),
1649 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data))
1650 ->GetReference());
1652 UpdateLayerTransform();
1654 if (bound_graphics_2d_platform_ &&
1655 (!view_data.is_page_visible ||
1656 PP_ToGfxRect(view_data.clip_rect).IsEmpty())) {
1657 bound_graphics_2d_platform_->ClearCache();
1660 // It's possible that Delete() has been called but the renderer hasn't
1661 // released its reference to this object yet.
1662 if (instance_interface_) {
1663 instance_interface_->DidChangeView(
1664 pp_instance(), resource, &view_data.rect, &view_data.clip_rect);
1668 void PepperPluginInstanceImpl::ReportGeometry() {
1669 // If this call was delayed, we may have transitioned back to fullscreen in
1670 // the mean time, so only report the geometry if we are actually in normal
1671 // mode.
1672 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1673 container_->reportGeometry();
1676 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1677 PP_PrintOutputFormat_Dev* format) {
1678 // Keep a reference on the stack. See NOTE above.
1679 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1680 if (!LoadPrintInterface())
1681 return false;
1682 uint32_t supported_formats =
1683 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1684 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1685 *format = PP_PRINTOUTPUTFORMAT_PDF;
1686 return true;
1688 return false;
1691 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1692 PP_PrintOutputFormat_Dev format;
1693 return GetPreferredPrintOutputFormat(&format);
1696 bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1697 DCHECK(plugin_print_interface_);
1698 if (!plugin_print_interface_)
1699 return false;
1700 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1703 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1704 // Keep a reference on the stack. See NOTE above.
1705 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1706 PP_PrintOutputFormat_Dev format;
1707 if (!GetPreferredPrintOutputFormat(&format)) {
1708 // PrintBegin should not have been called since SupportsPrintInterface
1709 // would have returned false;
1710 NOTREACHED();
1711 return 0;
1713 int num_pages = 0;
1714 PP_PrintSettings_Dev print_settings;
1715 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1716 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1717 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1718 print_settings.dpi = print_params.printerDPI;
1719 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1720 print_settings.grayscale = PP_FALSE;
1721 print_settings.print_scaling_option =
1722 static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1723 print_settings.format = format;
1724 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1725 if (!num_pages)
1726 return 0;
1727 current_print_settings_ = print_settings;
1728 canvas_.clear();
1729 ranges_.clear();
1730 return num_pages;
1733 bool PepperPluginInstanceImpl::PrintPage(int page_number,
1734 blink::WebCanvas* canvas) {
1735 #if defined(ENABLE_PRINTING)
1736 DCHECK(plugin_print_interface_);
1737 PP_PrintPageNumberRange_Dev page_range;
1738 page_range.first_page_number = page_range.last_page_number = page_number;
1739 // The canvas only has a metafile on it for print preview.
1740 bool save_for_later =
1741 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1742 #if defined(OS_MACOSX)
1743 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1744 #endif // defined(OS_MACOSX)
1745 if (save_for_later) {
1746 ranges_.push_back(page_range);
1747 canvas_ = skia::SharePtr(canvas);
1748 return true;
1749 } else {
1750 return PrintPageHelper(&page_range, 1, canvas);
1752 #else // ENABLE_PRINTING
1753 return false;
1754 #endif
1757 bool PepperPluginInstanceImpl::PrintPageHelper(
1758 PP_PrintPageNumberRange_Dev* page_ranges,
1759 int num_ranges,
1760 blink::WebCanvas* canvas) {
1761 // Keep a reference on the stack. See NOTE above.
1762 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1763 DCHECK(plugin_print_interface_);
1764 if (!plugin_print_interface_)
1765 return false;
1766 PP_Resource print_output = plugin_print_interface_->PrintPages(
1767 pp_instance(), page_ranges, num_ranges);
1768 if (!print_output)
1769 return false;
1771 bool ret = false;
1773 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1774 ret = PrintPDFOutput(print_output, canvas);
1776 // Now we need to release the print output resource.
1777 PluginModule::GetCore()->ReleaseResource(print_output);
1779 return ret;
1782 void PepperPluginInstanceImpl::PrintEnd() {
1783 // Keep a reference on the stack. See NOTE above.
1784 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1785 if (!ranges_.empty())
1786 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1787 canvas_.clear();
1788 ranges_.clear();
1790 DCHECK(plugin_print_interface_);
1791 if (plugin_print_interface_)
1792 plugin_print_interface_->End(pp_instance());
1794 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1795 #if defined(OS_MACOSX)
1796 last_printed_page_ = NULL;
1797 #endif // defined(OS_MACOSX)
1800 bool PepperPluginInstanceImpl::GetPrintPresetOptionsFromDocument(
1801 blink::WebPrintPresetOptions* preset_options) {
1802 // Keep a reference on the stack. See NOTE above.
1803 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1804 if (!LoadPdfInterface())
1805 return false;
1807 PP_PdfPrintPresetOptions_Dev options;
1808 if (!plugin_pdf_interface_->GetPrintPresetOptionsFromDocument(pp_instance(),
1809 &options)) {
1810 return false;
1813 preset_options->isScalingDisabled = PP_ToBool(options.is_scaling_disabled);
1814 preset_options->copies = options.copies;
1816 return true;
1819 bool PepperPluginInstanceImpl::CanRotateView() {
1820 if (!LoadPdfInterface())
1821 return false;
1823 return true;
1826 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1827 if (!LoadPdfInterface())
1828 return;
1829 PP_PrivatePageTransformType transform_type =
1830 type == WebPlugin::RotationType90Clockwise
1831 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1832 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1833 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1834 // NOTE: plugin instance may have been deleted.
1837 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1838 return fullscreen_container_ != NULL;
1841 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1842 return desired_fullscreen_state_;
1845 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1846 // Keep a reference on the stack. See NOTE above.
1847 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1849 // Check whether we are trying to switch to the state we're already going
1850 // to (i.e. if we're already switching to fullscreen but the fullscreen
1851 // container isn't ready yet, don't do anything more).
1852 if (fullscreen == IsFullscreenOrPending())
1853 return false;
1855 if (!render_frame_)
1856 return false;
1857 if (fullscreen && !render_frame_->render_view()
1858 ->renderer_preferences()
1859 .plugin_fullscreen_allowed)
1860 return false;
1862 // Check whether we are trying to switch while the state is in transition.
1863 // The 2nd request gets dropped while messing up the internal state, so
1864 // disallow this.
1865 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1866 return false;
1868 if (fullscreen && !IsProcessingUserGesture())
1869 return false;
1871 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1872 desired_fullscreen_state_ = fullscreen;
1874 if (fullscreen) {
1875 // Create the user gesture in case we're processing one that's pending.
1876 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1877 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1878 // so we will tweak plugin's attributes to support the expected behavior.
1879 KeepSizeAttributesBeforeFullscreen();
1880 SetSizeAttributesForFullscreen();
1881 container_->element().requestFullScreen();
1882 } else {
1883 container_->element().document().cancelFullScreen();
1885 return true;
1888 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1889 bool flash_fullscreen) {
1890 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1892 if (flash_fullscreen == flash_fullscreen_) {
1893 // Manually clear callback when fullscreen fails with mouselock pending.
1894 if (!flash_fullscreen && is_mouselock_pending)
1895 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1896 return;
1899 UpdateLayer(false);
1901 bool old_plugin_focus = PluginHasFocus();
1902 flash_fullscreen_ = flash_fullscreen;
1903 if (is_mouselock_pending && !IsMouseLocked()) {
1904 if (!IsProcessingUserGesture() &&
1905 !module_->permissions().HasPermission(
1906 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1907 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1908 } else {
1909 // Open a user gesture here so the Webkit user gesture checks will succeed
1910 // for out-of-process plugins.
1911 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1912 if (!LockMouse())
1913 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1917 if (PluginHasFocus() != old_plugin_focus)
1918 SendFocusChangeNotification();
1921 bool PepperPluginInstanceImpl::IsViewAccelerated() {
1922 if (!container_)
1923 return false;
1925 WebDocument document = container_->element().document();
1926 WebLocalFrame* frame = document.frame();
1927 if (!frame)
1928 return false;
1929 WebView* view = frame->view();
1930 if (!view)
1931 return false;
1933 return view->isAcceleratedCompositingActive();
1936 bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1937 blink::WebCanvas* canvas) {
1938 #if defined(ENABLE_PRINTING)
1939 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1940 if (enter.failed())
1941 return false;
1943 BufferAutoMapper mapper(enter.object());
1944 if (!mapper.data() || !mapper.size()) {
1945 NOTREACHED();
1946 return false;
1949 printing::PdfMetafileSkia* metafile =
1950 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1951 if (metafile)
1952 return metafile->InitFromData(mapper.data(), mapper.size());
1954 NOTREACHED();
1955 #endif // ENABLE_PRINTING
1956 return false;
1959 void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
1960 if (!container_)
1961 return;
1963 gpu::Mailbox mailbox;
1964 uint32 sync_point = 0;
1965 if (bound_graphics_3d_.get()) {
1966 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
1967 DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
1969 bool want_3d_layer = !mailbox.IsZero();
1970 bool want_2d_layer = !!bound_graphics_2d_platform_;
1971 bool want_texture_layer = want_3d_layer || want_2d_layer;
1972 bool want_compositor_layer = !!bound_compositor_;
1974 if (!device_changed && (want_texture_layer == !!texture_layer_.get()) &&
1975 (want_3d_layer == layer_is_hardware_) &&
1976 (want_compositor_layer == !!compositor_layer_.get()) &&
1977 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
1978 UpdateLayerTransform();
1979 return;
1982 if (texture_layer_.get() || compositor_layer_.get()) {
1983 if (!layer_bound_to_fullscreen_)
1984 container_->setWebLayer(NULL);
1985 else if (fullscreen_container_)
1986 fullscreen_container_->SetLayer(NULL);
1987 web_layer_.reset();
1988 texture_layer_ = NULL;
1989 compositor_layer_ = NULL;
1992 if (want_texture_layer) {
1993 bool opaque = false;
1994 if (want_3d_layer) {
1995 DCHECK(bound_graphics_3d_.get());
1996 texture_layer_ = cc::TextureLayer::CreateForMailbox(NULL);
1997 opaque = bound_graphics_3d_->IsOpaque();
1998 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
1999 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
2000 } else {
2001 DCHECK(bound_graphics_2d_platform_);
2002 texture_layer_ = cc::TextureLayer::CreateForMailbox(this);
2003 bound_graphics_2d_platform_->AttachedToNewLayer();
2004 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2005 texture_layer_->SetFlipped(false);
2008 // Ignore transparency in fullscreen, since that's what Flash always
2009 // wants to do, and that lets it not recreate a context if
2010 // wmode=transparent was specified.
2011 opaque = opaque || fullscreen_container_;
2012 texture_layer_->SetContentsOpaque(opaque);
2013 web_layer_.reset(new cc_blink::WebLayerImpl(texture_layer_));
2014 } else if (want_compositor_layer) {
2015 compositor_layer_ = bound_compositor_->layer();
2016 web_layer_.reset(new cc_blink::WebLayerImpl(compositor_layer_));
2019 if (web_layer_) {
2020 if (fullscreen_container_) {
2021 fullscreen_container_->SetLayer(web_layer_.get());
2022 } else {
2023 container_->setWebLayer(web_layer_.get());
2027 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2028 layer_is_hardware_ = want_3d_layer;
2029 UpdateLayerTransform();
2032 bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2033 cc::TextureMailbox* mailbox,
2034 scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2035 bool use_shared_memory) {
2036 if (!bound_graphics_2d_platform_)
2037 return false;
2038 return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2039 release_callback);
2042 void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2044 void PepperPluginInstanceImpl::OnThrottleStateChange() {
2045 SendDidChangeView();
2048 void PepperPluginInstanceImpl::AddLatencyInfo(
2049 const std::vector<ui::LatencyInfo>& latency_info) {
2050 if (render_frame_ && render_frame_->GetRenderWidget()) {
2051 RenderWidgetCompositor* compositor =
2052 render_frame_->GetRenderWidget()->compositor();
2053 if (compositor) {
2054 for (size_t i = 0; i < latency_info.size(); i++) {
2055 scoped_ptr<cc::SwapPromise> swap_promise(
2056 new cc::LatencyInfoSwapPromise(latency_info[i]));
2057 compositor->QueueSwapPromise(swap_promise.Pass());
2063 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2064 DCHECK(live_plugin_objects_.find(plugin_object) ==
2065 live_plugin_objects_.end());
2066 live_plugin_objects_.insert(plugin_object);
2069 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2070 // Don't actually verify that the object is in the set since during module
2071 // deletion we'll be in the process of freeing them.
2072 live_plugin_objects_.erase(plugin_object);
2075 bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2076 PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2077 // Give a lot of slack so tests won't be flaky.
2078 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2079 return pending_user_gesture_token_.hasGestures() &&
2080 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2083 WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2084 if (!IsProcessingUserGesture())
2085 pending_user_gesture_token_ = WebUserGestureToken();
2086 return pending_user_gesture_token_;
2089 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2090 if (TrackedCallback::IsPending(lock_mouse_callback_))
2091 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2094 void PepperPluginInstanceImpl::OnMouseLockLost() {
2095 if (LoadMouseLockInterface())
2096 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2099 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2100 const blink::WebMouseEvent& event) {
2101 // |cursor_info| is ignored since it is hidden when the mouse is locked.
2102 blink::WebCursorInfo cursor_info;
2103 HandleInputEvent(event, &cursor_info);
2106 void PepperPluginInstanceImpl::SimulateInputEvent(
2107 const InputEventData& input_event) {
2108 WebView* web_view = container()->element().document().frame()->view();
2109 if (!web_view) {
2110 NOTREACHED();
2111 return;
2114 bool handled = SimulateIMEEvent(input_event);
2115 if (handled)
2116 return;
2118 std::vector<linked_ptr<WebInputEvent> > events =
2119 CreateSimulatedWebInputEvents(
2120 input_event,
2121 view_data_.rect.point.x + view_data_.rect.size.width / 2,
2122 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2123 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2124 it != events.end();
2125 ++it) {
2126 web_view->handleInputEvent(*it->get());
2130 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2131 const InputEventData& input_event) {
2132 switch (input_event.event_type) {
2133 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2134 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2135 SimulateImeSetCompositionEvent(input_event);
2136 break;
2137 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2138 DCHECK(input_event.character_text.empty());
2139 SimulateImeSetCompositionEvent(input_event);
2140 break;
2141 case PP_INPUTEVENT_TYPE_IME_TEXT:
2142 if (!render_frame_)
2143 return false;
2144 render_frame_->SimulateImeConfirmComposition(
2145 base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2146 break;
2147 default:
2148 return false;
2150 return true;
2153 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2154 const InputEventData& input_event) {
2155 if (!render_frame_)
2156 return;
2158 std::vector<size_t> offsets;
2159 offsets.push_back(input_event.composition_selection_start);
2160 offsets.push_back(input_event.composition_selection_end);
2161 offsets.insert(offsets.end(),
2162 input_event.composition_segment_offsets.begin(),
2163 input_event.composition_segment_offsets.end());
2165 base::string16 utf16_text =
2166 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2168 std::vector<blink::WebCompositionUnderline> underlines;
2169 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2170 blink::WebCompositionUnderline underline;
2171 underline.startOffset = offsets[i];
2172 underline.endOffset = offsets[i + 1];
2173 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2174 underline.thick = true;
2175 underlines.push_back(underline);
2178 render_frame_->SimulateImeSetComposition(
2179 utf16_text, underlines, offsets[0], offsets[1]);
2182 ContentDecryptorDelegate*
2183 PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2184 if (content_decryptor_delegate_)
2185 return content_decryptor_delegate_.get();
2187 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2188 static_cast<const PPP_ContentDecryptor_Private*>(
2189 module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2190 if (!plugin_decryption_interface)
2191 return NULL;
2193 content_decryptor_delegate_.reset(
2194 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2195 return content_decryptor_delegate_.get();
2198 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2199 PP_Resource device) {
2200 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2201 // The Graphics3D instance can't be destroyed until we call
2202 // UpdateLayer().
2203 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2204 if (bound_graphics_3d_.get()) {
2205 bound_graphics_3d_->BindToInstance(false);
2206 bound_graphics_3d_ = NULL;
2208 if (bound_graphics_2d_platform_) {
2209 bound_graphics_2d_platform_->BindToInstance(NULL);
2210 bound_graphics_2d_platform_ = NULL;
2212 if (bound_compositor_) {
2213 bound_compositor_->BindToInstance(NULL);
2214 bound_compositor_ = NULL;
2217 // Special-case clearing the current device.
2218 if (!device) {
2219 UpdateLayer(true);
2220 InvalidateRect(gfx::Rect());
2221 return PP_TRUE;
2224 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2225 // to/from fullscreen with PPB_Fullscreen.
2226 if ((fullscreen_container_ && !flash_fullscreen_) ||
2227 desired_fullscreen_state_ != view_data_.is_fullscreen)
2228 return PP_FALSE;
2230 const ppapi::host::PpapiHost* ppapi_host =
2231 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2232 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2233 PepperGraphics2DHost* graphics_2d = NULL;
2234 PepperCompositorHost* compositor = NULL;
2235 if (host) {
2236 if (host->IsGraphics2DHost()) {
2237 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2238 } else if (host->IsCompositorHost()) {
2239 compositor = static_cast<PepperCompositorHost*>(host);
2240 } else {
2241 DLOG(ERROR) <<
2242 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2246 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2247 PPB_Graphics3D_Impl* graphics_3d =
2248 enter_3d.succeeded()
2249 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2250 : NULL;
2252 if (compositor) {
2253 if (compositor->BindToInstance(this)) {
2254 bound_compositor_ = compositor;
2255 UpdateLayer(true);
2256 return PP_TRUE;
2258 } else if (graphics_2d) {
2259 if (graphics_2d->BindToInstance(this)) {
2260 bound_graphics_2d_platform_ = graphics_2d;
2261 UpdateLayer(true);
2262 return PP_TRUE;
2264 } else if (graphics_3d) {
2265 // Make sure graphics can only be bound to the instance it is
2266 // associated with.
2267 if (graphics_3d->pp_instance() == pp_instance() &&
2268 graphics_3d->BindToInstance(true)) {
2269 bound_graphics_3d_ = graphics_3d;
2270 UpdateLayer(true);
2271 return PP_TRUE;
2275 // The instance cannot be bound or the device is not a valid resource type.
2276 return PP_FALSE;
2279 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2280 return PP_FromBool(full_frame());
2283 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2284 return &view_data_;
2287 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2288 return PP_FromBool(flash_fullscreen_);
2291 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2292 if (!container_)
2293 return PP_MakeUndefined();
2294 RecordFlashJavaScriptUse();
2295 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2296 PepperTryCatchVar try_catch(this, &converter, NULL);
2297 WebLocalFrame* frame = container_->element().document().frame();
2298 if (!frame) {
2299 try_catch.SetException("No frame exists for window object.");
2300 return PP_MakeUndefined();
2303 ScopedPPVar result =
2304 try_catch.FromV8(frame->mainWorldScriptContext()->Global());
2305 DCHECK(!try_catch.HasException());
2306 return result.Release();
2309 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2310 if (!container_)
2311 return PP_MakeUndefined();
2312 RecordFlashJavaScriptUse();
2313 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2314 PepperTryCatchVar try_catch(this, &converter, NULL);
2315 ScopedPPVar result = try_catch.FromV8(container_->v8ObjectForElement());
2316 DCHECK(!try_catch.HasException());
2317 return result.Release();
2320 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2321 PP_Var script_var,
2322 PP_Var* exception) {
2323 if (!container_)
2324 return PP_MakeUndefined();
2325 RecordFlashJavaScriptUse();
2327 // Executing the script may remove the plugin from the DOM, so we need to keep
2328 // a reference to ourselves so that we can still process the result after the
2329 // WebBindings::evaluate() below.
2330 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2331 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2332 PepperTryCatchVar try_catch(this, &converter, exception);
2334 // Check for an exception due to the context being destroyed.
2335 if (try_catch.HasException())
2336 return PP_MakeUndefined();
2338 WebLocalFrame* frame = container_->element().document().frame();
2339 if (!frame) {
2340 try_catch.SetException("No frame to execute script in.");
2341 return PP_MakeUndefined();
2344 StringVar* script_string_var = StringVar::FromPPVar(script_var);
2345 if (!script_string_var) {
2346 try_catch.SetException("Script param to ExecuteScript must be a string.");
2347 return PP_MakeUndefined();
2350 std::string script_string = script_string_var->value();
2351 blink::WebScriptSource script(
2352 blink::WebString::fromUTF8(script_string.c_str()));
2353 v8::Handle<v8::Value> result;
2354 if (IsProcessingUserGesture()) {
2355 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2356 result = frame->executeScriptAndReturnValue(script);
2357 } else {
2358 result = frame->executeScriptAndReturnValue(script);
2361 ScopedPPVar var_result = try_catch.FromV8(result);
2362 if (try_catch.HasException())
2363 return PP_MakeUndefined();
2365 return var_result.Release();
2368 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2369 PP_Instance instance) {
2370 RenderThreadImpl* thread = RenderThreadImpl::current();
2371 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2374 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2375 PP_Instance instance) {
2376 RenderThreadImpl* thread = RenderThreadImpl::current();
2377 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2380 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2381 if (!render_frame_)
2382 return PP_MakeUndefined();
2383 return StringVar::StringToPPVar(
2384 render_frame_->render_view()->webkit_preferences().default_encoding);
2387 // These PPB_ContentDecryptor_Private calls are responses to
2388 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2389 // Therefore, |content_decryptor_delegate_| must have been initialized when
2390 // the following methods are called.
2391 void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2392 uint32 promise_id) {
2393 content_decryptor_delegate_->OnPromiseResolved(promise_id);
2396 void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2397 PP_Instance instance,
2398 uint32 promise_id,
2399 PP_Var session_id_var) {
2400 content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2401 session_id_var);
2404 void PepperPluginInstanceImpl::PromiseRejected(
2405 PP_Instance instance,
2406 uint32 promise_id,
2407 PP_CdmExceptionCode exception_code,
2408 uint32 system_code,
2409 PP_Var error_description_var) {
2410 content_decryptor_delegate_->OnPromiseRejected(
2411 promise_id, exception_code, system_code, error_description_var);
2414 void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2415 PP_Var session_id_var,
2416 PP_CdmMessageType message_type,
2417 PP_Var message_var,
2418 PP_Var legacy_destination_url) {
2419 content_decryptor_delegate_->OnSessionMessage(
2420 session_id_var, message_type, message_var, legacy_destination_url);
2423 void PepperPluginInstanceImpl::SessionKeysChange(
2424 PP_Instance instance,
2425 PP_Var session_id_var,
2426 PP_Bool has_additional_usable_key,
2427 uint32_t key_count,
2428 const struct PP_KeyInformation key_information[]) {
2429 content_decryptor_delegate_->OnSessionKeysChange(
2430 session_id_var, has_additional_usable_key, key_count, key_information);
2433 void PepperPluginInstanceImpl::SessionExpirationChange(
2434 PP_Instance instance,
2435 PP_Var session_id_var,
2436 PP_Time new_expiry_time) {
2437 content_decryptor_delegate_->OnSessionExpirationChange(session_id_var,
2438 new_expiry_time);
2441 void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2442 PP_Var session_id_var) {
2443 content_decryptor_delegate_->OnSessionClosed(session_id_var);
2446 void PepperPluginInstanceImpl::SessionError(PP_Instance instance,
2447 PP_Var session_id_var,
2448 PP_CdmExceptionCode exception_code,
2449 uint32 system_code,
2450 PP_Var error_description_var) {
2451 content_decryptor_delegate_->OnSessionError(
2452 session_id_var, exception_code, system_code, error_description_var);
2455 void PepperPluginInstanceImpl::DeliverBlock(
2456 PP_Instance instance,
2457 PP_Resource decrypted_block,
2458 const PP_DecryptedBlockInfo* block_info) {
2459 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2462 void PepperPluginInstanceImpl::DecoderInitializeDone(
2463 PP_Instance instance,
2464 PP_DecryptorStreamType decoder_type,
2465 uint32_t request_id,
2466 PP_Bool success) {
2467 content_decryptor_delegate_->DecoderInitializeDone(
2468 decoder_type, request_id, success);
2471 void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2472 PP_Instance instance,
2473 PP_DecryptorStreamType decoder_type,
2474 uint32_t request_id) {
2475 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2476 request_id);
2479 void PepperPluginInstanceImpl::DecoderResetDone(
2480 PP_Instance instance,
2481 PP_DecryptorStreamType decoder_type,
2482 uint32_t request_id) {
2483 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2486 void PepperPluginInstanceImpl::DeliverFrame(
2487 PP_Instance instance,
2488 PP_Resource decrypted_frame,
2489 const PP_DecryptedFrameInfo* frame_info) {
2490 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2493 void PepperPluginInstanceImpl::DeliverSamples(
2494 PP_Instance instance,
2495 PP_Resource audio_frames,
2496 const PP_DecryptedSampleInfo* sample_info) {
2497 content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2500 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2501 PP_Instance instance) {
2502 if (!LoadFindInterface())
2503 return;
2504 bool is_main_frame =
2505 render_frame_ &&
2506 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2507 if (!is_main_frame)
2508 return;
2509 render_frame_->render_view()->set_plugin_find_handler(this);
2512 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2513 PP_Instance instance,
2514 int32_t total,
2515 PP_Bool final_result) {
2516 DCHECK_NE(find_identifier_, -1);
2517 if (render_frame_) {
2518 render_frame_->reportFindInPageMatchCount(
2519 find_identifier_, total, PP_ToBool(final_result));
2523 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2524 int32_t index) {
2525 DCHECK_NE(find_identifier_, -1);
2526 if (render_frame_) {
2527 render_frame_->reportFindInPageSelection(
2528 find_identifier_, index + 1, blink::WebRect());
2532 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2533 const PP_Rect* tickmarks,
2534 uint32_t count) {
2535 if (!render_frame_ || !render_frame_->GetWebFrame())
2536 return;
2538 blink::WebVector<blink::WebRect> tickmarks_converted(
2539 static_cast<size_t>(count));
2540 for (uint32 i = 0; i < count; ++i) {
2541 tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2542 tickmarks[i].point.y,
2543 tickmarks[i].size.width,
2544 tickmarks[i].size.height);
2547 blink::WebFrame* frame = render_frame_->GetWebFrame();
2548 frame->setTickmarks(tickmarks_converted);
2551 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2552 return PP_FromBool(view_data_.is_fullscreen);
2555 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2556 PP_Bool fullscreen) {
2557 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2560 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2561 PP_Size* size) {
2562 blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2563 *size = PP_MakeSize(info.rect.width, info.rect.height);
2564 return PP_TRUE;
2567 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2568 PP_Instance instance,
2569 ppapi::SingletonResourceID id) {
2570 // Flash APIs and some others aren't implemented in-process.
2571 switch (id) {
2572 case ppapi::BROKER_SINGLETON_ID:
2573 case ppapi::BROWSER_FONT_SINGLETON_ID:
2574 case ppapi::FILE_MAPPING_SINGLETON_ID:
2575 case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2576 case ppapi::FLASH_FILE_SINGLETON_ID:
2577 case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2578 case ppapi::FLASH_SINGLETON_ID:
2579 case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2580 case ppapi::NETWORK_PROXY_SINGLETON_ID:
2581 case ppapi::PDF_SINGLETON_ID:
2582 case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2583 NOTIMPLEMENTED();
2584 return NULL;
2585 case ppapi::GAMEPAD_SINGLETON_ID:
2586 return gamepad_impl_.get();
2587 case ppapi::UMA_SINGLETON_ID: {
2588 if (!uma_private_impl_.get()) {
2589 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2590 if (host_impl->in_process_router()) {
2591 uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2592 host_impl->in_process_router()->GetPluginConnection(instance),
2593 instance);
2596 return uma_private_impl_.get();
2600 NOTREACHED();
2601 return NULL;
2604 int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2605 uint32_t event_classes) {
2606 input_event_mask_ |= event_classes;
2607 filtered_input_event_mask_ &= ~(event_classes);
2608 RequestInputEventsHelper(event_classes);
2609 return ValidateRequestInputEvents(false, event_classes);
2612 int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2613 PP_Instance instance,
2614 uint32_t event_classes) {
2615 filtered_input_event_mask_ |= event_classes;
2616 input_event_mask_ &= ~(event_classes);
2617 RequestInputEventsHelper(event_classes);
2618 return ValidateRequestInputEvents(true, event_classes);
2621 void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2622 uint32_t event_classes) {
2623 input_event_mask_ &= ~(event_classes);
2624 filtered_input_event_mask_ &= ~(event_classes);
2625 RequestInputEventsHelper(event_classes);
2628 void PepperPluginInstanceImpl::StartTrackingLatency(PP_Instance instance) {
2629 if (module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
2630 is_tracking_latency_ = true;
2633 void PepperPluginInstanceImpl::ZoomChanged(PP_Instance instance,
2634 double factor) {
2635 // We only want to tell the page to change its zoom if the whole page is the
2636 // plugin. If we're in an iframe, then don't do anything.
2637 if (!IsFullPagePlugin())
2638 return;
2639 container()->zoomLevelChanged(content::ZoomFactorToZoomLevel(factor));
2642 void PepperPluginInstanceImpl::ZoomLimitsChanged(PP_Instance instance,
2643 double minimum_factor,
2644 double maximum_factor) {
2645 if (!render_frame_)
2646 return;
2647 if (minimum_factor > maximum_factor) {
2648 NOTREACHED();
2649 return;
2651 double minimum_level = ZoomFactorToZoomLevel(minimum_factor);
2652 double maximum_level = ZoomFactorToZoomLevel(maximum_factor);
2653 render_frame_->render_view()->webview()->zoomLimitsChanged(minimum_level,
2654 maximum_level);
2657 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2658 PP_Var message) {
2659 PostMessageToJavaScript(message);
2662 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2663 PP_MouseCursor_Type type,
2664 PP_Resource image,
2665 const PP_Point* hot_spot) {
2666 if (!ValidateSetCursorParams(type, image, hot_spot))
2667 return PP_FALSE;
2669 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2670 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2671 return PP_TRUE;
2674 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2675 if (enter.failed())
2676 return PP_FALSE;
2677 PPB_ImageData_Impl* image_data =
2678 static_cast<PPB_ImageData_Impl*>(enter.object());
2680 ImageDataAutoMapper auto_mapper(image_data);
2681 if (!auto_mapper.is_valid())
2682 return PP_FALSE;
2684 scoped_ptr<WebCursorInfo> custom_cursor(
2685 new WebCursorInfo(WebCursorInfo::TypeCustom));
2686 custom_cursor->hotSpot.x = hot_spot->x;
2687 custom_cursor->hotSpot.y = hot_spot->y;
2689 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2690 // Make a deep copy, so that the cursor remains valid even after the original
2691 // image data gets freed.
2692 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2693 return PP_FALSE;
2696 DoSetCursor(custom_cursor.release());
2697 return PP_TRUE;
2700 int32_t PepperPluginInstanceImpl::LockMouse(
2701 PP_Instance instance,
2702 scoped_refptr<TrackedCallback> callback) {
2703 if (TrackedCallback::IsPending(lock_mouse_callback_))
2704 return PP_ERROR_INPROGRESS;
2706 if (IsMouseLocked())
2707 return PP_OK;
2709 if (!CanAccessMainFrame())
2710 return PP_ERROR_NOACCESS;
2712 if (!IsProcessingUserGesture())
2713 return PP_ERROR_NO_USER_GESTURE;
2715 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2716 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2717 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2718 // Open a user gesture here so the Webkit user gesture checks will succeed
2719 // for out-of-process plugins.
2720 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2721 if (!LockMouse())
2722 return PP_ERROR_FAILED;
2725 // Either mouselock succeeded or a Flash fullscreen is pending.
2726 lock_mouse_callback_ = callback;
2727 return PP_OK_COMPLETIONPENDING;
2730 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2731 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2734 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2735 PP_TextInput_Type type) {
2736 if (!render_frame_)
2737 return;
2738 int itype = type;
2739 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2740 itype = ui::TEXT_INPUT_TYPE_NONE;
2741 SetTextInputType(static_cast<ui::TextInputType>(itype));
2744 void PepperPluginInstanceImpl::UpdateCaretPosition(
2745 PP_Instance instance,
2746 const PP_Rect& caret,
2747 const PP_Rect& bounding_box) {
2748 if (!render_frame_)
2749 return;
2750 text_input_caret_ = PP_ToGfxRect(caret);
2751 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2752 text_input_caret_set_ = true;
2753 render_frame_->PepperCaretPositionChanged(this);
2756 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2757 if (render_frame_)
2758 render_frame_->PepperCancelComposition(this);
2761 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2762 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2763 // It can be optimized so that it won't call it back until the information
2764 // is really needed.
2766 // Avoid calling in nested context or else this will reenter the plugin. This
2767 // uses a weak pointer rather than exploiting the fact that this class is
2768 // refcounted because we don't actually want this operation to affect the
2769 // lifetime of the instance.
2770 base::MessageLoop::current()->PostTask(
2771 FROM_HERE,
2772 base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2773 weak_factory_.GetWeakPtr(),
2774 static_cast<size_t>(kExtraCharsForTextInput)));
2777 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2778 const char* text,
2779 uint32_t caret,
2780 uint32_t anchor) {
2781 if (!render_frame_)
2782 return;
2783 surrounding_text_ = text;
2784 selection_caret_ = caret;
2785 selection_anchor_ = anchor;
2786 render_frame_->PepperSelectionChanged(this);
2789 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2790 PP_Instance instance,
2791 PP_Var relative,
2792 PP_URLComponents_Dev* components) {
2793 StringVar* relative_string = StringVar::FromPPVar(relative);
2794 if (!relative_string)
2795 return PP_MakeNull();
2797 WebElement plugin_element = container()->element();
2798 GURL document_url = plugin_element.document().baseURL();
2799 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2800 document_url.Resolve(relative_string->value()), components);
2803 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2804 PP_Var url) {
2805 StringVar* url_string = StringVar::FromPPVar(url);
2806 if (!url_string)
2807 return PP_FALSE;
2809 blink::WebSecurityOrigin security_origin;
2810 if (!SecurityOriginForInstance(instance, &security_origin))
2811 return PP_FALSE;
2813 GURL gurl(url_string->value());
2814 if (!gurl.is_valid())
2815 return PP_FALSE;
2817 return PP_FromBool(security_origin.canRequest(gurl));
2820 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2821 PP_Instance instance,
2822 PP_Instance target) {
2823 blink::WebSecurityOrigin our_origin;
2824 if (!SecurityOriginForInstance(instance, &our_origin))
2825 return PP_FALSE;
2827 blink::WebSecurityOrigin target_origin;
2828 if (!SecurityOriginForInstance(instance, &target_origin))
2829 return PP_FALSE;
2831 return PP_FromBool(our_origin.canAccess(target_origin));
2834 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2835 PP_Instance instance,
2836 PP_URLComponents_Dev* components) {
2837 blink::WebDocument document = container()->element().document();
2838 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2839 components);
2842 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2843 PP_Instance instance,
2844 PP_URLComponents_Dev* components) {
2845 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2848 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2849 PP_Instance instance,
2850 PP_URLComponents_Dev* components) {
2851 blink::WebDocument document = container()->element().document();
2852 if (!full_frame_)
2853 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2854 components);
2855 WebLocalFrame* frame = document.frame();
2856 if (!frame)
2857 return PP_MakeUndefined();
2858 const WebURLRequest& request = frame->dataSource()->originalRequest();
2859 WebString referer = request.httpHeaderField("Referer");
2860 if (referer.isEmpty())
2861 return PP_MakeUndefined();
2862 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2863 components);
2866 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2867 scoped_refptr<PluginModule> module) {
2868 // Save the original module and switch over to the new one now that this
2869 // plugin is using the IPC-based proxy.
2870 original_module_ = module_;
2871 module_ = module;
2873 // For NaCl instances, remember the NaCl plugin instance interface, so we
2874 // can shut it down by calling its DidDestroy in our Delete() method.
2875 original_instance_interface_.reset(instance_interface_.release());
2877 base::Callback<const void*(const char*)> get_plugin_interface_func =
2878 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2879 PPP_Instance_Combined* ppp_instance_combined =
2880 PPP_Instance_Combined::Create(get_plugin_interface_func);
2881 if (!ppp_instance_combined) {
2882 // The proxy must support at least one usable PPP_Instance interface.
2883 // While this could be a failure to implement the interface in the NaCl
2884 // module, it is more likely that the NaCl process has crashed. Either
2885 // way, report that module initialization failed.
2886 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2889 instance_interface_.reset(ppp_instance_combined);
2890 // Clear all PPP interfaces we may have cached.
2891 plugin_find_interface_ = NULL;
2892 plugin_input_event_interface_ = NULL;
2893 checked_for_plugin_input_event_interface_ = false;
2894 plugin_mouse_lock_interface_ = NULL;
2895 plugin_pdf_interface_ = NULL;
2896 checked_for_plugin_pdf_interface_ = false;
2897 plugin_private_interface_ = NULL;
2898 plugin_textinput_interface_ = NULL;
2899 plugin_zoom_interface_ = NULL;
2901 // Re-send the DidCreate event via the proxy.
2902 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2903 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2904 if (!instance_interface_->DidCreate(
2905 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2906 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2907 if (message_channel_)
2908 message_channel_->Start();
2910 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2911 // event. This way, SendDidChangeView will send the "current" view
2912 // immediately (before other events like HandleDocumentLoad).
2913 sent_initial_did_change_view_ = false;
2914 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2915 SendDidChangeView();
2917 DCHECK(external_document_load_);
2918 external_document_load_ = false;
2919 if (!external_document_response_.isNull()) {
2920 document_loader_ = NULL;
2921 // Pass the response to the new proxy.
2922 HandleDocumentLoad(external_document_response_);
2923 external_document_response_ = blink::WebURLResponse();
2924 // Replay any document load events we've received to the real loader.
2925 external_document_loader_->ReplayReceivedData(document_loader_);
2926 external_document_loader_.reset(NULL);
2929 return PP_EXTERNAL_PLUGIN_OK;
2932 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2933 DCHECK(module);
2934 return module == module_.get() || module == original_module_.get();
2937 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2938 return HostGlobals::Get()->GetInstance(instance_id);
2941 RenderView* PepperPluginInstanceImpl::GetRenderView() {
2942 return render_frame_ ? render_frame_->render_view() : NULL;
2945 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2946 return container_;
2949 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
2951 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
2952 return HostGlobals::Get()->GetVarTracker();
2955 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
2957 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
2958 return module_->path();
2961 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
2962 float scale) {
2963 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
2965 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
2966 return 0;
2968 scoped_refptr<PPB_ImageData_Impl> image_data(
2969 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
2970 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
2971 image_skia_rep.pixel_width(),
2972 image_skia_rep.pixel_height(),
2973 false)) {
2974 return 0;
2977 ImageDataAutoMapper mapper(image_data.get());
2978 if (!mapper.is_valid())
2979 return 0;
2981 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
2982 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
2983 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
2984 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
2986 return image_data->GetReference();
2989 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
2990 const base::FilePath& file_path,
2991 ppapi::PpapiPermissions permissions,
2992 const IPC::ChannelHandle& channel_handle,
2993 base::ProcessId plugin_pid,
2994 int plugin_child_id) {
2995 // Create a new module for each instance of the external plugin that is using
2996 // the IPC based out-of-process proxy. We can't use the existing module,
2997 // because it is configured for the in-process plugin, and we must keep it
2998 // that way to allow the page to create other instances.
2999 scoped_refptr<PluginModule> external_plugin_module(
3000 module_->CreateModuleForExternalPluginInstance());
3002 RendererPpapiHostImpl* renderer_ppapi_host =
3003 external_plugin_module->CreateOutOfProcessModule(render_frame_,
3004 file_path,
3005 permissions,
3006 channel_handle,
3007 plugin_pid,
3008 plugin_child_id,
3009 true);
3010 if (!renderer_ppapi_host) {
3011 DLOG(ERROR) << "CreateExternalPluginModule() failed";
3012 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
3015 // Finally, switch the instance to the proxy.
3016 return external_plugin_module->InitAsProxiedExternalPlugin(this);
3019 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3020 always_on_top_ = on_top;
3023 void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
3024 cursor_.reset(cursor);
3025 if (fullscreen_container_) {
3026 fullscreen_container_->DidChangeCursor(*cursor);
3027 } else if (render_frame_) {
3028 render_frame_->PepperDidChangeCursor(this, *cursor);
3032 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3033 WebLocalFrame* frame = container()->element().document().frame();
3034 return frame->view()->mainFrame()->document().isPluginDocument();
3037 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3038 bool delay_report) {
3039 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3040 // Keep a reference on the stack. See NOTE above.
3041 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3043 // We check whether we are trying to switch to the state we're already going
3044 // to (i.e. if we're already switching to fullscreen but the fullscreen
3045 // container isn't ready yet, don't do anything more).
3046 if (fullscreen == FlashIsFullscreenOrPending())
3047 return true;
3049 if (!render_frame_)
3050 return false;
3051 if (fullscreen && !render_frame_->render_view()
3052 ->renderer_preferences()
3053 .plugin_fullscreen_allowed)
3054 return false;
3056 // Unbind current 2D or 3D graphics context.
3057 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3058 if (fullscreen) {
3059 DCHECK(!fullscreen_container_);
3060 fullscreen_container_ =
3061 render_frame_->CreatePepperFullscreenContainer(this);
3062 UpdateLayer(false);
3063 } else {
3064 DCHECK(fullscreen_container_);
3065 fullscreen_container_->Destroy();
3066 fullscreen_container_ = NULL;
3067 UpdateFlashFullscreenState(false);
3068 if (!delay_report) {
3069 ReportGeometry();
3070 } else {
3071 base::MessageLoop::current()->PostTask(
3072 FROM_HERE,
3073 base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3077 return true;
3080 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3081 if (flash_fullscreen_)
3082 return true;
3084 return container_->isRectTopmost(rect);
3087 int32_t PepperPluginInstanceImpl::Navigate(
3088 const ppapi::URLRequestInfoData& request,
3089 const char* target,
3090 bool from_user_action) {
3091 if (!container_)
3092 return PP_ERROR_FAILED;
3094 WebDocument document = container_->element().document();
3095 WebLocalFrame* frame = document.frame();
3096 if (!frame)
3097 return PP_ERROR_FAILED;
3099 ppapi::URLRequestInfoData completed_request = request;
3101 WebURLRequest web_request;
3102 if (!CreateWebURLRequest(
3103 pp_instance_, &completed_request, frame, &web_request)) {
3104 return PP_ERROR_FAILED;
3106 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3107 web_request.setHasUserGesture(from_user_action);
3109 GURL gurl(web_request.url());
3110 if (gurl.SchemeIs(url::kJavaScriptScheme)) {
3111 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3112 // allowed for security reasons.
3113 WebFrame* target_frame =
3114 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3115 if (target_frame != frame)
3116 return PP_ERROR_NOACCESS;
3118 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3119 // need that?
3120 WebString result = container_->executeScriptURL(gurl, from_user_action);
3121 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3124 // Only GETs and POSTs are supported.
3125 if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3126 return PP_ERROR_BADARGUMENT;
3128 WebString target_str = WebString::fromUTF8(target);
3129 container_->loadFrameRequest(web_request, target_str, false, NULL);
3130 return PP_OK;
3133 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3134 const base::FilePath& path) {
3135 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3136 PepperFileRefRendererHost* file_ref_host(
3137 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3138 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3139 scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3142 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3143 if (message_channel_)
3144 message_channel_->SetReadOnlyProperty(key, value);
3147 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3148 if (!container_)
3149 return false;
3150 blink::WebDocument containing_document = container_->element().document();
3152 if (!containing_document.frame() || !containing_document.frame()->view() ||
3153 !containing_document.frame()->view()->mainFrame()) {
3154 return false;
3156 blink::WebDocument main_document =
3157 containing_document.frame()->view()->mainFrame()->document();
3159 return containing_document.securityOrigin().canAccess(
3160 main_document.securityOrigin());
3163 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3164 WebElement element = container_->element();
3165 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3166 height_before_fullscreen_ =
3167 element.getAttribute(WebString::fromUTF8(kHeight));
3168 border_before_fullscreen_ =
3169 element.getAttribute(WebString::fromUTF8(kBorder));
3170 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3173 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3174 if (!render_frame_)
3175 return;
3176 blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3177 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3178 std::string width = StringPrintf("%d", screen_size_for_fullscreen_.width());
3179 std::string height = StringPrintf("%d", screen_size_for_fullscreen_.height());
3181 WebElement element = container_->element();
3182 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3183 element.setAttribute(WebString::fromUTF8(kHeight),
3184 WebString::fromUTF8(height));
3185 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3187 // There should be no style settings that matter in fullscreen mode,
3188 // so just replace them instead of appending.
3189 // NOTE: "position: fixed" and "display: block" reset the plugin and
3190 // using %% settings might not work without them (e.g. if the plugin is a
3191 // child of a container element).
3192 std::string style;
3193 style += StringPrintf("width: %s !important; ", width.c_str());
3194 style += StringPrintf("height: %s !important; ", height.c_str());
3195 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3196 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3199 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3200 screen_size_for_fullscreen_ = gfx::Size();
3201 WebElement element = container_->element();
3202 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3203 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3204 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3205 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3208 bool PepperPluginInstanceImpl::IsMouseLocked() {
3209 return GetMouseLockDispatcher()->IsMouseLockedTo(
3210 GetOrCreateLockTargetAdapter());
3213 bool PepperPluginInstanceImpl::LockMouse() {
3214 return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3217 MouseLockDispatcher::LockTarget*
3218 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3219 if (!lock_target_.get()) {
3220 lock_target_.reset(new PluginInstanceLockTarget(this));
3222 return lock_target_.get();
3225 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3226 if (flash_fullscreen_) {
3227 RenderWidgetFullscreenPepper* container =
3228 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3229 return container->mouse_lock_dispatcher();
3230 } else if (render_frame_) {
3231 return render_frame_->render_view()->mouse_lock_dispatcher();
3233 return NULL;
3236 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3237 if (lock_target_.get()) {
3238 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3239 lock_target_.reset();
3243 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3244 const blink::WebURLResponse& response,
3245 int pending_host_id,
3246 const ppapi::URLResponseInfoData& data) {
3247 if (is_deleted_)
3248 return;
3250 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3252 if (host_impl->in_process_router()) {
3253 // Running in-process, we can just create the resource and call the
3254 // PPP_Instance function directly.
3255 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3256 new ppapi::proxy::URLLoaderResource(
3257 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3258 pp_instance(),
3259 pending_host_id,
3260 data));
3262 PP_Resource loader_pp_resource = loader_resource->GetReference();
3263 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3264 loader_pp_resource))
3265 loader_resource->Close();
3266 // We don't pass a ref into the plugin, if it wants one, it will have taken
3267 // an additional one.
3268 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3269 loader_pp_resource);
3270 } else {
3271 // Running out-of-process. Initiate an IPC call to notify the plugin
3272 // process.
3273 ppapi::proxy::HostDispatcher* dispatcher =
3274 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3275 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3276 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3280 void PepperPluginInstanceImpl::RecordFlashJavaScriptUse() {
3281 if (initialized_ && !javascript_used_ && is_flash_plugin_) {
3282 javascript_used_ = true;
3283 RenderThread::Get()->RecordAction(
3284 base::UserMetricsAction("Flash.JavaScriptUsed"));
3288 } // namespace content