Chromecast: extracts Linux window creation code to a common place.
[chromium-blink-merge.git] / content / renderer / pepper / pepper_plugin_instance_impl.cc
blobee9295d378830c35e3d81cf4f97420a28bd293a1
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
7 #include "base/bind.h"
8 #include "base/callback_helpers.h"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "base/memory/linked_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/stl_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/strings/utf_offset_string_conversions.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "cc/base/latency_info_swap_promise.h"
20 #include "cc/blink/web_layer_impl.h"
21 #include "cc/layers/texture_layer.h"
22 #include "cc/trees/layer_tree_host.h"
23 #include "content/common/content_constants_internal.h"
24 #include "content/common/input/web_input_event_traits.h"
25 #include "content/public/common/content_constants.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/page_zoom.h"
28 #include "content/public/renderer/content_renderer_client.h"
29 #include "content/renderer/gpu/render_widget_compositor.h"
30 #include "content/renderer/pepper/content_decryptor_delegate.h"
31 #include "content/renderer/pepper/event_conversion.h"
32 #include "content/renderer/pepper/fullscreen_container.h"
33 #include "content/renderer/pepper/gfx_conversion.h"
34 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
35 #include "content/renderer/pepper/host_globals.h"
36 #include "content/renderer/pepper/message_channel.h"
37 #include "content/renderer/pepper/pepper_browser_connection.h"
38 #include "content/renderer/pepper/pepper_compositor_host.h"
39 #include "content/renderer/pepper/pepper_file_ref_renderer_host.h"
40 #include "content/renderer/pepper/pepper_graphics_2d_host.h"
41 #include "content/renderer/pepper/pepper_in_process_router.h"
42 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
43 #include "content/renderer/pepper/pepper_plugin_instance_throttler.h"
44 #include "content/renderer/pepper/pepper_try_catch.h"
45 #include "content/renderer/pepper/pepper_url_loader_host.h"
46 #include "content/renderer/pepper/plugin_module.h"
47 #include "content/renderer/pepper/plugin_object.h"
48 #include "content/renderer/pepper/ppapi_preferences_builder.h"
49 #include "content/renderer/pepper/ppb_buffer_impl.h"
50 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
51 #include "content/renderer/pepper/ppb_image_data_impl.h"
52 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
53 #include "content/renderer/pepper/url_request_info_util.h"
54 #include "content/renderer/pepper/url_response_info_util.h"
55 #include "content/renderer/render_frame_impl.h"
56 #include "content/renderer/render_thread_impl.h"
57 #include "content/renderer/render_view_impl.h"
58 #include "content/renderer/render_widget.h"
59 #include "content/renderer/render_widget_fullscreen_pepper.h"
60 #include "content/renderer/sad_plugin.h"
61 #include "media/base/audio_hardware_config.h"
62 #include "ppapi/c/dev/ppb_zoom_dev.h"
63 #include "ppapi/c/dev/ppp_selection_dev.h"
64 #include "ppapi/c/dev/ppp_text_input_dev.h"
65 #include "ppapi/c/dev/ppp_zoom_dev.h"
66 #include "ppapi/c/pp_rect.h"
67 #include "ppapi/c/ppb_audio_config.h"
68 #include "ppapi/c/ppb_core.h"
69 #include "ppapi/c/ppb_gamepad.h"
70 #include "ppapi/c/ppp_input_event.h"
71 #include "ppapi/c/ppp_instance.h"
72 #include "ppapi/c/ppp_messaging.h"
73 #include "ppapi/c/ppp_mouse_lock.h"
74 #include "ppapi/c/private/ppb_find_private.h"
75 #include "ppapi/c/private/ppp_find_private.h"
76 #include "ppapi/c/private/ppp_instance_private.h"
77 #include "ppapi/c/private/ppp_pdf.h"
78 #include "ppapi/host/ppapi_host.h"
79 #include "ppapi/proxy/ppapi_messages.h"
80 #include "ppapi/proxy/serialized_var.h"
81 #include "ppapi/proxy/uma_private_resource.h"
82 #include "ppapi/proxy/url_loader_resource.h"
83 #include "ppapi/shared_impl/ppapi_permissions.h"
84 #include "ppapi/shared_impl/ppapi_preferences.h"
85 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
86 #include "ppapi/shared_impl/ppb_input_event_shared.h"
87 #include "ppapi/shared_impl/ppb_url_util_shared.h"
88 #include "ppapi/shared_impl/ppb_view_shared.h"
89 #include "ppapi/shared_impl/ppp_instance_combined.h"
90 #include "ppapi/shared_impl/resource.h"
91 #include "ppapi/shared_impl/scoped_pp_resource.h"
92 #include "ppapi/shared_impl/scoped_pp_var.h"
93 #include "ppapi/shared_impl/time_conversion.h"
94 #include "ppapi/shared_impl/url_request_info_data.h"
95 #include "ppapi/shared_impl/var.h"
96 #include "ppapi/thunk/enter.h"
97 #include "ppapi/thunk/ppb_buffer_api.h"
98 #include "printing/metafile_skia_wrapper.h"
99 #include "printing/pdf_metafile_skia.h"
100 #include "skia/ext/platform_canvas.h"
101 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
102 #include "third_party/WebKit/public/platform/WebGamepads.h"
103 #include "third_party/WebKit/public/platform/WebRect.h"
104 #include "third_party/WebKit/public/platform/WebString.h"
105 #include "third_party/WebKit/public/platform/WebURL.h"
106 #include "third_party/WebKit/public/platform/WebURLError.h"
107 #include "third_party/WebKit/public/platform/WebURLRequest.h"
108 #include "third_party/WebKit/public/web/WebBindings.h"
109 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
110 #include "third_party/WebKit/public/web/WebDataSource.h"
111 #include "third_party/WebKit/public/web/WebDocument.h"
112 #include "third_party/WebKit/public/web/WebElement.h"
113 #include "third_party/WebKit/public/web/WebInputEvent.h"
114 #include "third_party/WebKit/public/web/WebLocalFrame.h"
115 #include "third_party/WebKit/public/web/WebPluginContainer.h"
116 #include "third_party/WebKit/public/web/WebPrintParams.h"
117 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
118 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
119 #include "third_party/WebKit/public/web/WebScriptSource.h"
120 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
121 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
122 #include "third_party/WebKit/public/web/WebView.h"
123 #include "third_party/khronos/GLES2/gl2.h"
124 #include "ui/gfx/image/image_skia.h"
125 #include "ui/gfx/image/image_skia_rep.h"
126 #include "ui/gfx/range/range.h"
127 #include "v8/include/v8.h"
129 #if defined(OS_CHROMEOS)
130 #include "ui/events/keycodes/keyboard_codes_posix.h"
131 #endif
133 #if defined(OS_WIN)
134 #include "base/metrics/histogram.h"
135 #include "base/win/windows_version.h"
136 #include "skia/ext/platform_canvas.h"
137 #endif
139 using base::StringPrintf;
140 using ppapi::InputEventData;
141 using ppapi::PpapiGlobals;
142 using ppapi::PPB_InputEvent_Shared;
143 using ppapi::PPB_View_Shared;
144 using ppapi::PPP_Instance_Combined;
145 using ppapi::Resource;
146 using ppapi::ScopedPPResource;
147 using ppapi::ScopedPPVar;
148 using ppapi::StringVar;
149 using ppapi::TrackedCallback;
150 using ppapi::thunk::EnterResourceNoLock;
151 using ppapi::thunk::PPB_Buffer_API;
152 using ppapi::thunk::PPB_Gamepad_API;
153 using ppapi::thunk::PPB_Graphics2D_API;
154 using ppapi::thunk::PPB_Graphics3D_API;
155 using ppapi::thunk::PPB_ImageData_API;
156 using ppapi::Var;
157 using ppapi::ArrayBufferVar;
158 using ppapi::ViewData;
159 using blink::WebBindings;
160 using blink::WebCanvas;
161 using blink::WebCursorInfo;
162 using blink::WebDocument;
163 using blink::WebElement;
164 using blink::WebFrame;
165 using blink::WebInputEvent;
166 using blink::WebLocalFrame;
167 using blink::WebPlugin;
168 using blink::WebPluginContainer;
169 using blink::WebPrintParams;
170 using blink::WebPrintScalingOption;
171 using blink::WebScopedUserGesture;
172 using blink::WebString;
173 using blink::WebURLError;
174 using blink::WebURLLoader;
175 using blink::WebURLLoaderClient;
176 using blink::WebURLRequest;
177 using blink::WebURLResponse;
178 using blink::WebUserGestureIndicator;
179 using blink::WebUserGestureToken;
180 using blink::WebView;
182 namespace content {
184 namespace {
186 // Check PP_TextInput_Type and ui::TextInputType are kept in sync.
187 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NONE) == int(PP_TEXTINPUT_TYPE_NONE),
188 mismatching_enums);
189 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TEXT) == int(PP_TEXTINPUT_TYPE_TEXT),
190 mismatching_enums);
191 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_PASSWORD) ==
192 int(PP_TEXTINPUT_TYPE_PASSWORD),
193 mismatching_enums);
194 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_SEARCH) == int(PP_TEXTINPUT_TYPE_SEARCH),
195 mismatching_enums);
196 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_EMAIL) == int(PP_TEXTINPUT_TYPE_EMAIL),
197 mismatching_enums);
198 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NUMBER) == int(PP_TEXTINPUT_TYPE_NUMBER),
199 mismatching_enums);
200 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TELEPHONE) ==
201 int(PP_TEXTINPUT_TYPE_TELEPHONE),
202 mismatching_enums);
203 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_URL) == int(PP_TEXTINPUT_TYPE_URL),
204 mismatching_enums);
206 // The default text input type is to regard the plugin always accept text input.
207 // This is for allowing users to use input methods even on completely-IME-
208 // unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
209 // Plugins need to explicitly opt out the text input mode if they know
210 // that they don't accept texts.
211 const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
213 #define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
214 COMPILE_ASSERT(static_cast<int>(WebCursorInfo::webkit_name) == \
215 static_cast<int>(np_name), \
216 mismatching_enums)
218 #define COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(webkit_name, pp_name) \
219 COMPILE_ASSERT(static_cast<int>(webkit_name) == static_cast<int>(pp_name), \
220 mismatching_enums)
222 // <embed>/<object> attributes.
223 const char kWidth[] = "width";
224 const char kHeight[] = "height";
225 const char kBorder[] = "border"; // According to w3c, deprecated.
226 const char kStyle[] = "style";
228 COMPILE_ASSERT_MATCHING_ENUM(TypePointer, PP_MOUSECURSOR_TYPE_POINTER);
229 COMPILE_ASSERT_MATCHING_ENUM(TypeCross, PP_MOUSECURSOR_TYPE_CROSS);
230 COMPILE_ASSERT_MATCHING_ENUM(TypeHand, PP_MOUSECURSOR_TYPE_HAND);
231 COMPILE_ASSERT_MATCHING_ENUM(TypeIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
232 COMPILE_ASSERT_MATCHING_ENUM(TypeWait, PP_MOUSECURSOR_TYPE_WAIT);
233 COMPILE_ASSERT_MATCHING_ENUM(TypeHelp, PP_MOUSECURSOR_TYPE_HELP);
234 COMPILE_ASSERT_MATCHING_ENUM(TypeEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
235 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
236 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastResize,
237 PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
238 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestResize,
239 PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
240 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
241 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastResize,
242 PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
243 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestResize,
244 PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
245 COMPILE_ASSERT_MATCHING_ENUM(TypeWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
246 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
247 PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
248 COMPILE_ASSERT_MATCHING_ENUM(TypeEastWestResize,
249 PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
250 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
251 PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
252 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
253 PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
254 COMPILE_ASSERT_MATCHING_ENUM(TypeColumnResize,
255 PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
256 COMPILE_ASSERT_MATCHING_ENUM(TypeRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
257 COMPILE_ASSERT_MATCHING_ENUM(TypeMiddlePanning,
258 PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
259 COMPILE_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
260 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthPanning,
261 PP_MOUSECURSOR_TYPE_NORTHPANNING);
262 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
263 PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
264 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
265 PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
266 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthPanning,
267 PP_MOUSECURSOR_TYPE_SOUTHPANNING);
268 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
269 PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
270 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
271 PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
272 COMPILE_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
273 COMPILE_ASSERT_MATCHING_ENUM(TypeMove, PP_MOUSECURSOR_TYPE_MOVE);
274 COMPILE_ASSERT_MATCHING_ENUM(TypeVerticalText,
275 PP_MOUSECURSOR_TYPE_VERTICALTEXT);
276 COMPILE_ASSERT_MATCHING_ENUM(TypeCell, PP_MOUSECURSOR_TYPE_CELL);
277 COMPILE_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
278 COMPILE_ASSERT_MATCHING_ENUM(TypeAlias, PP_MOUSECURSOR_TYPE_ALIAS);
279 COMPILE_ASSERT_MATCHING_ENUM(TypeProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
280 COMPILE_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
281 COMPILE_ASSERT_MATCHING_ENUM(TypeCopy, PP_MOUSECURSOR_TYPE_COPY);
282 COMPILE_ASSERT_MATCHING_ENUM(TypeNone, PP_MOUSECURSOR_TYPE_NONE);
283 COMPILE_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
284 COMPILE_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
285 COMPILE_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
286 COMPILE_ASSERT_MATCHING_ENUM(TypeGrab, PP_MOUSECURSOR_TYPE_GRAB);
287 COMPILE_ASSERT_MATCHING_ENUM(TypeGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
288 // Do not assert WebCursorInfo::TypeCustom == PP_CURSORTYPE_CUSTOM;
289 // PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
291 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(blink::WebPrintScalingOptionNone,
292 PP_PRINTSCALINGOPTION_NONE);
293 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
294 blink::WebPrintScalingOptionFitToPrintableArea,
295 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
296 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
297 blink::WebPrintScalingOptionSourceSize,
298 PP_PRINTSCALINGOPTION_SOURCE_SIZE);
300 // Sets |*security_origin| to be the WebKit security origin associated with the
301 // document containing the given plugin instance. On success, returns true. If
302 // the instance is invalid, returns false and |*security_origin| will be
303 // unchanged.
304 bool SecurityOriginForInstance(PP_Instance instance_id,
305 blink::WebSecurityOrigin* security_origin) {
306 PepperPluginInstanceImpl* instance =
307 HostGlobals::Get()->GetInstance(instance_id);
308 if (!instance)
309 return false;
311 WebElement plugin_element = instance->container()->element();
312 *security_origin = plugin_element.document().securityOrigin();
313 return true;
316 // Convert the given vector to an array of C-strings. The strings in the
317 // returned vector are only guaranteed valid so long as the vector of strings
318 // is not modified.
319 scoped_ptr<const char* []> StringVectorToArgArray(
320 const std::vector<std::string>& vector) {
321 scoped_ptr<const char * []> array(new const char* [vector.size()]);
322 for (size_t i = 0; i < vector.size(); ++i)
323 array[i] = vector[i].c_str();
324 return array.Pass();
327 // Returns true if this is a "system reserved" key which should not be sent to
328 // a plugin. Some poorly behaving plugins (like Flash) incorrectly report that
329 // they handle all keys sent to them. This can prevent keystrokes from working
330 // for things like screen brightness and volume control.
331 bool IsReservedSystemInputEvent(const blink::WebInputEvent& event) {
332 #if defined(OS_CHROMEOS)
333 if (event.type != WebInputEvent::KeyDown &&
334 event.type != WebInputEvent::KeyUp)
335 return false;
336 const blink::WebKeyboardEvent& key_event =
337 static_cast<const blink::WebKeyboardEvent&>(event);
338 switch (key_event.windowsKeyCode) {
339 case ui::VKEY_BRIGHTNESS_DOWN:
340 case ui::VKEY_BRIGHTNESS_UP:
341 case ui::VKEY_KBD_BRIGHTNESS_DOWN:
342 case ui::VKEY_KBD_BRIGHTNESS_UP:
343 case ui::VKEY_VOLUME_MUTE:
344 case ui::VKEY_VOLUME_DOWN:
345 case ui::VKEY_VOLUME_UP:
346 return true;
347 default:
348 return false;
350 #endif // defined(OS_CHROMEOS)
351 return false;
354 class PluginInstanceLockTarget : public MouseLockDispatcher::LockTarget {
355 public:
356 PluginInstanceLockTarget(PepperPluginInstanceImpl* plugin)
357 : plugin_(plugin) {}
359 virtual void OnLockMouseACK(bool succeeded) override {
360 plugin_->OnLockMouseACK(succeeded);
363 virtual void OnMouseLockLost() override { plugin_->OnMouseLockLost(); }
365 virtual bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event)
366 override {
367 plugin_->HandleMouseLockedInputEvent(event);
368 return true;
371 private:
372 PepperPluginInstanceImpl* plugin_;
375 void InitLatencyInfo(ui::LatencyInfo* new_latency,
376 const ui::LatencyInfo* old_latency,
377 blink::WebInputEvent::Type type,
378 int64 input_sequence) {
379 new_latency->AddLatencyNumber(
380 ui::INPUT_EVENT_LATENCY_BEGIN_PLUGIN_COMPONENT,
382 input_sequence);
383 new_latency->TraceEventType(WebInputEventTraits::GetName(type));
384 if (old_latency) {
385 new_latency->CopyLatencyFrom(*old_latency,
386 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
387 new_latency->CopyLatencyFrom(*old_latency,
388 ui::INPUT_EVENT_LATENCY_UI_COMPONENT);
392 } // namespace
394 // static
395 PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
396 RenderFrameImpl* render_frame,
397 PluginModule* module,
398 WebPluginContainer* container,
399 const GURL& plugin_url) {
400 base::Callback<const void*(const char*)> get_plugin_interface_func =
401 base::Bind(&PluginModule::GetPluginInterface, module);
402 PPP_Instance_Combined* ppp_instance_combined =
403 PPP_Instance_Combined::Create(get_plugin_interface_func);
404 if (!ppp_instance_combined)
405 return NULL;
407 return new PepperPluginInstanceImpl(render_frame,
408 module,
409 ppp_instance_combined,
410 container,
411 plugin_url);
414 PepperPluginInstanceImpl::ExternalDocumentLoader::ExternalDocumentLoader()
415 : finished_loading_(false) {}
417 PepperPluginInstanceImpl::ExternalDocumentLoader::~ExternalDocumentLoader() {}
419 void PepperPluginInstanceImpl::ExternalDocumentLoader::ReplayReceivedData(
420 WebURLLoaderClient* document_loader) {
421 for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
422 ++it) {
423 document_loader->didReceiveData(
424 NULL, it->c_str(), it->length(), 0 /* encoded_data_length */);
426 if (finished_loading_) {
427 document_loader->didFinishLoading(
428 NULL,
429 0 /* finish_time */,
430 blink::WebURLLoaderClient::kUnknownEncodedDataLength);
432 if (error_.get()) {
433 document_loader->didFail(NULL, *error_);
437 void PepperPluginInstanceImpl::ExternalDocumentLoader::didReceiveData(
438 WebURLLoader* loader,
439 const char* data,
440 int data_length,
441 int encoded_data_length) {
442 data_.push_back(std::string(data, data_length));
445 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFinishLoading(
446 WebURLLoader* loader,
447 double finish_time,
448 int64_t total_encoded_data_length) {
449 DCHECK(!finished_loading_);
450 finished_loading_ = true;
453 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFail(
454 WebURLLoader* loader,
455 const WebURLError& error) {
456 DCHECK(!error_.get());
457 error_.reset(new WebURLError(error));
460 PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
461 : Resource(ppapi::Resource::Untracked()) {}
463 PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
465 PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
466 return this;
469 void PepperPluginInstanceImpl::GamepadImpl::Sample(
470 PP_Instance instance,
471 PP_GamepadsSampleData* data) {
472 blink::WebGamepads webkit_data;
473 RenderThreadImpl::current()->SampleGamepads(&webkit_data);
474 ConvertWebKitGamepadData(bit_cast<ppapi::WebKitGamepads>(webkit_data), data);
477 PepperPluginInstanceImpl::PepperPluginInstanceImpl(
478 RenderFrameImpl* render_frame,
479 PluginModule* module,
480 ppapi::PPP_Instance_Combined* instance_interface,
481 WebPluginContainer* container,
482 const GURL& plugin_url)
483 : RenderFrameObserver(render_frame),
484 render_frame_(render_frame),
485 module_(module),
486 instance_interface_(instance_interface),
487 pp_instance_(0),
488 container_(container),
489 layer_bound_to_fullscreen_(false),
490 layer_is_hardware_(false),
491 plugin_url_(plugin_url),
492 power_saver_enabled_(false),
493 plugin_throttled_(false),
494 full_frame_(false),
495 sent_initial_did_change_view_(false),
496 bound_graphics_2d_platform_(NULL),
497 bound_compositor_(NULL),
498 has_webkit_focus_(false),
499 has_content_area_focus_(false),
500 find_identifier_(-1),
501 plugin_find_interface_(NULL),
502 plugin_input_event_interface_(NULL),
503 plugin_mouse_lock_interface_(NULL),
504 plugin_pdf_interface_(NULL),
505 plugin_private_interface_(NULL),
506 plugin_textinput_interface_(NULL),
507 plugin_zoom_interface_(NULL),
508 checked_for_plugin_input_event_interface_(false),
509 checked_for_plugin_pdf_interface_(false),
510 gamepad_impl_(new GamepadImpl()),
511 uma_private_impl_(NULL),
512 plugin_print_interface_(NULL),
513 plugin_graphics_3d_interface_(NULL),
514 always_on_top_(false),
515 fullscreen_container_(NULL),
516 flash_fullscreen_(false),
517 desired_fullscreen_state_(false),
518 message_channel_(NULL),
519 sad_plugin_(NULL),
520 input_event_mask_(0),
521 filtered_input_event_mask_(0),
522 text_input_type_(kPluginDefaultTextInputType),
523 text_input_caret_(0, 0, 0, 0),
524 text_input_caret_bounds_(0, 0, 0, 0),
525 text_input_caret_set_(false),
526 selection_caret_(0),
527 selection_anchor_(0),
528 pending_user_gesture_(0.0),
529 document_loader_(NULL),
530 external_document_load_(false),
531 isolate_(v8::Isolate::GetCurrent()),
532 is_deleted_(false),
533 last_input_number_(0),
534 is_tracking_latency_(false),
535 view_change_weak_ptr_factory_(this),
536 weak_factory_(this) {
537 pp_instance_ = HostGlobals::Get()->AddInstance(this);
539 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
540 module_->InstanceCreated(this);
542 if (render_frame) { // NULL in tests
543 render_frame->render_view()->PepperInstanceCreated(this);
544 // Bind a callback now so that we can inform the RenderViewImpl when we are
545 // destroyed. This works around a temporary problem stemming from work to
546 // move parts of RenderViewImpl in to RenderFrameImpl (see
547 // crbug.com/245126). If destruction happens in this order:
548 // 1) RenderFrameImpl
549 // 2) PepperPluginInstanceImpl
550 // 3) RenderViewImpl
551 // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
552 // to the RenderViewImpl. But when the instance is destroyed, it still
553 // needs to inform the RenderViewImpl that it has gone away, otherwise
554 // between (2) and (3), the RenderViewImpl will still have the dead
555 // instance in its active set, and so might make calls on the deleted
556 // instance. See crbug.com/343576 for more information. Once the plugin
557 // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
558 // can be a little bit simplified by instead making a direct call on
559 // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
560 instance_deleted_callback_ =
561 base::Bind(&RenderViewImpl::PepperInstanceDeleted,
562 render_frame->render_view()->AsWeakPtr(),
563 base::Unretained(this));
564 view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
566 // Set the initial focus.
567 SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
569 if (!module_->IsProxied()) {
570 PepperBrowserConnection* browser_connection =
571 PepperBrowserConnection::Get(render_frame_);
572 browser_connection->DidCreateInProcessInstance(
573 pp_instance(),
574 render_frame_->GetRoutingID(),
575 container_->element().document().url(),
576 GetPluginURL());
580 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
581 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
583 if (GetContentClient()->renderer() && // NULL in unit tests.
584 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
585 external_document_load_ = true;
587 // TODO(tommycli): Insert heuristics to determine whether plugin content
588 // is peripheral here.
589 bool is_peripheral_content = true;
590 power_saver_enabled_ = is_peripheral_content &&
591 module->name() == kFlashPluginName &&
592 CommandLine::ForCurrentProcess()->HasSwitch(
593 switches::kEnablePluginPowerSaver);
595 if (power_saver_enabled_) {
596 throttler_.reset(new PepperPluginInstanceThrottler(
597 base::Bind(&PepperPluginInstanceImpl::SetPluginThrottled,
598 weak_factory_.GetWeakPtr(), true /* throttled */)));
602 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
603 DCHECK(!fullscreen_container_);
605 // Notify all the plugin objects of deletion. This will prevent blink from
606 // calling into the plugin any more.
608 // Swap out the set so we can delete from it (the objects will try to
609 // unregister themselves inside the delete call).
610 PluginObjectSet plugin_object_copy;
611 live_plugin_objects_.swap(plugin_object_copy);
612 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
613 i != plugin_object_copy.end();
614 ++i) {
615 (*i)->InstanceDeleted();
618 if (message_channel_)
619 message_channel_->InstanceDeleted();
620 message_channel_object_.Reset();
622 if (TrackedCallback::IsPending(lock_mouse_callback_))
623 lock_mouse_callback_->Abort();
625 if (!instance_deleted_callback_.is_null())
626 instance_deleted_callback_.Run();
628 if (!module_->IsProxied() && render_frame_) {
629 PepperBrowserConnection* browser_connection =
630 PepperBrowserConnection::Get(render_frame_);
631 browser_connection->DidDeleteInProcessInstance(pp_instance());
634 UnSetAndDeleteLockTargetAdapter();
635 module_->InstanceDeleted(this);
636 // If we switched from the NaCl plugin module, notify it too.
637 if (original_module_.get())
638 original_module_->InstanceDeleted(this);
640 // This should be last since some of the above "instance deleted" calls will
641 // want to look up in the global map to get info off of our object.
642 HostGlobals::Get()->InstanceDeleted(pp_instance_);
645 // NOTE: Any of these methods that calls into the plugin needs to take into
646 // account that the plugin may use Var to remove the <embed> from the DOM, which
647 // will make the PepperWebPluginImpl drop its reference, usually the last one.
648 // If a method needs to access a member of the instance after the call has
649 // returned, then it needs to keep its own reference on the stack.
651 v8::Local<v8::Object> PepperPluginInstanceImpl::GetMessageChannelObject() {
652 return v8::Local<v8::Object>::New(isolate_, message_channel_object_);
655 void PepperPluginInstanceImpl::MessageChannelDestroyed() {
656 message_channel_ = NULL;
657 message_channel_object_.Reset();
660 v8::Local<v8::Context> PepperPluginInstanceImpl::GetMainWorldContext() {
661 if (!container_)
662 return v8::Handle<v8::Context>();
664 if (container_->element().isNull())
665 return v8::Handle<v8::Context>();
667 if (container_->element().document().isNull())
668 return v8::Handle<v8::Context>();
670 if (!container_->element().document().frame())
671 return v8::Handle<v8::Context>();
673 v8::Local<v8::Context> context =
674 container_->element().document().frame()->mainWorldScriptContext();
675 DCHECK(context->GetIsolate() == isolate_);
676 return context;
679 void PepperPluginInstanceImpl::Delete() {
680 is_deleted_ = true;
682 if (render_frame_ &&
683 render_frame_->render_view()->plugin_find_handler() == this) {
684 render_frame_->render_view()->set_plugin_find_handler(NULL);
687 // Keep a reference on the stack. See NOTE above.
688 scoped_refptr<PepperPluginInstanceImpl> ref(this);
689 // Force the MessageChannel to release its "passthrough object" which should
690 // release our last reference to the "InstanceObject" and will probably
691 // destroy it. We want to do this prior to calling DidDestroy in case the
692 // destructor of the instance object tries to use the instance.
693 if (message_channel_)
694 message_channel_->SetPassthroughObject(v8::Handle<v8::Object>());
695 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
696 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
697 // since there is little that it can do at this point.
698 if (original_instance_interface_)
699 original_instance_interface_->DidDestroy(pp_instance());
700 else
701 instance_interface_->DidDestroy(pp_instance());
702 // Ensure we don't attempt to call functions on the destroyed instance.
703 original_instance_interface_.reset();
704 instance_interface_.reset();
706 if (fullscreen_container_) {
707 fullscreen_container_->Destroy();
708 fullscreen_container_ = NULL;
711 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
712 // leaks the graphics 2D, it may actually get cleaned up after our
713 // destruction, so we need its pointers to be up-to-date.
714 BindGraphics(pp_instance(), 0);
715 container_ = NULL;
718 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
720 void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
721 const gfx::Rect& plugin_rect,
722 const gfx::Rect& paint_rect) {
723 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
724 if (module()->is_crashed()) {
725 // Crashed plugin painting.
726 if (!sad_plugin_) // Lazily initialize bitmap.
727 sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
728 if (sad_plugin_)
729 PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
730 return;
733 if (bound_graphics_2d_platform_)
734 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
737 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
738 if (fullscreen_container_) {
739 if (rect.IsEmpty())
740 fullscreen_container_->Invalidate();
741 else
742 fullscreen_container_->InvalidateRect(rect);
743 } else {
744 if (!container_ || view_data_.rect.size.width == 0 ||
745 view_data_.rect.size.height == 0)
746 return; // Nothing to do.
747 if (rect.IsEmpty())
748 container_->invalidate();
749 else
750 container_->invalidateRect(rect);
753 cc::Layer* layer =
754 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
755 if (layer) {
756 if (rect.IsEmpty()) {
757 layer->SetNeedsDisplay();
758 } else {
759 layer->SetNeedsDisplayRect(rect);
764 void PepperPluginInstanceImpl::ScrollRect(int dx,
765 int dy,
766 const gfx::Rect& rect) {
767 cc::Layer* layer =
768 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
769 if (layer) {
770 InvalidateRect(rect);
771 } else if (fullscreen_container_) {
772 fullscreen_container_->ScrollRect(dx, dy, rect);
773 } else {
774 if (full_frame_ && !IsViewAccelerated()) {
775 container_->scrollRect(rect);
776 } else {
777 // Can't do optimized scrolling since there could be other elements on top
778 // of us or the view renders via the accelerated compositor which is
779 // incompatible with the move and backfill scrolling model.
780 InvalidateRect(rect);
785 void PepperPluginInstanceImpl::CommitBackingTexture() {
786 if (!texture_layer_.get())
787 return;
788 gpu::Mailbox mailbox;
789 uint32 sync_point = 0;
790 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
791 DCHECK(!mailbox.IsZero());
792 DCHECK_NE(sync_point, 0u);
793 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
794 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
795 texture_layer_->SetNeedsDisplay();
798 void PepperPluginInstanceImpl::InstanceCrashed() {
799 // Force free all resources and vars.
800 HostGlobals::Get()->InstanceCrashed(pp_instance());
802 // Free any associated graphics.
803 SetFullscreen(false);
804 FlashSetFullscreen(false, false);
805 // Unbind current 2D or 3D graphics context.
806 BindGraphics(pp_instance(), 0);
807 InvalidateRect(gfx::Rect());
809 if (content_decryptor_delegate_) {
810 content_decryptor_delegate_->InstanceCrashed();
811 content_decryptor_delegate_.reset();
814 if (render_frame_)
815 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
816 UnSetAndDeleteLockTargetAdapter();
819 static void SetGPUHistogram(const ppapi::Preferences& prefs,
820 const std::vector<std::string>& arg_names,
821 const std::vector<std::string>& arg_values) {
822 // Calculate a histogram to let us determine how likely people are to try to
823 // run Stage3D content on machines that have it blacklisted.
824 #if defined(OS_WIN)
825 bool needs_gpu = false;
826 bool is_xp = base::win::GetVersion() <= base::win::VERSION_XP;
828 for (size_t i = 0; i < arg_names.size(); i++) {
829 if (arg_names[i] == "wmode") {
830 // In theory content other than Flash could have a "wmode" argument,
831 // but that's pretty unlikely.
832 if (arg_values[i] == "direct" || arg_values[i] == "gpu")
833 needs_gpu = true;
834 break;
837 // 0 : No 3D content and GPU is blacklisted
838 // 1 : No 3D content and GPU is not blacklisted
839 // 2 : 3D content but GPU is blacklisted
840 // 3 : 3D content and GPU is not blacklisted
841 // 4 : No 3D content and GPU is blacklisted on XP
842 // 5 : No 3D content and GPU is not blacklisted on XP
843 // 6 : 3D content but GPU is blacklisted on XP
844 // 7 : 3D content and GPU is not blacklisted on XP
845 UMA_HISTOGRAM_ENUMERATION(
846 "Flash.UsesGPU", is_xp * 4 + needs_gpu * 2 + prefs.is_webgl_supported, 8);
847 #endif
850 bool PepperPluginInstanceImpl::Initialize(
851 const std::vector<std::string>& arg_names,
852 const std::vector<std::string>& arg_values,
853 bool full_frame) {
854 if (!render_frame_)
855 return false;
856 message_channel_ = MessageChannel::Create(this, &message_channel_object_);
858 full_frame_ = full_frame;
860 UpdateTouchEventRequest();
861 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
863 SetGPUHistogram(ppapi::Preferences(PpapiPreferencesBuilder::Build(
864 render_frame_->render_view()->webkit_preferences())),
865 arg_names,
866 arg_values);
868 argn_ = arg_names;
869 argv_ = arg_values;
870 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
871 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
872 bool success = PP_ToBool(instance_interface_->DidCreate(
873 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
874 // If this is a plugin that hosts external plugins, we should delay messages
875 // so that the child plugin that's created later will receive all the
876 // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
878 // A host for external plugins will call ResetAsProxied later, at which point
879 // we can Start() the MessageChannel.
880 if (success && (!module_->renderer_ppapi_host()->IsExternalPluginHost())) {
881 if (message_channel_)
882 message_channel_->Start();
884 return success;
887 bool PepperPluginInstanceImpl::HandleDocumentLoad(
888 const blink::WebURLResponse& response) {
889 DCHECK(!document_loader_);
890 if (external_document_load_) {
891 // The external proxy isn't available, so save the response and record
892 // document load notifications for later replay.
893 external_document_response_ = response;
894 external_document_loader_.reset(new ExternalDocumentLoader());
895 document_loader_ = external_document_loader_.get();
896 return true;
899 if (module()->is_crashed()) {
900 // Don't create a resource for a crashed plugin.
901 container()->element().document().frame()->stopLoading();
902 return false;
905 DCHECK(!document_loader_);
907 // Create a loader resource host for this load. Note that we have to set
908 // the document_loader before issuing the in-process
909 // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
910 // call into the instance and expect it to be valid.
911 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
912 PepperURLLoaderHost* loader_host =
913 new PepperURLLoaderHost(host_impl, true, pp_instance(), 0);
914 // TODO(teravest): Remove set_document_loader() from instance and clean up
915 // this relationship.
916 set_document_loader(loader_host);
917 loader_host->didReceiveResponse(NULL, response);
919 // This host will be pending until the resource object attaches to it.
921 // PpapiHost now owns the pointer to loader_host, so we don't have to worry
922 // about managing it.
923 int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
924 scoped_ptr<ppapi::host::ResourceHost>(loader_host));
925 DCHECK(pending_host_id);
927 DataFromWebURLResponse(
928 host_impl,
929 pp_instance(),
930 response,
931 base::Bind(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
932 weak_factory_.GetWeakPtr(),
933 response,
934 pending_host_id));
936 // If the load was not abandoned, document_loader_ will now be set. It's
937 // possible that the load was canceled by now and document_loader_ was
938 // already nulled out.
939 return true;
942 bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
943 PP_InputEvent_Type type,
944 const base::string16& text) {
945 std::vector<blink::WebCompositionUnderline> empty;
946 return SendCompositionEventWithUnderlineInformationToPlugin(
947 type,
948 text,
949 empty,
950 static_cast<int>(text.size()),
951 static_cast<int>(text.size()));
954 bool
955 PepperPluginInstanceImpl::SendCompositionEventWithUnderlineInformationToPlugin(
956 PP_InputEvent_Type type,
957 const base::string16& text,
958 const std::vector<blink::WebCompositionUnderline>& underlines,
959 int selection_start,
960 int selection_end) {
961 // Keep a reference on the stack. See NOTE above.
962 scoped_refptr<PepperPluginInstanceImpl> ref(this);
964 if (!LoadInputEventInterface())
965 return false;
967 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
968 if (!(filtered_input_event_mask_ & event_class) &&
969 !(input_event_mask_ & event_class))
970 return false;
972 ppapi::InputEventData event;
973 event.event_type = type;
974 event.event_time_stamp =
975 ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
977 // Convert UTF16 text to UTF8 with offset conversion.
978 std::vector<size_t> utf16_offsets;
979 utf16_offsets.push_back(selection_start);
980 utf16_offsets.push_back(selection_end);
981 for (size_t i = 0; i < underlines.size(); ++i) {
982 utf16_offsets.push_back(underlines[i].startOffset);
983 utf16_offsets.push_back(underlines[i].endOffset);
985 std::vector<size_t> utf8_offsets(utf16_offsets);
986 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
988 // Set the converted selection range.
989 event.composition_selection_start =
990 (utf8_offsets[0] == std::string::npos ? event.character_text.size()
991 : utf8_offsets[0]);
992 event.composition_selection_end =
993 (utf8_offsets[1] == std::string::npos ? event.character_text.size()
994 : utf8_offsets[1]);
996 // Set the converted segmentation points.
997 // Be sure to add 0 and size(), and remove duplication or errors.
998 std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
999 offset_set.insert(0);
1000 offset_set.insert(event.character_text.size());
1001 offset_set.erase(std::string::npos);
1002 event.composition_segment_offsets.assign(offset_set.begin(),
1003 offset_set.end());
1005 // Set the composition target.
1006 for (size_t i = 0; i < underlines.size(); ++i) {
1007 if (underlines[i].thick) {
1008 std::vector<uint32_t>::iterator it =
1009 std::find(event.composition_segment_offsets.begin(),
1010 event.composition_segment_offsets.end(),
1011 utf8_offsets[2 * i + 2]);
1012 if (it != event.composition_segment_offsets.end()) {
1013 event.composition_target_segment =
1014 it - event.composition_segment_offsets.begin();
1015 break;
1020 // Send the event.
1021 bool handled = false;
1022 if (filtered_input_event_mask_ & event_class)
1023 event.is_filtered = true;
1024 else
1025 handled = true; // Unfiltered events are assumed to be handled.
1026 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1027 new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
1028 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1029 pp_instance(), event_resource->pp_resource()));
1030 return handled;
1033 void PepperPluginInstanceImpl::RequestInputEventsHelper(
1034 uint32_t event_classes) {
1035 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
1036 UpdateTouchEventRequest();
1037 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
1038 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
1041 bool PepperPluginInstanceImpl::HandleCompositionStart(
1042 const base::string16& text) {
1043 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1044 text);
1047 bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1048 const base::string16& text,
1049 const std::vector<blink::WebCompositionUnderline>& underlines,
1050 int selection_start,
1051 int selection_end) {
1052 return SendCompositionEventWithUnderlineInformationToPlugin(
1053 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
1054 text,
1055 underlines,
1056 selection_start,
1057 selection_end);
1060 bool PepperPluginInstanceImpl::HandleCompositionEnd(
1061 const base::string16& text) {
1062 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1063 text);
1066 bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1067 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1070 void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1071 gfx::Range* range) const {
1072 std::vector<size_t> offsets;
1073 offsets.push_back(selection_anchor_);
1074 offsets.push_back(selection_caret_);
1075 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1076 range->set_start(offsets[0] == base::string16::npos ? text->size()
1077 : offsets[0]);
1078 range->set_end(offsets[1] == base::string16::npos ? text->size()
1079 : offsets[1]);
1082 bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1083 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1084 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1087 gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1088 if (!text_input_caret_set_) {
1089 // If it is never set by the plugin, use the bottom left corner.
1090 return gfx::Rect(view_data_.rect.point.x,
1091 view_data_.rect.point.y + view_data_.rect.size.height,
1096 // TODO(kinaba) Take CSS transformation into accont.
1097 // TODO(kinaba) Take bounding_box into account. On some platforms, an
1098 // "exclude rectangle" where candidate window must avoid the region can be
1099 // passed to IME. Currently, we pass only the caret rectangle because
1100 // it is the only information supported uniformly in Chromium.
1101 gfx::Rect caret(text_input_caret_);
1102 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1103 return caret;
1106 bool PepperPluginInstanceImpl::HandleInputEvent(
1107 const blink::WebInputEvent& event,
1108 WebCursorInfo* cursor_info) {
1109 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1111 if (event.type == blink::WebInputEvent::MouseUp && power_saver_enabled_)
1112 power_saver_enabled_ = false;
1114 if (plugin_throttled_) {
1115 if (event.type == blink::WebInputEvent::MouseUp)
1116 SetPluginThrottled(false /* throttled */);
1118 return true;
1121 if (!render_frame_)
1122 return false;
1123 if (WebInputEvent::isMouseEventType(event.type)) {
1124 render_frame_->PepperDidReceiveMouseEvent(this);
1127 // Don't dispatch input events to crashed plugins.
1128 if (module()->is_crashed())
1129 return false;
1131 // Don't send reserved system key events to plugins.
1132 if (IsReservedSystemInputEvent(event))
1133 return false;
1135 // Keep a reference on the stack. See NOTE above.
1136 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1138 bool rv = false;
1139 if (LoadInputEventInterface()) {
1140 PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
1141 if (!event_class)
1142 return false;
1144 if ((filtered_input_event_mask_ & event_class) ||
1145 (input_event_mask_ & event_class)) {
1146 // Actually send the event.
1147 std::vector<ppapi::InputEventData> events;
1148 CreateInputEventData(event, &events);
1150 // Allow the user gesture to be pending after the plugin handles the
1151 // event. This allows out-of-process plugins to respond to the user
1152 // gesture after processing has finished here.
1153 if (WebUserGestureIndicator::isProcessingUserGesture()) {
1154 pending_user_gesture_ =
1155 ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
1156 pending_user_gesture_token_ =
1157 WebUserGestureIndicator::currentUserGestureToken();
1158 pending_user_gesture_token_.setOutOfProcess();
1161 const ui::LatencyInfo* current_event_latency_info = NULL;
1162 if (render_frame_->GetRenderWidget()) {
1163 current_event_latency_info =
1164 render_frame_->GetRenderWidget()->current_event_latency_info();
1167 // Each input event may generate more than one PP_InputEvent.
1168 for (size_t i = 0; i < events.size(); i++) {
1169 if (is_tracking_latency_) {
1170 InitLatencyInfo(&events[i].latency_info,
1171 current_event_latency_info,
1172 event.type,
1173 last_input_number_++);
1175 if (filtered_input_event_mask_ & event_class)
1176 events[i].is_filtered = true;
1177 else
1178 rv = true; // Unfiltered events are assumed to be handled.
1179 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1180 new PPB_InputEvent_Shared(
1181 ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1183 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1184 pp_instance(), event_resource->pp_resource()));
1189 if (cursor_)
1190 *cursor_info = *cursor_;
1191 return rv;
1194 void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1195 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1196 if (is_deleted_)
1197 return;
1198 ppapi::proxy::HostDispatcher* dispatcher =
1199 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1200 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1201 // The dispatcher should always be valid, and MessageChannel should never
1202 // send an 'object' var over PPP_Messaging.
1203 NOTREACHED();
1204 return;
1206 dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1207 ppapi::API_ID_PPP_MESSAGING,
1208 pp_instance(),
1209 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1210 pp_instance())));
1213 bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1214 ScopedPPVar* result) {
1215 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
1216 if (is_deleted_)
1217 return false;
1218 ppapi::proxy::HostDispatcher* dispatcher =
1219 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1220 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1221 // The dispatcher should always be valid, and MessageChannel should never
1222 // send an 'object' var over PPP_Messaging.
1223 NOTREACHED();
1224 return false;
1226 ppapi::proxy::ReceiveSerializedVarReturnValue msg_reply;
1227 bool was_handled = false;
1228 dispatcher->Send(new PpapiMsg_PPPMessageHandler_HandleBlockingMessage(
1229 ppapi::API_ID_PPP_MESSAGING,
1230 pp_instance(),
1231 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1232 pp_instance()),
1233 &msg_reply,
1234 &was_handled));
1235 *result = ScopedPPVar(ScopedPPVar::PassRef(), msg_reply.Return(dispatcher));
1236 TRACE_EVENT0("ppapi",
1237 "PepperPluginInstanceImpl::HandleBlockingMessage return.");
1238 return was_handled;
1241 PP_Var PepperPluginInstanceImpl::GetInstanceObject(v8::Isolate* isolate) {
1242 // Keep a reference on the stack. See NOTE above.
1243 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1245 DCHECK_EQ(isolate, isolate_);
1247 // If the plugin supports the private instance interface, try to retrieve its
1248 // instance object.
1249 if (LoadPrivateInterface())
1250 return plugin_private_interface_->GetInstanceObject(pp_instance());
1251 return PP_MakeUndefined();
1254 void PepperPluginInstanceImpl::ViewChanged(
1255 const gfx::Rect& position,
1256 const gfx::Rect& clip,
1257 const std::vector<gfx::Rect>& cut_outs_rects) {
1258 // WebKit can give weird (x,y) positions for empty clip rects (since the
1259 // position technically doesn't matter). But we want to make these
1260 // consistent since this is given to the plugin, so force everything to 0
1261 // in the "everything is clipped" case.
1262 gfx::Rect new_clip;
1263 if (!clip.IsEmpty())
1264 new_clip = clip;
1266 cut_outs_rects_ = cut_outs_rects;
1268 view_data_.rect = PP_FromGfxRect(position);
1269 view_data_.clip_rect = PP_FromGfxRect(clip);
1270 view_data_.device_scale = container_->deviceScaleFactor();
1271 view_data_.css_scale =
1272 container_->pageZoomFactor() * container_->pageScaleFactor();
1274 gfx::Size scroll_offset =
1275 container_->element().document().frame()->scrollOffset();
1276 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1277 scroll_offset.height());
1279 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1280 WebElement element = container_->element();
1281 WebDocument document = element.document();
1282 bool is_fullscreen_element = (element == document.fullScreenElement());
1283 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1284 render_frame()->GetRenderWidget()->is_fullscreen() &&
1285 is_fullscreen_element) {
1286 // Entered fullscreen. Only possible via SetFullscreen().
1287 view_data_.is_fullscreen = true;
1288 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1289 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1290 // so desired_fullscreen_state might be out-of-date.
1291 desired_fullscreen_state_ = false;
1292 view_data_.is_fullscreen = false;
1294 // This operation will cause the plugin to re-layout which will send more
1295 // DidChangeView updates. Schedule an asynchronous update and suppress
1296 // notifications until that completes to avoid sending intermediate sizes
1297 // to the plugins.
1298 ScheduleAsyncDidChangeView();
1300 // Reset the size attributes that we hacked to fill in the screen and
1301 // retrigger ViewChanged. Make sure we don't forward duplicates of
1302 // this view to the plugin.
1303 ResetSizeAttributesAfterFullscreen();
1304 return;
1308 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1310 SendDidChangeView();
1313 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1314 if (has_webkit_focus_ == has_focus)
1315 return;
1317 bool old_plugin_focus = PluginHasFocus();
1318 has_webkit_focus_ = has_focus;
1319 if (PluginHasFocus() != old_plugin_focus)
1320 SendFocusChangeNotification();
1323 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1324 if (has_content_area_focus_ == has_focus)
1325 return;
1327 bool old_plugin_focus = PluginHasFocus();
1328 has_content_area_focus_ = has_focus;
1329 if (PluginHasFocus() != old_plugin_focus)
1330 SendFocusChangeNotification();
1333 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1334 if (is_visible == view_data_.is_page_visible)
1335 return; // Nothing to do.
1336 view_data_.is_page_visible = is_visible;
1338 // If the initial DidChangeView notification hasn't been sent to the plugin,
1339 // let it pass the visibility state for us, instead of sending a notification
1340 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1341 // hasn't been called for the first time. In that case, most of the fields in
1342 // |view_data_| haven't been properly initialized.
1343 if (sent_initial_did_change_view_)
1344 SendDidChangeView();
1347 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1348 if (bound_graphics_2d_platform_)
1349 bound_graphics_2d_platform_->ViewInitiatedPaint();
1350 else if (bound_graphics_3d_.get())
1351 bound_graphics_3d_->ViewInitiatedPaint();
1352 else if (bound_compositor_)
1353 bound_compositor_->ViewInitiatedPaint();
1356 void PepperPluginInstanceImpl::ViewFlushedPaint() {
1357 // Keep a reference on the stack. See NOTE above.
1358 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1359 if (bound_graphics_2d_platform_)
1360 bound_graphics_2d_platform_->ViewFlushedPaint();
1361 else if (bound_graphics_3d_.get())
1362 bound_graphics_3d_->ViewFlushedPaint();
1363 else if (bound_compositor_)
1364 bound_compositor_->ViewFlushedPaint();
1367 void PepperPluginInstanceImpl::SetSelectedText(
1368 const base::string16& selected_text) {
1369 selected_text_ = selected_text;
1370 gfx::Range range(0, selected_text.length());
1371 render_frame_->SetSelectedText(selected_text, 0, range);
1374 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1375 link_under_cursor_ = base::UTF8ToUTF16(url);
1378 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1379 text_input_type_ = type;
1380 render_frame_->PepperTextInputTypeChanged(this);
1383 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1384 if (message_channel_)
1385 message_channel_->PostMessageToJavaScript(message);
1388 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1389 PP_Instance instance,
1390 void* user_data,
1391 const PPP_MessageHandler_0_2* handler,
1392 PP_Resource message_loop) {
1393 // Not supported in-process.
1394 NOTIMPLEMENTED();
1395 return PP_ERROR_FAILED;
1398 int32_t PepperPluginInstanceImpl::RegisterMessageHandler_1_1_Deprecated(
1399 PP_Instance instance,
1400 void* user_data,
1401 const PPP_MessageHandler_0_1_Deprecated* handler,
1402 PP_Resource message_loop) {
1403 // Not supported in-process.
1404 NOTIMPLEMENTED();
1405 return PP_ERROR_FAILED;
1408 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1409 // Not supported in-process.
1410 NOTIMPLEMENTED();
1413 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1414 return selected_text_;
1417 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1418 const gfx::Point& point) {
1419 // Keep a reference on the stack. See NOTE above.
1420 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1421 if (!LoadPdfInterface()) {
1422 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1423 // return |link_under_cursor_| here because this is only ever called with
1424 // the current mouse coordinates.
1425 return link_under_cursor_;
1428 PP_Point p;
1429 p.x = point.x();
1430 p.y = point.y();
1431 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1432 // If the plugin returns undefined for this function it has switched to
1433 // providing us with the link under the cursor eagerly.
1434 if (rv.type == PP_VARTYPE_UNDEFINED)
1435 return link_under_cursor_;
1436 StringVar* string = StringVar::FromPPVar(rv);
1437 base::string16 link;
1438 if (string)
1439 link = base::UTF8ToUTF16(string->value());
1440 // Release the ref the plugin transfered to us.
1441 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1442 return link;
1445 void PepperPluginInstanceImpl::RequestSurroundingText(
1446 size_t desired_number_of_characters) {
1447 // Keep a reference on the stack. See NOTE above.
1448 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1449 if (!LoadTextInputInterface())
1450 return;
1451 plugin_textinput_interface_->RequestSurroundingText(
1452 pp_instance(), desired_number_of_characters);
1455 void PepperPluginInstanceImpl::Zoom(double factor, bool text_only) {
1456 // Keep a reference on the stack. See NOTE above.
1457 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1458 if (!LoadZoomInterface())
1459 return;
1460 plugin_zoom_interface_->Zoom(pp_instance(), factor, PP_FromBool(text_only));
1463 bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1464 bool case_sensitive,
1465 int identifier) {
1466 // Keep a reference on the stack. See NOTE above.
1467 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1468 if (!LoadFindInterface())
1469 return false;
1470 find_identifier_ = identifier;
1471 return PP_ToBool(
1472 plugin_find_interface_->StartFind(pp_instance(),
1473 base::UTF16ToUTF8(search_text).c_str(),
1474 PP_FromBool(case_sensitive)));
1477 void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1478 // Keep a reference on the stack. See NOTE above.
1479 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1480 if (LoadFindInterface())
1481 plugin_find_interface_->SelectFindResult(pp_instance(),
1482 PP_FromBool(forward));
1485 void PepperPluginInstanceImpl::StopFind() {
1486 // Keep a reference on the stack. See NOTE above.
1487 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1488 if (!LoadFindInterface())
1489 return;
1490 find_identifier_ = -1;
1491 plugin_find_interface_->StopFind(pp_instance());
1494 bool PepperPluginInstanceImpl::LoadFindInterface() {
1495 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1496 return false;
1497 if (!plugin_find_interface_) {
1498 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1499 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1502 return !!plugin_find_interface_;
1505 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1506 if (!checked_for_plugin_input_event_interface_) {
1507 checked_for_plugin_input_event_interface_ = true;
1508 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1509 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1511 return !!plugin_input_event_interface_;
1514 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1515 if (!plugin_mouse_lock_interface_) {
1516 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1517 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1520 return !!plugin_mouse_lock_interface_;
1523 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1524 if (!checked_for_plugin_pdf_interface_) {
1525 checked_for_plugin_pdf_interface_ = true;
1526 plugin_pdf_interface_ = static_cast<const PPP_Pdf_1*>(
1527 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1530 return !!plugin_pdf_interface_;
1533 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1534 // Only check for the interface if the plugin has dev permission.
1535 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1536 return false;
1537 if (!plugin_print_interface_) {
1538 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1539 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1541 return !!plugin_print_interface_;
1544 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1545 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1546 // call GetInstanceObject. This is necessary to ensure that the properties
1547 // the trusted plugin exposes (readyState and lastError) work properly. Note
1548 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1549 // so it's correct to never look up PPP_InstancePrivate for them.
1551 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1552 // to the "real" module.
1553 scoped_refptr<PluginModule> module =
1554 original_module_.get() ? original_module_ : module_;
1555 // Only check for the interface if the plugin has private permission.
1556 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1557 return false;
1558 if (!plugin_private_interface_) {
1559 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1560 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1563 return !!plugin_private_interface_;
1566 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1567 if (!plugin_textinput_interface_) {
1568 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1569 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1572 return !!plugin_textinput_interface_;
1575 bool PepperPluginInstanceImpl::LoadZoomInterface() {
1576 if (!plugin_zoom_interface_) {
1577 plugin_zoom_interface_ = static_cast<const PPP_Zoom_Dev*>(
1578 module_->GetPluginInterface(PPP_ZOOM_DEV_INTERFACE));
1581 return !!plugin_zoom_interface_;
1584 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1585 if (!bound_graphics_2d_platform_ || !texture_layer_.get()) {
1586 // Currently the transform is only applied for Graphics2D.
1587 return;
1589 // Set the UV coordinates of the texture based on the size of the Graphics2D
1590 // context. By default a texture gets scaled to the size of the layer. But
1591 // if the size of the Graphics2D context doesn't match the size of the plugin
1592 // then it will be incorrectly stretched. This also affects how the plugin
1593 // is painted when it is being resized. If the Graphics2D contents are
1594 // stretched when a plugin is resized while waiting for a new frame from the
1595 // plugin to be rendered, then flickering behavior occurs as in
1596 // crbug.com/353453.
1597 gfx::SizeF graphics_2d_size_in_dip =
1598 gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1599 bound_graphics_2d_platform_->GetScale());
1600 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1601 view_data_.rect.size.height);
1603 texture_layer_->SetUV(
1604 gfx::PointF(0.0f, 0.0f),
1605 gfx::PointF(
1606 plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1607 plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1610 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1611 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1614 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1615 // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1616 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1617 // drop its reference, usually the last one. This is similar to possible
1618 // plugin behavior described at the NOTE above Delete().
1619 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1621 if (!render_frame_)
1622 return;
1624 bool has_focus = PluginHasFocus();
1625 render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1627 // instance_interface_ may have been cleared in Delete() if the
1628 // PepperWebPluginImpl is destroyed.
1629 if (instance_interface_)
1630 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1633 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1634 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1635 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1636 container_->requestTouchEventType(
1637 raw_touch
1638 ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1639 : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1642 bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1643 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1644 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1647 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1648 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1649 return; // Already scheduled.
1650 base::MessageLoop::current()->PostTask(
1651 FROM_HERE,
1652 base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1653 view_change_weak_ptr_factory_.GetWeakPtr()));
1656 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1657 // The bound callback that owns the weak pointer is still valid until after
1658 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1659 // invalidate them here.
1660 // NOTE: If we ever want to have more than one pending callback, it should
1661 // use a different factory, or we should have a different strategy here.
1662 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1663 SendDidChangeView();
1666 void PepperPluginInstanceImpl::SendDidChangeView() {
1667 // Don't send DidChangeView to crashed plugins.
1668 if (module()->is_crashed())
1669 return;
1671 // When plugin is throttled, send ViewData indicating it's in the background.
1672 const ppapi::ViewData& view_data =
1673 plugin_throttled_ ? empty_view_data_ : view_data_;
1675 if (view_change_weak_ptr_factory_.HasWeakPtrs() ||
1676 (sent_initial_did_change_view_ &&
1677 last_sent_view_data_.Equals(view_data)))
1678 return; // Nothing to update.
1680 sent_initial_did_change_view_ = true;
1681 last_sent_view_data_ = view_data;
1682 ScopedPPResource resource(
1683 ScopedPPResource::PassRef(),
1684 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data))
1685 ->GetReference());
1687 UpdateLayerTransform();
1689 if (bound_graphics_2d_platform_ &&
1690 (!view_data.is_page_visible ||
1691 PP_ToGfxRect(view_data.clip_rect).IsEmpty())) {
1692 bound_graphics_2d_platform_->ClearCache();
1695 // It's possible that Delete() has been called but the renderer hasn't
1696 // released its reference to this object yet.
1697 if (instance_interface_) {
1698 instance_interface_->DidChangeView(
1699 pp_instance(), resource, &view_data.rect, &view_data.clip_rect);
1703 void PepperPluginInstanceImpl::ReportGeometry() {
1704 // If this call was delayed, we may have transitioned back to fullscreen in
1705 // the mean time, so only report the geometry if we are actually in normal
1706 // mode.
1707 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1708 container_->reportGeometry();
1711 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1712 PP_PrintOutputFormat_Dev* format) {
1713 // Keep a reference on the stack. See NOTE above.
1714 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1715 if (!LoadPrintInterface())
1716 return false;
1717 uint32_t supported_formats =
1718 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1719 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1720 *format = PP_PRINTOUTPUTFORMAT_PDF;
1721 return true;
1723 return false;
1726 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1727 PP_PrintOutputFormat_Dev format;
1728 return GetPreferredPrintOutputFormat(&format);
1731 bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1732 DCHECK(plugin_print_interface_);
1733 if (!plugin_print_interface_)
1734 return false;
1735 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1738 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1739 // Keep a reference on the stack. See NOTE above.
1740 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1741 PP_PrintOutputFormat_Dev format;
1742 if (!GetPreferredPrintOutputFormat(&format)) {
1743 // PrintBegin should not have been called since SupportsPrintInterface
1744 // would have returned false;
1745 NOTREACHED();
1746 return 0;
1748 int num_pages = 0;
1749 PP_PrintSettings_Dev print_settings;
1750 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1751 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1752 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1753 print_settings.dpi = print_params.printerDPI;
1754 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1755 print_settings.grayscale = PP_FALSE;
1756 print_settings.print_scaling_option =
1757 static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1758 print_settings.format = format;
1759 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1760 if (!num_pages)
1761 return 0;
1762 current_print_settings_ = print_settings;
1763 canvas_.clear();
1764 ranges_.clear();
1765 return num_pages;
1768 bool PepperPluginInstanceImpl::PrintPage(int page_number,
1769 blink::WebCanvas* canvas) {
1770 #if defined(ENABLE_PRINTING)
1771 DCHECK(plugin_print_interface_);
1772 PP_PrintPageNumberRange_Dev page_range;
1773 page_range.first_page_number = page_range.last_page_number = page_number;
1774 // The canvas only has a metafile on it for print preview.
1775 bool save_for_later =
1776 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1777 #if defined(OS_MACOSX)
1778 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1779 #endif // defined(OS_MACOSX)
1780 if (save_for_later) {
1781 ranges_.push_back(page_range);
1782 canvas_ = skia::SharePtr(canvas);
1783 return true;
1784 } else {
1785 return PrintPageHelper(&page_range, 1, canvas);
1787 #else // ENABLE_PRINTING
1788 return false;
1789 #endif
1792 bool PepperPluginInstanceImpl::PrintPageHelper(
1793 PP_PrintPageNumberRange_Dev* page_ranges,
1794 int num_ranges,
1795 blink::WebCanvas* canvas) {
1796 // Keep a reference on the stack. See NOTE above.
1797 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1798 DCHECK(plugin_print_interface_);
1799 if (!plugin_print_interface_)
1800 return false;
1801 PP_Resource print_output = plugin_print_interface_->PrintPages(
1802 pp_instance(), page_ranges, num_ranges);
1803 if (!print_output)
1804 return false;
1806 bool ret = false;
1808 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1809 ret = PrintPDFOutput(print_output, canvas);
1811 // Now we need to release the print output resource.
1812 PluginModule::GetCore()->ReleaseResource(print_output);
1814 return ret;
1817 void PepperPluginInstanceImpl::PrintEnd() {
1818 // Keep a reference on the stack. See NOTE above.
1819 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1820 if (!ranges_.empty())
1821 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1822 canvas_.clear();
1823 ranges_.clear();
1825 DCHECK(plugin_print_interface_);
1826 if (plugin_print_interface_)
1827 plugin_print_interface_->End(pp_instance());
1829 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1830 #if defined(OS_MACOSX)
1831 last_printed_page_ = NULL;
1832 #endif // defined(OS_MACOSX)
1835 bool PepperPluginInstanceImpl::CanRotateView() {
1836 if (!LoadPdfInterface())
1837 return false;
1839 return true;
1842 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1843 if (!LoadPdfInterface())
1844 return;
1845 PP_PrivatePageTransformType transform_type =
1846 type == WebPlugin::RotationType90Clockwise
1847 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1848 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1849 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1850 // NOTE: plugin instance may have been deleted.
1853 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1854 return fullscreen_container_ != NULL;
1857 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1858 return desired_fullscreen_state_;
1861 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1862 // Keep a reference on the stack. See NOTE above.
1863 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1865 // Check whether we are trying to switch to the state we're already going
1866 // to (i.e. if we're already switching to fullscreen but the fullscreen
1867 // container isn't ready yet, don't do anything more).
1868 if (fullscreen == IsFullscreenOrPending())
1869 return false;
1871 if (!render_frame_)
1872 return false;
1873 if (fullscreen && !render_frame_->render_view()
1874 ->renderer_preferences()
1875 .plugin_fullscreen_allowed)
1876 return false;
1878 // Check whether we are trying to switch while the state is in transition.
1879 // The 2nd request gets dropped while messing up the internal state, so
1880 // disallow this.
1881 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1882 return false;
1884 if (fullscreen && !IsProcessingUserGesture())
1885 return false;
1887 VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1888 desired_fullscreen_state_ = fullscreen;
1890 if (fullscreen) {
1891 // Create the user gesture in case we're processing one that's pending.
1892 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1893 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1894 // so we will tweak plugin's attributes to support the expected behavior.
1895 KeepSizeAttributesBeforeFullscreen();
1896 SetSizeAttributesForFullscreen();
1897 container_->element().requestFullScreen();
1898 } else {
1899 container_->element().document().cancelFullScreen();
1901 return true;
1904 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1905 bool flash_fullscreen) {
1906 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1908 if (flash_fullscreen == flash_fullscreen_) {
1909 // Manually clear callback when fullscreen fails with mouselock pending.
1910 if (!flash_fullscreen && is_mouselock_pending)
1911 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1912 return;
1915 UpdateLayer(false);
1917 bool old_plugin_focus = PluginHasFocus();
1918 flash_fullscreen_ = flash_fullscreen;
1919 if (is_mouselock_pending && !IsMouseLocked()) {
1920 if (!IsProcessingUserGesture() &&
1921 !module_->permissions().HasPermission(
1922 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1923 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1924 } else {
1925 // Open a user gesture here so the Webkit user gesture checks will succeed
1926 // for out-of-process plugins.
1927 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1928 if (!LockMouse())
1929 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1933 if (PluginHasFocus() != old_plugin_focus)
1934 SendFocusChangeNotification();
1937 bool PepperPluginInstanceImpl::IsViewAccelerated() {
1938 if (!container_)
1939 return false;
1941 WebDocument document = container_->element().document();
1942 WebLocalFrame* frame = document.frame();
1943 if (!frame)
1944 return false;
1945 WebView* view = frame->view();
1946 if (!view)
1947 return false;
1949 return view->isAcceleratedCompositingActive();
1952 bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1953 blink::WebCanvas* canvas) {
1954 #if defined(ENABLE_PRINTING)
1955 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1956 if (enter.failed())
1957 return false;
1959 BufferAutoMapper mapper(enter.object());
1960 if (!mapper.data() || !mapper.size()) {
1961 NOTREACHED();
1962 return false;
1965 printing::PdfMetafileSkia* metafile =
1966 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1967 if (metafile)
1968 return metafile->InitFromData(mapper.data(), mapper.size());
1970 NOTREACHED();
1971 #endif // ENABLE_PRINTING
1972 return false;
1975 void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
1976 if (!container_)
1977 return;
1979 gpu::Mailbox mailbox;
1980 uint32 sync_point = 0;
1981 if (bound_graphics_3d_.get()) {
1982 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
1983 DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
1985 bool want_3d_layer = !mailbox.IsZero();
1986 bool want_2d_layer = !!bound_graphics_2d_platform_;
1987 bool want_texture_layer = want_3d_layer || want_2d_layer;
1988 bool want_compositor_layer = !!bound_compositor_;
1990 if (!device_changed && (want_texture_layer == !!texture_layer_.get()) &&
1991 (want_3d_layer == layer_is_hardware_) &&
1992 (want_compositor_layer == !!compositor_layer_.get()) &&
1993 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
1994 UpdateLayerTransform();
1995 return;
1998 if (texture_layer_.get() || compositor_layer_.get()) {
1999 if (!layer_bound_to_fullscreen_)
2000 container_->setWebLayer(NULL);
2001 else if (fullscreen_container_)
2002 fullscreen_container_->SetLayer(NULL);
2003 web_layer_.reset();
2004 texture_layer_ = NULL;
2005 compositor_layer_ = NULL;
2008 if (want_texture_layer) {
2009 bool opaque = false;
2010 if (want_3d_layer) {
2011 DCHECK(bound_graphics_3d_.get());
2012 texture_layer_ = cc::TextureLayer::CreateForMailbox(NULL);
2013 opaque = bound_graphics_3d_->IsOpaque();
2014 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
2015 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
2016 } else {
2017 DCHECK(bound_graphics_2d_platform_);
2018 texture_layer_ = cc::TextureLayer::CreateForMailbox(this);
2019 bound_graphics_2d_platform_->AttachedToNewLayer();
2020 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2021 texture_layer_->SetFlipped(false);
2024 // Ignore transparency in fullscreen, since that's what Flash always
2025 // wants to do, and that lets it not recreate a context if
2026 // wmode=transparent was specified.
2027 opaque = opaque || fullscreen_container_;
2028 texture_layer_->SetContentsOpaque(opaque);
2029 web_layer_.reset(new cc_blink::WebLayerImpl(texture_layer_));
2030 } else if (want_compositor_layer) {
2031 compositor_layer_ = bound_compositor_->layer();
2032 web_layer_.reset(new cc_blink::WebLayerImpl(compositor_layer_));
2035 if (web_layer_) {
2036 if (fullscreen_container_) {
2037 fullscreen_container_->SetLayer(web_layer_.get());
2038 } else {
2039 container_->setWebLayer(web_layer_.get());
2043 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2044 layer_is_hardware_ = want_3d_layer;
2045 UpdateLayerTransform();
2048 bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2049 cc::TextureMailbox* mailbox,
2050 scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2051 bool use_shared_memory) {
2052 if (!bound_graphics_2d_platform_)
2053 return false;
2054 return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2055 release_callback);
2058 void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2060 void PepperPluginInstanceImpl::AddLatencyInfo(
2061 const std::vector<ui::LatencyInfo>& latency_info) {
2062 if (render_frame_ && render_frame_->GetRenderWidget()) {
2063 RenderWidgetCompositor* compositor =
2064 render_frame_->GetRenderWidget()->compositor();
2065 if (compositor) {
2066 for (size_t i = 0; i < latency_info.size(); i++) {
2067 scoped_ptr<cc::SwapPromise> swap_promise(
2068 new cc::LatencyInfoSwapPromise(latency_info[i]));
2069 compositor->QueueSwapPromise(swap_promise.Pass());
2075 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2076 DCHECK(live_plugin_objects_.find(plugin_object) ==
2077 live_plugin_objects_.end());
2078 live_plugin_objects_.insert(plugin_object);
2081 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2082 // Don't actually verify that the object is in the set since during module
2083 // deletion we'll be in the process of freeing them.
2084 live_plugin_objects_.erase(plugin_object);
2087 bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2088 PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2089 // Give a lot of slack so tests won't be flaky.
2090 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2091 return pending_user_gesture_token_.hasGestures() &&
2092 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2095 WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2096 if (!IsProcessingUserGesture())
2097 pending_user_gesture_token_ = WebUserGestureToken();
2098 return pending_user_gesture_token_;
2101 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2102 if (TrackedCallback::IsPending(lock_mouse_callback_))
2103 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2106 void PepperPluginInstanceImpl::OnMouseLockLost() {
2107 if (LoadMouseLockInterface())
2108 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2111 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2112 const blink::WebMouseEvent& event) {
2113 // |cursor_info| is ignored since it is hidden when the mouse is locked.
2114 blink::WebCursorInfo cursor_info;
2115 HandleInputEvent(event, &cursor_info);
2118 void PepperPluginInstanceImpl::SimulateInputEvent(
2119 const InputEventData& input_event) {
2120 WebView* web_view = container()->element().document().frame()->view();
2121 if (!web_view) {
2122 NOTREACHED();
2123 return;
2126 bool handled = SimulateIMEEvent(input_event);
2127 if (handled)
2128 return;
2130 std::vector<linked_ptr<WebInputEvent> > events =
2131 CreateSimulatedWebInputEvents(
2132 input_event,
2133 view_data_.rect.point.x + view_data_.rect.size.width / 2,
2134 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2135 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2136 it != events.end();
2137 ++it) {
2138 web_view->handleInputEvent(*it->get());
2142 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2143 const InputEventData& input_event) {
2144 switch (input_event.event_type) {
2145 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2146 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2147 SimulateImeSetCompositionEvent(input_event);
2148 break;
2149 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2150 DCHECK(input_event.character_text.empty());
2151 SimulateImeSetCompositionEvent(input_event);
2152 break;
2153 case PP_INPUTEVENT_TYPE_IME_TEXT:
2154 if (!render_frame_)
2155 return false;
2156 render_frame_->SimulateImeConfirmComposition(
2157 base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2158 break;
2159 default:
2160 return false;
2162 return true;
2165 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2166 const InputEventData& input_event) {
2167 if (!render_frame_)
2168 return;
2170 std::vector<size_t> offsets;
2171 offsets.push_back(input_event.composition_selection_start);
2172 offsets.push_back(input_event.composition_selection_end);
2173 offsets.insert(offsets.end(),
2174 input_event.composition_segment_offsets.begin(),
2175 input_event.composition_segment_offsets.end());
2177 base::string16 utf16_text =
2178 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2180 std::vector<blink::WebCompositionUnderline> underlines;
2181 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2182 blink::WebCompositionUnderline underline;
2183 underline.startOffset = offsets[i];
2184 underline.endOffset = offsets[i + 1];
2185 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2186 underline.thick = true;
2187 underlines.push_back(underline);
2190 render_frame_->SimulateImeSetComposition(
2191 utf16_text, underlines, offsets[0], offsets[1]);
2194 ContentDecryptorDelegate*
2195 PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2196 if (content_decryptor_delegate_)
2197 return content_decryptor_delegate_.get();
2199 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2200 static_cast<const PPP_ContentDecryptor_Private*>(
2201 module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2202 if (!plugin_decryption_interface)
2203 return NULL;
2205 content_decryptor_delegate_.reset(
2206 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2207 return content_decryptor_delegate_.get();
2210 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2211 PP_Resource device) {
2212 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2213 // The Graphics3D instance can't be destroyed until we call
2214 // UpdateLayer().
2215 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2216 if (bound_graphics_3d_.get()) {
2217 bound_graphics_3d_->BindToInstance(false);
2218 bound_graphics_3d_ = NULL;
2220 if (bound_graphics_2d_platform_) {
2221 bound_graphics_2d_platform_->BindToInstance(NULL);
2222 bound_graphics_2d_platform_ = NULL;
2224 if (bound_compositor_) {
2225 bound_compositor_->BindToInstance(NULL);
2226 bound_compositor_ = NULL;
2229 // Special-case clearing the current device.
2230 if (!device) {
2231 UpdateLayer(true);
2232 InvalidateRect(gfx::Rect());
2233 return PP_TRUE;
2236 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2237 // to/from fullscreen with PPB_Fullscreen.
2238 if ((fullscreen_container_ && !flash_fullscreen_) ||
2239 desired_fullscreen_state_ != view_data_.is_fullscreen)
2240 return PP_FALSE;
2242 const ppapi::host::PpapiHost* ppapi_host =
2243 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2244 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2245 PepperGraphics2DHost* graphics_2d = NULL;
2246 PepperCompositorHost* compositor = NULL;
2247 if (host) {
2248 if (host->IsGraphics2DHost()) {
2249 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2250 } else if (host->IsCompositorHost()) {
2251 compositor = static_cast<PepperCompositorHost*>(host);
2252 } else {
2253 DLOG(ERROR) <<
2254 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2258 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2259 PPB_Graphics3D_Impl* graphics_3d =
2260 enter_3d.succeeded()
2261 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2262 : NULL;
2264 if (compositor) {
2265 if (compositor->BindToInstance(this)) {
2266 bound_compositor_ = compositor;
2267 UpdateLayer(true);
2268 return PP_TRUE;
2270 } else if (graphics_2d) {
2271 if (graphics_2d->BindToInstance(this)) {
2272 bound_graphics_2d_platform_ = graphics_2d;
2273 UpdateLayer(true);
2274 return PP_TRUE;
2276 } else if (graphics_3d) {
2277 // Make sure graphics can only be bound to the instance it is
2278 // associated with.
2279 if (graphics_3d->pp_instance() == pp_instance() &&
2280 graphics_3d->BindToInstance(true)) {
2281 bound_graphics_3d_ = graphics_3d;
2282 UpdateLayer(true);
2283 return PP_TRUE;
2287 // The instance cannot be bound or the device is not a valid resource type.
2288 return PP_FALSE;
2291 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2292 return PP_FromBool(full_frame());
2295 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2296 return &view_data_;
2299 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2300 return PP_FromBool(flash_fullscreen_);
2303 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2304 if (!container_)
2305 return PP_MakeUndefined();
2307 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2308 PepperTryCatchVar try_catch(this, &converter, NULL);
2309 WebLocalFrame* frame = container_->element().document().frame();
2310 if (!frame) {
2311 try_catch.SetException("No frame exists for window object.");
2312 return PP_MakeUndefined();
2315 ScopedPPVar result =
2316 try_catch.FromV8(frame->mainWorldScriptContext()->Global());
2317 DCHECK(!try_catch.HasException());
2318 return result.Release();
2321 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2322 if (!container_)
2323 return PP_MakeUndefined();
2324 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2325 PepperTryCatchVar try_catch(this, &converter, NULL);
2326 ScopedPPVar result = try_catch.FromV8(container_->v8ObjectForElement());
2327 DCHECK(!try_catch.HasException());
2328 return result.Release();
2331 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2332 PP_Var script_var,
2333 PP_Var* exception) {
2334 if (!container_)
2335 return PP_MakeUndefined();
2337 // Executing the script may remove the plugin from the DOM, so we need to keep
2338 // a reference to ourselves so that we can still process the result after the
2339 // WebBindings::evaluate() below.
2340 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2341 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2342 PepperTryCatchVar try_catch(this, &converter, exception);
2344 // Check for an exception due to the context being destroyed.
2345 if (try_catch.HasException())
2346 return PP_MakeUndefined();
2348 WebLocalFrame* frame = container_->element().document().frame();
2349 if (!frame) {
2350 try_catch.SetException("No frame to execute script in.");
2351 return PP_MakeUndefined();
2354 StringVar* script_string_var = StringVar::FromPPVar(script_var);
2355 if (!script_string_var) {
2356 try_catch.SetException("Script param to ExecuteScript must be a string.");
2357 return PP_MakeUndefined();
2360 std::string script_string = script_string_var->value();
2361 blink::WebScriptSource script(
2362 blink::WebString::fromUTF8(script_string.c_str()));
2363 v8::Handle<v8::Value> result;
2364 if (IsProcessingUserGesture()) {
2365 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2366 result = frame->executeScriptAndReturnValue(script);
2367 } else {
2368 result = frame->executeScriptAndReturnValue(script);
2371 // Check for an exception due to the context being destroyed.
2372 if (try_catch.HasException())
2373 return PP_MakeUndefined();
2375 ScopedPPVar var_result = try_catch.FromV8(result);
2376 if (try_catch.HasException())
2377 return PP_MakeUndefined();
2379 return var_result.Release();
2382 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2383 PP_Instance instance) {
2384 RenderThreadImpl* thread = RenderThreadImpl::current();
2385 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2388 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2389 PP_Instance instance) {
2390 RenderThreadImpl* thread = RenderThreadImpl::current();
2391 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2394 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2395 if (!render_frame_)
2396 return PP_MakeUndefined();
2397 return StringVar::StringToPPVar(
2398 render_frame_->render_view()->webkit_preferences().default_encoding);
2401 // These PPB_ContentDecryptor_Private calls are responses to
2402 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2403 // Therefore, |content_decryptor_delegate_| must have been initialized when
2404 // the following methods are called.
2405 void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2406 uint32 promise_id) {
2407 content_decryptor_delegate_->OnPromiseResolved(promise_id);
2410 void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2411 PP_Instance instance,
2412 uint32 promise_id,
2413 PP_Var web_session_id_var) {
2414 content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2415 web_session_id_var);
2418 void PepperPluginInstanceImpl::PromiseResolvedWithKeyIds(PP_Instance instance,
2419 uint32 promise_id,
2420 PP_Var key_ids_var) {
2421 content_decryptor_delegate_->OnPromiseResolvedWithKeyIds(promise_id,
2422 key_ids_var);
2425 void PepperPluginInstanceImpl::PromiseRejected(
2426 PP_Instance instance,
2427 uint32 promise_id,
2428 PP_CdmExceptionCode exception_code,
2429 uint32 system_code,
2430 PP_Var error_description_var) {
2431 content_decryptor_delegate_->OnPromiseRejected(
2432 promise_id, exception_code, system_code, error_description_var);
2435 void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2436 PP_Var web_session_id_var,
2437 PP_Var message_var,
2438 PP_Var destination_url_var) {
2439 content_decryptor_delegate_->OnSessionMessage(
2440 web_session_id_var, message_var, destination_url_var);
2443 void PepperPluginInstanceImpl::SessionKeysChange(
2444 PP_Instance instance,
2445 PP_Var web_session_id_var,
2446 PP_Bool has_additional_usable_key) {
2447 content_decryptor_delegate_->OnSessionKeysChange(web_session_id_var,
2448 has_additional_usable_key);
2451 void PepperPluginInstanceImpl::SessionExpirationChange(
2452 PP_Instance instance,
2453 PP_Var web_session_id_var,
2454 PP_Time new_expiry_time) {
2455 content_decryptor_delegate_->OnSessionExpirationChange(web_session_id_var,
2456 new_expiry_time);
2459 void PepperPluginInstanceImpl::SessionReady(PP_Instance instance,
2460 PP_Var web_session_id_var) {
2461 content_decryptor_delegate_->OnSessionReady(web_session_id_var);
2464 void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2465 PP_Var web_session_id_var) {
2466 content_decryptor_delegate_->OnSessionClosed(web_session_id_var);
2469 void PepperPluginInstanceImpl::SessionError(PP_Instance instance,
2470 PP_Var web_session_id_var,
2471 PP_CdmExceptionCode exception_code,
2472 uint32 system_code,
2473 PP_Var error_description_var) {
2474 content_decryptor_delegate_->OnSessionError(
2475 web_session_id_var, exception_code, system_code, error_description_var);
2478 void PepperPluginInstanceImpl::DeliverBlock(
2479 PP_Instance instance,
2480 PP_Resource decrypted_block,
2481 const PP_DecryptedBlockInfo* block_info) {
2482 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2485 void PepperPluginInstanceImpl::DecoderInitializeDone(
2486 PP_Instance instance,
2487 PP_DecryptorStreamType decoder_type,
2488 uint32_t request_id,
2489 PP_Bool success) {
2490 content_decryptor_delegate_->DecoderInitializeDone(
2491 decoder_type, request_id, success);
2494 void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2495 PP_Instance instance,
2496 PP_DecryptorStreamType decoder_type,
2497 uint32_t request_id) {
2498 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2499 request_id);
2502 void PepperPluginInstanceImpl::DecoderResetDone(
2503 PP_Instance instance,
2504 PP_DecryptorStreamType decoder_type,
2505 uint32_t request_id) {
2506 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2509 void PepperPluginInstanceImpl::DeliverFrame(
2510 PP_Instance instance,
2511 PP_Resource decrypted_frame,
2512 const PP_DecryptedFrameInfo* frame_info) {
2513 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2516 void PepperPluginInstanceImpl::DeliverSamples(
2517 PP_Instance instance,
2518 PP_Resource audio_frames,
2519 const PP_DecryptedSampleInfo* sample_info) {
2520 content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2523 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2524 PP_Instance instance) {
2525 if (!LoadFindInterface())
2526 return;
2527 bool is_main_frame =
2528 render_frame_ &&
2529 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2530 if (!is_main_frame)
2531 return;
2532 render_frame_->render_view()->set_plugin_find_handler(this);
2535 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2536 PP_Instance instance,
2537 int32_t total,
2538 PP_Bool final_result) {
2539 DCHECK_NE(find_identifier_, -1);
2540 if (render_frame_) {
2541 render_frame_->reportFindInPageMatchCount(
2542 find_identifier_, total, PP_ToBool(final_result));
2546 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2547 int32_t index) {
2548 DCHECK_NE(find_identifier_, -1);
2549 if (render_frame_) {
2550 render_frame_->reportFindInPageSelection(
2551 find_identifier_, index + 1, blink::WebRect());
2555 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2556 const PP_Rect* tickmarks,
2557 uint32_t count) {
2558 if (!render_frame_ || !render_frame_->GetWebFrame())
2559 return;
2561 blink::WebVector<blink::WebRect> tickmarks_converted(
2562 static_cast<size_t>(count));
2563 for (uint32 i = 0; i < count; ++i) {
2564 tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2565 tickmarks[i].point.y,
2566 tickmarks[i].size.width,
2567 tickmarks[i].size.height);
2570 blink::WebFrame* frame = render_frame_->GetWebFrame();
2571 frame->setTickmarks(tickmarks_converted);
2574 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2575 return PP_FromBool(view_data_.is_fullscreen);
2578 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2579 PP_Bool fullscreen) {
2580 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2583 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2584 PP_Size* size) {
2585 blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2586 *size = PP_MakeSize(info.rect.width, info.rect.height);
2587 return PP_TRUE;
2590 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2591 PP_Instance instance,
2592 ppapi::SingletonResourceID id) {
2593 // Flash APIs and some others aren't implemented in-process.
2594 switch (id) {
2595 case ppapi::BROKER_SINGLETON_ID:
2596 case ppapi::BROWSER_FONT_SINGLETON_ID:
2597 case ppapi::FILE_MAPPING_SINGLETON_ID:
2598 case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2599 case ppapi::FLASH_FILE_SINGLETON_ID:
2600 case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2601 case ppapi::FLASH_SINGLETON_ID:
2602 case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2603 case ppapi::NETWORK_PROXY_SINGLETON_ID:
2604 case ppapi::PDF_SINGLETON_ID:
2605 case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2606 NOTIMPLEMENTED();
2607 return NULL;
2608 case ppapi::GAMEPAD_SINGLETON_ID:
2609 return gamepad_impl_.get();
2610 case ppapi::UMA_SINGLETON_ID: {
2611 if (!uma_private_impl_.get()) {
2612 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2613 if (host_impl->in_process_router()) {
2614 uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2615 host_impl->in_process_router()->GetPluginConnection(instance),
2616 instance);
2619 return uma_private_impl_.get();
2623 NOTREACHED();
2624 return NULL;
2627 int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2628 uint32_t event_classes) {
2629 input_event_mask_ |= event_classes;
2630 filtered_input_event_mask_ &= ~(event_classes);
2631 RequestInputEventsHelper(event_classes);
2632 return ValidateRequestInputEvents(false, event_classes);
2635 int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2636 PP_Instance instance,
2637 uint32_t event_classes) {
2638 filtered_input_event_mask_ |= event_classes;
2639 input_event_mask_ &= ~(event_classes);
2640 RequestInputEventsHelper(event_classes);
2641 return ValidateRequestInputEvents(true, event_classes);
2644 void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2645 uint32_t event_classes) {
2646 input_event_mask_ &= ~(event_classes);
2647 filtered_input_event_mask_ &= ~(event_classes);
2648 RequestInputEventsHelper(event_classes);
2651 void PepperPluginInstanceImpl::StartTrackingLatency(PP_Instance instance) {
2652 if (module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
2653 is_tracking_latency_ = true;
2656 void PepperPluginInstanceImpl::ZoomChanged(PP_Instance instance,
2657 double factor) {
2658 // We only want to tell the page to change its zoom if the whole page is the
2659 // plugin. If we're in an iframe, then don't do anything.
2660 if (!IsFullPagePlugin())
2661 return;
2662 container()->zoomLevelChanged(content::ZoomFactorToZoomLevel(factor));
2665 void PepperPluginInstanceImpl::ZoomLimitsChanged(PP_Instance instance,
2666 double minimum_factor,
2667 double maximum_factor) {
2668 if (!render_frame_)
2669 return;
2670 if (minimum_factor > maximum_factor) {
2671 NOTREACHED();
2672 return;
2674 double minimum_level = ZoomFactorToZoomLevel(minimum_factor);
2675 double maximum_level = ZoomFactorToZoomLevel(maximum_factor);
2676 render_frame_->render_view()->webview()->zoomLimitsChanged(minimum_level,
2677 maximum_level);
2680 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2681 PP_Var message) {
2682 PostMessageToJavaScript(message);
2685 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2686 PP_MouseCursor_Type type,
2687 PP_Resource image,
2688 const PP_Point* hot_spot) {
2689 if (!ValidateSetCursorParams(type, image, hot_spot))
2690 return PP_FALSE;
2692 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2693 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2694 return PP_TRUE;
2697 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2698 if (enter.failed())
2699 return PP_FALSE;
2700 PPB_ImageData_Impl* image_data =
2701 static_cast<PPB_ImageData_Impl*>(enter.object());
2703 ImageDataAutoMapper auto_mapper(image_data);
2704 if (!auto_mapper.is_valid())
2705 return PP_FALSE;
2707 scoped_ptr<WebCursorInfo> custom_cursor(
2708 new WebCursorInfo(WebCursorInfo::TypeCustom));
2709 custom_cursor->hotSpot.x = hot_spot->x;
2710 custom_cursor->hotSpot.y = hot_spot->y;
2712 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2713 // Make a deep copy, so that the cursor remains valid even after the original
2714 // image data gets freed.
2715 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2716 return PP_FALSE;
2719 DoSetCursor(custom_cursor.release());
2720 return PP_TRUE;
2723 int32_t PepperPluginInstanceImpl::LockMouse(
2724 PP_Instance instance,
2725 scoped_refptr<TrackedCallback> callback) {
2726 if (TrackedCallback::IsPending(lock_mouse_callback_))
2727 return PP_ERROR_INPROGRESS;
2729 if (IsMouseLocked())
2730 return PP_OK;
2732 if (!CanAccessMainFrame())
2733 return PP_ERROR_NOACCESS;
2735 if (!IsProcessingUserGesture())
2736 return PP_ERROR_NO_USER_GESTURE;
2738 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2739 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2740 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2741 // Open a user gesture here so the Webkit user gesture checks will succeed
2742 // for out-of-process plugins.
2743 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2744 if (!LockMouse())
2745 return PP_ERROR_FAILED;
2748 // Either mouselock succeeded or a Flash fullscreen is pending.
2749 lock_mouse_callback_ = callback;
2750 return PP_OK_COMPLETIONPENDING;
2753 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2754 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2757 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2758 PP_TextInput_Type type) {
2759 if (!render_frame_)
2760 return;
2761 int itype = type;
2762 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2763 itype = ui::TEXT_INPUT_TYPE_NONE;
2764 SetTextInputType(static_cast<ui::TextInputType>(itype));
2767 void PepperPluginInstanceImpl::UpdateCaretPosition(
2768 PP_Instance instance,
2769 const PP_Rect& caret,
2770 const PP_Rect& bounding_box) {
2771 if (!render_frame_)
2772 return;
2773 text_input_caret_ = PP_ToGfxRect(caret);
2774 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2775 text_input_caret_set_ = true;
2776 render_frame_->PepperCaretPositionChanged(this);
2779 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2780 if (render_frame_)
2781 render_frame_->PepperCancelComposition(this);
2784 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2785 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2786 // It can be optimized so that it won't call it back until the information
2787 // is really needed.
2789 // Avoid calling in nested context or else this will reenter the plugin. This
2790 // uses a weak pointer rather than exploiting the fact that this class is
2791 // refcounted because we don't actually want this operation to affect the
2792 // lifetime of the instance.
2793 base::MessageLoop::current()->PostTask(
2794 FROM_HERE,
2795 base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2796 weak_factory_.GetWeakPtr(),
2797 static_cast<size_t>(kExtraCharsForTextInput)));
2800 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2801 const char* text,
2802 uint32_t caret,
2803 uint32_t anchor) {
2804 if (!render_frame_)
2805 return;
2806 surrounding_text_ = text;
2807 selection_caret_ = caret;
2808 selection_anchor_ = anchor;
2809 render_frame_->PepperSelectionChanged(this);
2812 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2813 PP_Instance instance,
2814 PP_Var relative,
2815 PP_URLComponents_Dev* components) {
2816 StringVar* relative_string = StringVar::FromPPVar(relative);
2817 if (!relative_string)
2818 return PP_MakeNull();
2820 WebElement plugin_element = container()->element();
2821 GURL document_url = plugin_element.document().baseURL();
2822 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2823 document_url.Resolve(relative_string->value()), components);
2826 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2827 PP_Var url) {
2828 StringVar* url_string = StringVar::FromPPVar(url);
2829 if (!url_string)
2830 return PP_FALSE;
2832 blink::WebSecurityOrigin security_origin;
2833 if (!SecurityOriginForInstance(instance, &security_origin))
2834 return PP_FALSE;
2836 GURL gurl(url_string->value());
2837 if (!gurl.is_valid())
2838 return PP_FALSE;
2840 return PP_FromBool(security_origin.canRequest(gurl));
2843 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2844 PP_Instance instance,
2845 PP_Instance target) {
2846 blink::WebSecurityOrigin our_origin;
2847 if (!SecurityOriginForInstance(instance, &our_origin))
2848 return PP_FALSE;
2850 blink::WebSecurityOrigin target_origin;
2851 if (!SecurityOriginForInstance(instance, &target_origin))
2852 return PP_FALSE;
2854 return PP_FromBool(our_origin.canAccess(target_origin));
2857 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2858 PP_Instance instance,
2859 PP_URLComponents_Dev* components) {
2860 blink::WebDocument document = container()->element().document();
2861 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2862 components);
2865 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2866 PP_Instance instance,
2867 PP_URLComponents_Dev* components) {
2868 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2871 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2872 PP_Instance instance,
2873 PP_URLComponents_Dev* components) {
2874 blink::WebDocument document = container()->element().document();
2875 if (!full_frame_)
2876 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2877 components);
2878 WebLocalFrame* frame = document.frame();
2879 if (!frame)
2880 return PP_MakeUndefined();
2881 const WebURLRequest& request = frame->dataSource()->originalRequest();
2882 WebString referer = request.httpHeaderField("Referer");
2883 if (referer.isEmpty())
2884 return PP_MakeUndefined();
2885 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2886 components);
2889 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2890 scoped_refptr<PluginModule> module) {
2891 // Save the original module and switch over to the new one now that this
2892 // plugin is using the IPC-based proxy.
2893 original_module_ = module_;
2894 module_ = module;
2896 // For NaCl instances, remember the NaCl plugin instance interface, so we
2897 // can shut it down by calling its DidDestroy in our Delete() method.
2898 original_instance_interface_.reset(instance_interface_.release());
2900 base::Callback<const void*(const char*)> get_plugin_interface_func =
2901 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2902 PPP_Instance_Combined* ppp_instance_combined =
2903 PPP_Instance_Combined::Create(get_plugin_interface_func);
2904 if (!ppp_instance_combined) {
2905 // The proxy must support at least one usable PPP_Instance interface.
2906 // While this could be a failure to implement the interface in the NaCl
2907 // module, it is more likely that the NaCl process has crashed. Either
2908 // way, report that module initialization failed.
2909 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2912 instance_interface_.reset(ppp_instance_combined);
2913 // Clear all PPP interfaces we may have cached.
2914 plugin_find_interface_ = NULL;
2915 plugin_input_event_interface_ = NULL;
2916 checked_for_plugin_input_event_interface_ = false;
2917 plugin_mouse_lock_interface_ = NULL;
2918 plugin_pdf_interface_ = NULL;
2919 checked_for_plugin_pdf_interface_ = false;
2920 plugin_private_interface_ = NULL;
2921 plugin_textinput_interface_ = NULL;
2922 plugin_zoom_interface_ = NULL;
2924 // Re-send the DidCreate event via the proxy.
2925 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2926 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2927 if (!instance_interface_->DidCreate(
2928 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2929 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2930 if (message_channel_)
2931 message_channel_->Start();
2933 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2934 // event. This way, SendDidChangeView will send the "current" view
2935 // immediately (before other events like HandleDocumentLoad).
2936 sent_initial_did_change_view_ = false;
2937 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2938 SendDidChangeView();
2940 DCHECK(external_document_load_);
2941 external_document_load_ = false;
2942 if (!external_document_response_.isNull()) {
2943 document_loader_ = NULL;
2944 // Pass the response to the new proxy.
2945 HandleDocumentLoad(external_document_response_);
2946 external_document_response_ = blink::WebURLResponse();
2947 // Replay any document load events we've received to the real loader.
2948 external_document_loader_->ReplayReceivedData(document_loader_);
2949 external_document_loader_.reset(NULL);
2952 return PP_EXTERNAL_PLUGIN_OK;
2955 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2956 DCHECK(module);
2957 return module == module_.get() || module == original_module_.get();
2960 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2961 return HostGlobals::Get()->GetInstance(instance_id);
2964 RenderView* PepperPluginInstanceImpl::GetRenderView() {
2965 return render_frame_ ? render_frame_->render_view() : NULL;
2968 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2969 return container_;
2972 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
2974 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
2975 return HostGlobals::Get()->GetVarTracker();
2978 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
2980 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
2981 return module_->path();
2984 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
2985 float scale) {
2986 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
2988 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
2989 return 0;
2991 scoped_refptr<PPB_ImageData_Impl> image_data(
2992 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
2993 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
2994 image_skia_rep.pixel_width(),
2995 image_skia_rep.pixel_height(),
2996 false)) {
2997 return 0;
3000 ImageDataAutoMapper mapper(image_data.get());
3001 if (!mapper.is_valid())
3002 return 0;
3004 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
3005 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
3006 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
3007 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
3009 return image_data->GetReference();
3012 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
3013 const base::FilePath& file_path,
3014 ppapi::PpapiPermissions permissions,
3015 const IPC::ChannelHandle& channel_handle,
3016 base::ProcessId plugin_pid,
3017 int plugin_child_id) {
3018 // Create a new module for each instance of the external plugin that is using
3019 // the IPC based out-of-process proxy. We can't use the existing module,
3020 // because it is configured for the in-process plugin, and we must keep it
3021 // that way to allow the page to create other instances.
3022 scoped_refptr<PluginModule> external_plugin_module(
3023 module_->CreateModuleForExternalPluginInstance());
3025 RendererPpapiHostImpl* renderer_ppapi_host =
3026 external_plugin_module->CreateOutOfProcessModule(render_frame_,
3027 file_path,
3028 permissions,
3029 channel_handle,
3030 plugin_pid,
3031 plugin_child_id,
3032 true);
3033 if (!renderer_ppapi_host) {
3034 DLOG(ERROR) << "CreateExternalPluginModule() failed";
3035 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
3038 // Finally, switch the instance to the proxy.
3039 return external_plugin_module->InitAsProxiedExternalPlugin(this);
3042 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3043 always_on_top_ = on_top;
3046 void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
3047 cursor_.reset(cursor);
3048 if (fullscreen_container_) {
3049 fullscreen_container_->DidChangeCursor(*cursor);
3050 } else if (render_frame_) {
3051 render_frame_->PepperDidChangeCursor(this, *cursor);
3055 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3056 WebLocalFrame* frame = container()->element().document().frame();
3057 return frame->view()->mainFrame()->document().isPluginDocument();
3060 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3061 bool delay_report) {
3062 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3063 // Keep a reference on the stack. See NOTE above.
3064 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3066 // We check whether we are trying to switch to the state we're already going
3067 // to (i.e. if we're already switching to fullscreen but the fullscreen
3068 // container isn't ready yet, don't do anything more).
3069 if (fullscreen == FlashIsFullscreenOrPending())
3070 return true;
3072 if (!render_frame_)
3073 return false;
3074 if (fullscreen && !render_frame_->render_view()
3075 ->renderer_preferences()
3076 .plugin_fullscreen_allowed)
3077 return false;
3079 // Unbind current 2D or 3D graphics context.
3080 VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3081 if (fullscreen) {
3082 DCHECK(!fullscreen_container_);
3083 fullscreen_container_ =
3084 render_frame_->CreatePepperFullscreenContainer(this);
3085 UpdateLayer(false);
3086 } else {
3087 DCHECK(fullscreen_container_);
3088 fullscreen_container_->Destroy();
3089 fullscreen_container_ = NULL;
3090 UpdateFlashFullscreenState(false);
3091 if (!delay_report) {
3092 ReportGeometry();
3093 } else {
3094 base::MessageLoop::current()->PostTask(
3095 FROM_HERE,
3096 base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3100 return true;
3103 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3104 if (flash_fullscreen_)
3105 return true;
3107 return container_->isRectTopmost(rect);
3110 int32_t PepperPluginInstanceImpl::Navigate(
3111 const ppapi::URLRequestInfoData& request,
3112 const char* target,
3113 bool from_user_action) {
3114 if (!container_)
3115 return PP_ERROR_FAILED;
3117 WebDocument document = container_->element().document();
3118 WebLocalFrame* frame = document.frame();
3119 if (!frame)
3120 return PP_ERROR_FAILED;
3122 ppapi::URLRequestInfoData completed_request = request;
3124 WebURLRequest web_request;
3125 if (!CreateWebURLRequest(
3126 pp_instance_, &completed_request, frame, &web_request)) {
3127 return PP_ERROR_FAILED;
3129 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3130 web_request.setHasUserGesture(from_user_action);
3132 GURL gurl(web_request.url());
3133 if (gurl.SchemeIs(url::kJavaScriptScheme)) {
3134 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3135 // allowed for security reasons.
3136 WebFrame* target_frame =
3137 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3138 if (target_frame != frame)
3139 return PP_ERROR_NOACCESS;
3141 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3142 // need that?
3143 WebString result = container_->executeScriptURL(gurl, from_user_action);
3144 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3147 // Only GETs and POSTs are supported.
3148 if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3149 return PP_ERROR_BADARGUMENT;
3151 WebString target_str = WebString::fromUTF8(target);
3152 container_->loadFrameRequest(web_request, target_str, false, NULL);
3153 return PP_OK;
3156 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3157 const base::FilePath& path) {
3158 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3159 PepperFileRefRendererHost* file_ref_host(
3160 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3161 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3162 scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3165 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3166 if (message_channel_)
3167 message_channel_->SetReadOnlyProperty(key, value);
3170 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3171 if (!container_)
3172 return false;
3173 blink::WebDocument containing_document = container_->element().document();
3175 if (!containing_document.frame() || !containing_document.frame()->view() ||
3176 !containing_document.frame()->view()->mainFrame()) {
3177 return false;
3179 blink::WebDocument main_document =
3180 containing_document.frame()->view()->mainFrame()->document();
3182 return containing_document.securityOrigin().canAccess(
3183 main_document.securityOrigin());
3186 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3187 WebElement element = container_->element();
3188 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3189 height_before_fullscreen_ =
3190 element.getAttribute(WebString::fromUTF8(kHeight));
3191 border_before_fullscreen_ =
3192 element.getAttribute(WebString::fromUTF8(kBorder));
3193 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3196 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3197 if (!render_frame_)
3198 return;
3199 blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3200 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3201 std::string width = StringPrintf("%d", screen_size_for_fullscreen_.width());
3202 std::string height = StringPrintf("%d", screen_size_for_fullscreen_.height());
3204 WebElement element = container_->element();
3205 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3206 element.setAttribute(WebString::fromUTF8(kHeight),
3207 WebString::fromUTF8(height));
3208 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3210 // There should be no style settings that matter in fullscreen mode,
3211 // so just replace them instead of appending.
3212 // NOTE: "position: fixed" and "display: block" reset the plugin and
3213 // using %% settings might not work without them (e.g. if the plugin is a
3214 // child of a container element).
3215 std::string style;
3216 style += StringPrintf("width: %s !important; ", width.c_str());
3217 style += StringPrintf("height: %s !important; ", height.c_str());
3218 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3219 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3222 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3223 screen_size_for_fullscreen_ = gfx::Size();
3224 WebElement element = container_->element();
3225 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3226 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3227 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3228 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3231 bool PepperPluginInstanceImpl::IsMouseLocked() {
3232 return GetMouseLockDispatcher()->IsMouseLockedTo(
3233 GetOrCreateLockTargetAdapter());
3236 bool PepperPluginInstanceImpl::LockMouse() {
3237 return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3240 MouseLockDispatcher::LockTarget*
3241 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3242 if (!lock_target_.get()) {
3243 lock_target_.reset(new PluginInstanceLockTarget(this));
3245 return lock_target_.get();
3248 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3249 if (flash_fullscreen_) {
3250 RenderWidgetFullscreenPepper* container =
3251 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3252 return container->mouse_lock_dispatcher();
3253 } else if (render_frame_) {
3254 return render_frame_->render_view()->mouse_lock_dispatcher();
3256 return NULL;
3259 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3260 if (lock_target_.get()) {
3261 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3262 lock_target_.reset();
3266 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3267 const blink::WebURLResponse& response,
3268 int pending_host_id,
3269 const ppapi::URLResponseInfoData& data) {
3270 if (is_deleted_)
3271 return;
3273 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3275 if (host_impl->in_process_router()) {
3276 // Running in-process, we can just create the resource and call the
3277 // PPP_Instance function directly.
3278 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3279 new ppapi::proxy::URLLoaderResource(
3280 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3281 pp_instance(),
3282 pending_host_id,
3283 data));
3285 PP_Resource loader_pp_resource = loader_resource->GetReference();
3286 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3287 loader_pp_resource))
3288 loader_resource->Close();
3289 // We don't pass a ref into the plugin, if it wants one, it will have taken
3290 // an additional one.
3291 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3292 loader_pp_resource);
3293 } else {
3294 // Running out-of-process. Initiate an IPC call to notify the plugin
3295 // process.
3296 ppapi::proxy::HostDispatcher* dispatcher =
3297 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3298 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3299 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3303 void PepperPluginInstanceImpl::SetPluginThrottled(bool throttled) {
3304 // Do not throttle if we've already disabled power saver.
3305 if (!power_saver_enabled_ && throttled)
3306 return;
3308 plugin_throttled_ = throttled;
3309 SendDidChangeView();
3312 } // namespace content