Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / content / renderer / pepper / pepper_plugin_instance_impl.cc
blobb9170f4cfb29cc8997efb2bc932321ac8d741c2f
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_switches.h"
26 #include "content/public/common/page_zoom.h"
27 #include "content/public/renderer/content_renderer_client.h"
28 #include "content/renderer/gpu/render_widget_compositor.h"
29 #include "content/renderer/pepper/content_decryptor_delegate.h"
30 #include "content/renderer/pepper/event_conversion.h"
31 #include "content/renderer/pepper/fullscreen_container.h"
32 #include "content/renderer/pepper/gfx_conversion.h"
33 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
34 #include "content/renderer/pepper/host_globals.h"
35 #include "content/renderer/pepper/message_channel.h"
36 #include "content/renderer/pepper/npapi_glue.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_url_loader_host.h"
43 #include "content/renderer/pepper/plugin_module.h"
44 #include "content/renderer/pepper/plugin_object.h"
45 #include "content/renderer/pepper/ppapi_preferences_builder.h"
46 #include "content/renderer/pepper/ppb_buffer_impl.h"
47 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
48 #include "content/renderer/pepper/ppb_image_data_impl.h"
49 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
50 #include "content/renderer/pepper/url_request_info_util.h"
51 #include "content/renderer/pepper/url_response_info_util.h"
52 #include "content/renderer/render_frame_impl.h"
53 #include "content/renderer/render_thread_impl.h"
54 #include "content/renderer/render_view_impl.h"
55 #include "content/renderer/render_widget.h"
56 #include "content/renderer/render_widget_fullscreen_pepper.h"
57 #include "content/renderer/sad_plugin.h"
58 #include "media/base/audio_hardware_config.h"
59 #include "ppapi/c/dev/ppb_zoom_dev.h"
60 #include "ppapi/c/dev/ppp_selection_dev.h"
61 #include "ppapi/c/dev/ppp_text_input_dev.h"
62 #include "ppapi/c/dev/ppp_zoom_dev.h"
63 #include "ppapi/c/pp_rect.h"
64 #include "ppapi/c/ppb_audio_config.h"
65 #include "ppapi/c/ppb_core.h"
66 #include "ppapi/c/ppb_gamepad.h"
67 #include "ppapi/c/ppp_input_event.h"
68 #include "ppapi/c/ppp_instance.h"
69 #include "ppapi/c/ppp_messaging.h"
70 #include "ppapi/c/ppp_mouse_lock.h"
71 #include "ppapi/c/private/ppb_find_private.h"
72 #include "ppapi/c/private/ppp_find_private.h"
73 #include "ppapi/c/private/ppp_instance_private.h"
74 #include "ppapi/c/private/ppp_pdf.h"
75 #include "ppapi/host/ppapi_host.h"
76 #include "ppapi/proxy/ppapi_messages.h"
77 #include "ppapi/proxy/serialized_var.h"
78 #include "ppapi/proxy/uma_private_resource.h"
79 #include "ppapi/proxy/url_loader_resource.h"
80 #include "ppapi/shared_impl/ppapi_permissions.h"
81 #include "ppapi/shared_impl/ppapi_preferences.h"
82 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
83 #include "ppapi/shared_impl/ppb_input_event_shared.h"
84 #include "ppapi/shared_impl/ppb_url_util_shared.h"
85 #include "ppapi/shared_impl/ppb_view_shared.h"
86 #include "ppapi/shared_impl/ppp_instance_combined.h"
87 #include "ppapi/shared_impl/resource.h"
88 #include "ppapi/shared_impl/scoped_pp_resource.h"
89 #include "ppapi/shared_impl/scoped_pp_var.h"
90 #include "ppapi/shared_impl/time_conversion.h"
91 #include "ppapi/shared_impl/url_request_info_data.h"
92 #include "ppapi/shared_impl/var.h"
93 #include "ppapi/thunk/enter.h"
94 #include "ppapi/thunk/ppb_buffer_api.h"
95 #include "printing/metafile.h"
96 #include "printing/metafile_skia_wrapper.h"
97 #include "printing/units.h"
98 #include "skia/ext/platform_canvas.h"
99 #include "skia/ext/platform_device.h"
100 #include "third_party/WebKit/public/platform/WebCursorInfo.h"
101 #include "third_party/WebKit/public/platform/WebGamepads.h"
102 #include "third_party/WebKit/public/platform/WebRect.h"
103 #include "third_party/WebKit/public/platform/WebString.h"
104 #include "third_party/WebKit/public/platform/WebURL.h"
105 #include "third_party/WebKit/public/platform/WebURLError.h"
106 #include "third_party/WebKit/public/platform/WebURLRequest.h"
107 #include "third_party/WebKit/public/web/WebBindings.h"
108 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
109 #include "third_party/WebKit/public/web/WebDataSource.h"
110 #include "third_party/WebKit/public/web/WebDocument.h"
111 #include "third_party/WebKit/public/web/WebElement.h"
112 #include "third_party/WebKit/public/web/WebInputEvent.h"
113 #include "third_party/WebKit/public/web/WebLocalFrame.h"
114 #include "third_party/WebKit/public/web/WebPluginContainer.h"
115 #include "third_party/WebKit/public/web/WebPrintParams.h"
116 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
117 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
118 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
119 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
120 #include "third_party/WebKit/public/web/WebView.h"
121 #include "third_party/khronos/GLES2/gl2.h"
122 #include "third_party/skia/include/core/SkCanvas.h"
123 #include "third_party/skia/include/core/SkRect.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 "ui/gfx/rect_conversions.h"
128 #include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h"
129 #include "v8/include/v8.h"
131 #if defined(OS_CHROMEOS)
132 #include "ui/events/keycodes/keyboard_codes_posix.h"
133 #endif
135 #if defined(OS_MACOSX)
136 #include "printing/metafile_impl.h"
137 #endif // defined(OS_MACOSX)
139 #if defined(OS_WIN)
140 #include "base/metrics/histogram.h"
141 #include "base/win/windows_version.h"
142 #include "skia/ext/platform_canvas.h"
143 #include "ui/gfx/codec/jpeg_codec.h"
144 #include "ui/gfx/gdi_util.h"
145 #endif
147 using base::StringPrintf;
148 using ppapi::InputEventData;
149 using ppapi::PpapiGlobals;
150 using ppapi::PPB_InputEvent_Shared;
151 using ppapi::PPB_View_Shared;
152 using ppapi::PPP_Instance_Combined;
153 using ppapi::Resource;
154 using ppapi::ScopedPPResource;
155 using ppapi::ScopedPPVar;
156 using ppapi::StringVar;
157 using ppapi::TrackedCallback;
158 using ppapi::thunk::EnterResourceNoLock;
159 using ppapi::thunk::PPB_Buffer_API;
160 using ppapi::thunk::PPB_Gamepad_API;
161 using ppapi::thunk::PPB_Graphics2D_API;
162 using ppapi::thunk::PPB_Graphics3D_API;
163 using ppapi::thunk::PPB_ImageData_API;
164 using ppapi::Var;
165 using ppapi::ArrayBufferVar;
166 using ppapi::ViewData;
167 using blink::WebBindings;
168 using blink::WebCanvas;
169 using blink::WebCursorInfo;
170 using blink::WebDocument;
171 using blink::WebElement;
172 using blink::WebFrame;
173 using blink::WebInputEvent;
174 using blink::WebLocalFrame;
175 using blink::WebPlugin;
176 using blink::WebPluginContainer;
177 using blink::WebPrintParams;
178 using blink::WebPrintScalingOption;
179 using blink::WebScopedUserGesture;
180 using blink::WebString;
181 using blink::WebURLError;
182 using blink::WebURLLoader;
183 using blink::WebURLLoaderClient;
184 using blink::WebURLRequest;
185 using blink::WebURLResponse;
186 using blink::WebUserGestureIndicator;
187 using blink::WebUserGestureToken;
188 using blink::WebView;
190 namespace content {
192 #if defined(OS_WIN)
193 // Exported by pdf.dll
194 typedef bool (*RenderPDFPageToDCProc)(const unsigned char* pdf_buffer,
195 int buffer_size,
196 int page_number,
197 HDC dc,
198 int dpi_x,
199 int dpi_y,
200 int bounds_origin_x,
201 int bounds_origin_y,
202 int bounds_width,
203 int bounds_height,
204 bool fit_to_bounds,
205 bool stretch_to_bounds,
206 bool keep_aspect_ratio,
207 bool center_in_bounds,
208 bool autorotate);
210 void DrawEmptyRectangle(HDC dc) {
211 // TODO(sanjeevr): This is a temporary hack. If we output a JPEG
212 // to the EMF, the EnumEnhMetaFile call fails in the browser
213 // process. The failure also happens if we output nothing here.
214 // We need to investigate the reason for this failure and fix it.
215 // In the meantime this temporary hack of drawing an empty
216 // rectangle in the DC gets us by.
217 Rectangle(dc, 0, 0, 0, 0);
219 #endif // defined(OS_WIN)
221 namespace {
223 // Check PP_TextInput_Type and ui::TextInputType are kept in sync.
224 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NONE) == int(PP_TEXTINPUT_TYPE_NONE),
225 mismatching_enums);
226 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TEXT) == int(PP_TEXTINPUT_TYPE_TEXT),
227 mismatching_enums);
228 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_PASSWORD) ==
229 int(PP_TEXTINPUT_TYPE_PASSWORD),
230 mismatching_enums);
231 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_SEARCH) == int(PP_TEXTINPUT_TYPE_SEARCH),
232 mismatching_enums);
233 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_EMAIL) == int(PP_TEXTINPUT_TYPE_EMAIL),
234 mismatching_enums);
235 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NUMBER) == int(PP_TEXTINPUT_TYPE_NUMBER),
236 mismatching_enums);
237 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TELEPHONE) ==
238 int(PP_TEXTINPUT_TYPE_TELEPHONE),
239 mismatching_enums);
240 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_URL) == int(PP_TEXTINPUT_TYPE_URL),
241 mismatching_enums);
243 // The default text input type is to regard the plugin always accept text input.
244 // This is for allowing users to use input methods even on completely-IME-
245 // unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
246 // Plugins need to explicitly opt out the text input mode if they know
247 // that they don't accept texts.
248 const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
250 #define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
251 COMPILE_ASSERT(static_cast<int>(WebCursorInfo::webkit_name) == \
252 static_cast<int>(np_name), \
253 mismatching_enums)
255 #define COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(webkit_name, pp_name) \
256 COMPILE_ASSERT(static_cast<int>(webkit_name) == static_cast<int>(pp_name), \
257 mismatching_enums)
259 // <embed>/<object> attributes.
260 const char kWidth[] = "width";
261 const char kHeight[] = "height";
262 const char kBorder[] = "border"; // According to w3c, deprecated.
263 const char kStyle[] = "style";
265 COMPILE_ASSERT_MATCHING_ENUM(TypePointer, PP_MOUSECURSOR_TYPE_POINTER);
266 COMPILE_ASSERT_MATCHING_ENUM(TypeCross, PP_MOUSECURSOR_TYPE_CROSS);
267 COMPILE_ASSERT_MATCHING_ENUM(TypeHand, PP_MOUSECURSOR_TYPE_HAND);
268 COMPILE_ASSERT_MATCHING_ENUM(TypeIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
269 COMPILE_ASSERT_MATCHING_ENUM(TypeWait, PP_MOUSECURSOR_TYPE_WAIT);
270 COMPILE_ASSERT_MATCHING_ENUM(TypeHelp, PP_MOUSECURSOR_TYPE_HELP);
271 COMPILE_ASSERT_MATCHING_ENUM(TypeEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
272 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
273 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastResize,
274 PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
275 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestResize,
276 PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
277 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
278 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastResize,
279 PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
280 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestResize,
281 PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
282 COMPILE_ASSERT_MATCHING_ENUM(TypeWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
283 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
284 PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
285 COMPILE_ASSERT_MATCHING_ENUM(TypeEastWestResize,
286 PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
287 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
288 PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
289 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
290 PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
291 COMPILE_ASSERT_MATCHING_ENUM(TypeColumnResize,
292 PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
293 COMPILE_ASSERT_MATCHING_ENUM(TypeRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
294 COMPILE_ASSERT_MATCHING_ENUM(TypeMiddlePanning,
295 PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
296 COMPILE_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
297 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthPanning,
298 PP_MOUSECURSOR_TYPE_NORTHPANNING);
299 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
300 PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
301 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
302 PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
303 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthPanning,
304 PP_MOUSECURSOR_TYPE_SOUTHPANNING);
305 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
306 PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
307 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
308 PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
309 COMPILE_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
310 COMPILE_ASSERT_MATCHING_ENUM(TypeMove, PP_MOUSECURSOR_TYPE_MOVE);
311 COMPILE_ASSERT_MATCHING_ENUM(TypeVerticalText,
312 PP_MOUSECURSOR_TYPE_VERTICALTEXT);
313 COMPILE_ASSERT_MATCHING_ENUM(TypeCell, PP_MOUSECURSOR_TYPE_CELL);
314 COMPILE_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
315 COMPILE_ASSERT_MATCHING_ENUM(TypeAlias, PP_MOUSECURSOR_TYPE_ALIAS);
316 COMPILE_ASSERT_MATCHING_ENUM(TypeProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
317 COMPILE_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
318 COMPILE_ASSERT_MATCHING_ENUM(TypeCopy, PP_MOUSECURSOR_TYPE_COPY);
319 COMPILE_ASSERT_MATCHING_ENUM(TypeNone, PP_MOUSECURSOR_TYPE_NONE);
320 COMPILE_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
321 COMPILE_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
322 COMPILE_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
323 COMPILE_ASSERT_MATCHING_ENUM(TypeGrab, PP_MOUSECURSOR_TYPE_GRAB);
324 COMPILE_ASSERT_MATCHING_ENUM(TypeGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
325 // Do not assert WebCursorInfo::TypeCustom == PP_CURSORTYPE_CUSTOM;
326 // PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
328 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(blink::WebPrintScalingOptionNone,
329 PP_PRINTSCALINGOPTION_NONE);
330 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
331 blink::WebPrintScalingOptionFitToPrintableArea,
332 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
333 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
334 blink::WebPrintScalingOptionSourceSize,
335 PP_PRINTSCALINGOPTION_SOURCE_SIZE);
337 // Sets |*security_origin| to be the WebKit security origin associated with the
338 // document containing the given plugin instance. On success, returns true. If
339 // the instance is invalid, returns false and |*security_origin| will be
340 // unchanged.
341 bool SecurityOriginForInstance(PP_Instance instance_id,
342 blink::WebSecurityOrigin* security_origin) {
343 PepperPluginInstanceImpl* instance =
344 HostGlobals::Get()->GetInstance(instance_id);
345 if (!instance)
346 return false;
348 WebElement plugin_element = instance->container()->element();
349 *security_origin = plugin_element.document().securityOrigin();
350 return true;
353 // Convert the given vector to an array of C-strings. The strings in the
354 // returned vector are only guaranteed valid so long as the vector of strings
355 // is not modified.
356 scoped_ptr<const char* []> StringVectorToArgArray(
357 const std::vector<std::string>& vector) {
358 scoped_ptr<const char * []> array(new const char* [vector.size()]);
359 for (size_t i = 0; i < vector.size(); ++i)
360 array[i] = vector[i].c_str();
361 return array.Pass();
364 // Returns true if this is a "system reserved" key which should not be sent to
365 // a plugin. Some poorly behaving plugins (like Flash) incorrectly report that
366 // they handle all keys sent to them. This can prevent keystrokes from working
367 // for things like screen brightness and volume control.
368 bool IsReservedSystemInputEvent(const blink::WebInputEvent& event) {
369 #if defined(OS_CHROMEOS)
370 if (event.type != WebInputEvent::KeyDown &&
371 event.type != WebInputEvent::KeyUp)
372 return false;
373 const blink::WebKeyboardEvent& key_event =
374 static_cast<const blink::WebKeyboardEvent&>(event);
375 switch (key_event.windowsKeyCode) {
376 case ui::VKEY_BRIGHTNESS_DOWN:
377 case ui::VKEY_BRIGHTNESS_UP:
378 case ui::VKEY_KBD_BRIGHTNESS_DOWN:
379 case ui::VKEY_KBD_BRIGHTNESS_UP:
380 case ui::VKEY_VOLUME_MUTE:
381 case ui::VKEY_VOLUME_DOWN:
382 case ui::VKEY_VOLUME_UP:
383 return true;
384 default:
385 return false;
387 #endif // defined(OS_CHROMEOS)
388 return false;
391 class PluginInstanceLockTarget : public MouseLockDispatcher::LockTarget {
392 public:
393 PluginInstanceLockTarget(PepperPluginInstanceImpl* plugin)
394 : plugin_(plugin) {}
396 virtual void OnLockMouseACK(bool succeeded) OVERRIDE {
397 plugin_->OnLockMouseACK(succeeded);
400 virtual void OnMouseLockLost() OVERRIDE { plugin_->OnMouseLockLost(); }
402 virtual bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event)
403 OVERRIDE {
404 plugin_->HandleMouseLockedInputEvent(event);
405 return true;
408 private:
409 PepperPluginInstanceImpl* plugin_;
412 void InitLatencyInfo(ui::LatencyInfo* new_latency,
413 const ui::LatencyInfo* old_latency,
414 blink::WebInputEvent::Type type,
415 int64 input_sequence) {
416 new_latency->AddLatencyNumber(
417 ui::INPUT_EVENT_LATENCY_BEGIN_PLUGIN_COMPONENT,
419 input_sequence);
420 new_latency->TraceEventType(WebInputEventTraits::GetName(type));
421 if (old_latency) {
422 new_latency->CopyLatencyFrom(*old_latency,
423 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
424 new_latency->CopyLatencyFrom(*old_latency,
425 ui::INPUT_EVENT_LATENCY_UI_COMPONENT);
429 } // namespace
431 // static
432 PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
433 RenderFrameImpl* render_frame,
434 PluginModule* module,
435 WebPluginContainer* container,
436 const GURL& plugin_url) {
437 base::Callback<const void*(const char*)> get_plugin_interface_func =
438 base::Bind(&PluginModule::GetPluginInterface, module);
439 PPP_Instance_Combined* ppp_instance_combined =
440 PPP_Instance_Combined::Create(get_plugin_interface_func);
441 if (!ppp_instance_combined)
442 return NULL;
443 return new PepperPluginInstanceImpl(
444 render_frame, module, ppp_instance_combined, container, plugin_url);
447 PepperPluginInstanceImpl::ExternalDocumentLoader::ExternalDocumentLoader()
448 : finished_loading_(false) {}
450 PepperPluginInstanceImpl::ExternalDocumentLoader::~ExternalDocumentLoader() {}
452 void PepperPluginInstanceImpl::ExternalDocumentLoader::ReplayReceivedData(
453 WebURLLoaderClient* document_loader) {
454 for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
455 ++it) {
456 document_loader->didReceiveData(
457 NULL, it->c_str(), it->length(), 0 /* encoded_data_length */);
459 if (finished_loading_) {
460 document_loader->didFinishLoading(
461 NULL,
462 0 /* finish_time */,
463 blink::WebURLLoaderClient::kUnknownEncodedDataLength);
465 if (error_.get()) {
466 document_loader->didFail(NULL, *error_);
470 void PepperPluginInstanceImpl::ExternalDocumentLoader::didReceiveData(
471 WebURLLoader* loader,
472 const char* data,
473 int data_length,
474 int encoded_data_length) {
475 data_.push_back(std::string(data, data_length));
478 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFinishLoading(
479 WebURLLoader* loader,
480 double finish_time,
481 int64_t total_encoded_data_length) {
482 DCHECK(!finished_loading_);
483 finished_loading_ = true;
486 void PepperPluginInstanceImpl::ExternalDocumentLoader::didFail(
487 WebURLLoader* loader,
488 const WebURLError& error) {
489 DCHECK(!error_.get());
490 error_.reset(new WebURLError(error));
493 PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
494 : Resource(ppapi::Resource::Untracked()) {}
496 PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
498 PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
499 return this;
502 void PepperPluginInstanceImpl::GamepadImpl::Sample(
503 PP_Instance instance,
504 PP_GamepadsSampleData* data) {
505 blink::WebGamepads webkit_data;
506 RenderThreadImpl::current()->SampleGamepads(&webkit_data);
507 ConvertWebKitGamepadData(bit_cast<ppapi::WebKitGamepads>(webkit_data), data);
510 PepperPluginInstanceImpl::PepperPluginInstanceImpl(
511 RenderFrameImpl* render_frame,
512 PluginModule* module,
513 ppapi::PPP_Instance_Combined* instance_interface,
514 WebPluginContainer* container,
515 const GURL& plugin_url)
516 : RenderFrameObserver(render_frame),
517 render_frame_(render_frame),
518 module_(module),
519 instance_interface_(instance_interface),
520 pp_instance_(0),
521 container_(container),
522 layer_bound_to_fullscreen_(false),
523 layer_is_hardware_(false),
524 plugin_url_(plugin_url),
525 full_frame_(false),
526 sent_initial_did_change_view_(false),
527 bound_graphics_2d_platform_(NULL),
528 bound_compositor_(NULL),
529 has_webkit_focus_(false),
530 has_content_area_focus_(false),
531 find_identifier_(-1),
532 plugin_find_interface_(NULL),
533 plugin_input_event_interface_(NULL),
534 plugin_mouse_lock_interface_(NULL),
535 plugin_pdf_interface_(NULL),
536 plugin_private_interface_(NULL),
537 plugin_selection_interface_(NULL),
538 plugin_textinput_interface_(NULL),
539 plugin_zoom_interface_(NULL),
540 checked_for_plugin_input_event_interface_(false),
541 checked_for_plugin_pdf_interface_(false),
542 gamepad_impl_(new GamepadImpl()),
543 uma_private_impl_(NULL),
544 plugin_print_interface_(NULL),
545 plugin_graphics_3d_interface_(NULL),
546 always_on_top_(false),
547 fullscreen_container_(NULL),
548 flash_fullscreen_(false),
549 desired_fullscreen_state_(false),
550 sad_plugin_(NULL),
551 input_event_mask_(0),
552 filtered_input_event_mask_(0),
553 text_input_type_(kPluginDefaultTextInputType),
554 text_input_caret_(0, 0, 0, 0),
555 text_input_caret_bounds_(0, 0, 0, 0),
556 text_input_caret_set_(false),
557 selection_caret_(0),
558 selection_anchor_(0),
559 pending_user_gesture_(0.0),
560 document_loader_(NULL),
561 external_document_load_(false),
562 npp_(new NPP_t),
563 isolate_(v8::Isolate::GetCurrent()),
564 is_deleted_(false),
565 last_input_number_(0),
566 is_tracking_latency_(false),
567 view_change_weak_ptr_factory_(this),
568 weak_factory_(this) {
569 pp_instance_ = HostGlobals::Get()->AddInstance(this);
571 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
572 module_->InstanceCreated(this);
574 if (render_frame) { // NULL in tests
575 render_frame->render_view()->PepperInstanceCreated(this);
576 // Bind a callback now so that we can inform the RenderViewImpl when we are
577 // destroyed. This works around a temporary problem stemming from work to
578 // move parts of RenderViewImpl in to RenderFrameImpl (see
579 // crbug.com/245126). If destruction happens in this order:
580 // 1) RenderFrameImpl
581 // 2) PepperPluginInstanceImpl
582 // 3) RenderViewImpl
583 // Then after 1), the PepperPluginInstanceImpl doesn't have any way to talk
584 // to the RenderViewImpl. But when the instance is destroyed, it still
585 // needs to inform the RenderViewImpl that it has gone away, otherwise
586 // between (2) and (3), the RenderViewImpl will still have the dead
587 // instance in its active set, and so might make calls on the deleted
588 // instance. See crbug.com/343576 for more information. Once the plugin
589 // calls move entirely from RenderViewImpl in to RenderFrameImpl, this
590 // can be a little bit simplified by instead making a direct call on
591 // RenderFrameImpl in the destructor (but only if render_frame_ is valid).
592 instance_deleted_callback_ =
593 base::Bind(&RenderViewImpl::PepperInstanceDeleted,
594 render_frame->render_view()->AsWeakPtr(),
595 base::Unretained(this));
596 view_data_.is_page_visible = !render_frame_->GetRenderWidget()->is_hidden();
598 // Set the initial focus.
599 SetContentAreaFocus(render_frame_->GetRenderWidget()->has_focus());
601 if (!module_->IsProxied()) {
602 PepperBrowserConnection* browser_connection =
603 PepperBrowserConnection::Get(render_frame_);
604 browser_connection->DidCreateInProcessInstance(
605 pp_instance(),
606 render_frame_->GetRoutingID(),
607 container_->element().document().url(),
608 GetPluginURL());
612 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
613 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
615 if (GetContentClient()->renderer() && // NULL in unit tests.
616 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
617 external_document_load_ = true;
620 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
621 DCHECK(!fullscreen_container_);
623 // Free all the plugin objects. This will automatically clear the back-
624 // pointer from the NPObject so WebKit can't call into the plugin any more.
626 // Swap out the set so we can delete from it (the objects will try to
627 // unregister themselves inside the delete call).
628 PluginObjectSet plugin_object_copy;
629 live_plugin_objects_.swap(plugin_object_copy);
630 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
631 i != plugin_object_copy.end();
632 ++i)
633 delete *i;
635 if (TrackedCallback::IsPending(lock_mouse_callback_))
636 lock_mouse_callback_->Abort();
638 if (!instance_deleted_callback_.is_null())
639 instance_deleted_callback_.Run();
641 if (!module_->IsProxied() && render_frame_) {
642 PepperBrowserConnection* browser_connection =
643 PepperBrowserConnection::Get(render_frame_);
644 browser_connection->DidDeleteInProcessInstance(pp_instance());
647 UnSetAndDeleteLockTargetAdapter();
648 module_->InstanceDeleted(this);
649 // If we switched from the NaCl plugin module, notify it too.
650 if (original_module_.get())
651 original_module_->InstanceDeleted(this);
653 // This should be last since some of the above "instance deleted" calls will
654 // want to look up in the global map to get info off of our object.
655 HostGlobals::Get()->InstanceDeleted(pp_instance_);
658 // NOTE: Any of these methods that calls into the plugin needs to take into
659 // account that the plugin may use Var to remove the <embed> from the DOM, which
660 // will make the PepperWebPluginImpl drop its reference, usually the last one.
661 // If a method needs to access a member of the instance after the call has
662 // returned, then it needs to keep its own reference on the stack.
664 v8::Local<v8::Context> PepperPluginInstanceImpl::GetContext() {
665 if (!container_)
666 return v8::Handle<v8::Context>();
667 WebLocalFrame* frame = container_->element().document().frame();
668 if (!frame)
669 return v8::Handle<v8::Context>();
671 v8::Local<v8::Context> context = frame->mainWorldScriptContext();
672 DCHECK(context->GetIsolate() == isolate_);
673 return context;
676 void PepperPluginInstanceImpl::Delete() {
677 is_deleted_ = true;
679 if (render_frame_ &&
680 render_frame_->render_view()->plugin_find_handler() == this) {
681 render_frame_->render_view()->set_plugin_find_handler(NULL);
684 // Keep a reference on the stack. See NOTE above.
685 scoped_refptr<PepperPluginInstanceImpl> ref(this);
686 // Force the MessageChannel to release its "passthrough object" which should
687 // release our last reference to the "InstanceObject" and will probably
688 // destroy it. We want to do this prior to calling DidDestroy in case the
689 // destructor of the instance object tries to use the instance.
690 message_channel_->SetPassthroughObject(NULL);
691 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
692 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
693 // since there is little that it can do at this point.
694 if (original_instance_interface_)
695 original_instance_interface_->DidDestroy(pp_instance());
696 else
697 instance_interface_->DidDestroy(pp_instance());
698 // Ensure we don't attempt to call functions on the destroyed instance.
699 original_instance_interface_.reset();
700 instance_interface_.reset();
702 if (fullscreen_container_) {
703 fullscreen_container_->Destroy();
704 fullscreen_container_ = NULL;
707 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
708 // leaks the graphics 2D, it may actually get cleaned up after our
709 // destruction, so we need its pointers to be up-to-date.
710 BindGraphics(pp_instance(), 0);
711 container_ = NULL;
714 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
716 void PepperPluginInstanceImpl::Paint(WebCanvas* canvas,
717 const gfx::Rect& plugin_rect,
718 const gfx::Rect& paint_rect) {
719 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
720 if (module()->is_crashed()) {
721 // Crashed plugin painting.
722 if (!sad_plugin_) // Lazily initialize bitmap.
723 sad_plugin_ = GetContentClient()->renderer()->GetSadPluginBitmap();
724 if (sad_plugin_)
725 PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
726 return;
729 if (bound_graphics_2d_platform_)
730 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
733 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
734 if (fullscreen_container_) {
735 if (rect.IsEmpty())
736 fullscreen_container_->Invalidate();
737 else
738 fullscreen_container_->InvalidateRect(rect);
739 } else {
740 if (!container_ || view_data_.rect.size.width == 0 ||
741 view_data_.rect.size.height == 0)
742 return; // Nothing to do.
743 if (rect.IsEmpty())
744 container_->invalidate();
745 else
746 container_->invalidateRect(rect);
749 cc::Layer* layer =
750 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
751 if (layer) {
752 if (rect.IsEmpty()) {
753 layer->SetNeedsDisplay();
754 } else {
755 layer->SetNeedsDisplayRect(rect);
760 void PepperPluginInstanceImpl::ScrollRect(int dx,
761 int dy,
762 const gfx::Rect& rect) {
763 cc::Layer* layer =
764 texture_layer_.get() ? texture_layer_.get() : compositor_layer_.get();
765 if (layer) {
766 InvalidateRect(rect);
767 } else if (fullscreen_container_) {
768 fullscreen_container_->ScrollRect(dx, dy, rect);
769 } else {
770 if (full_frame_ && !IsViewAccelerated()) {
771 container_->scrollRect(rect);
772 } else {
773 // Can't do optimized scrolling since there could be other elements on top
774 // of us or the view renders via the accelerated compositor which is
775 // incompatible with the move and backfill scrolling model.
776 InvalidateRect(rect);
781 void PepperPluginInstanceImpl::CommitBackingTexture() {
782 if (!texture_layer_.get())
783 return;
784 gpu::Mailbox mailbox;
785 uint32 sync_point = 0;
786 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
787 DCHECK(!mailbox.IsZero());
788 DCHECK_NE(sync_point, 0u);
789 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
790 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
791 texture_layer_->SetNeedsDisplay();
794 void PepperPluginInstanceImpl::InstanceCrashed() {
795 // Force free all resources and vars.
796 HostGlobals::Get()->InstanceCrashed(pp_instance());
798 // Free any associated graphics.
799 SetFullscreen(false);
800 FlashSetFullscreen(false, false);
801 // Unbind current 2D or 3D graphics context.
802 BindGraphics(pp_instance(), 0);
803 InvalidateRect(gfx::Rect());
805 if (content_decryptor_delegate_) {
806 content_decryptor_delegate_->InstanceCrashed();
807 content_decryptor_delegate_.reset();
810 if (render_frame_)
811 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
812 UnSetAndDeleteLockTargetAdapter();
815 static void SetGPUHistogram(const ppapi::Preferences& prefs,
816 const std::vector<std::string>& arg_names,
817 const std::vector<std::string>& arg_values) {
818 // Calculate a histogram to let us determine how likely people are to try to
819 // run Stage3D content on machines that have it blacklisted.
820 #if defined(OS_WIN)
821 bool needs_gpu = false;
822 bool is_xp = base::win::GetVersion() <= base::win::VERSION_XP;
824 for (size_t i = 0; i < arg_names.size(); i++) {
825 if (arg_names[i] == "wmode") {
826 // In theory content other than Flash could have a "wmode" argument,
827 // but that's pretty unlikely.
828 if (arg_values[i] == "direct" || arg_values[i] == "gpu")
829 needs_gpu = true;
830 break;
833 // 0 : No 3D content and GPU is blacklisted
834 // 1 : No 3D content and GPU is not blacklisted
835 // 2 : 3D content but GPU is blacklisted
836 // 3 : 3D content and GPU is not blacklisted
837 // 4 : No 3D content and GPU is blacklisted on XP
838 // 5 : No 3D content and GPU is not blacklisted on XP
839 // 6 : 3D content but GPU is blacklisted on XP
840 // 7 : 3D content and GPU is not blacklisted on XP
841 UMA_HISTOGRAM_ENUMERATION(
842 "Flash.UsesGPU", is_xp * 4 + needs_gpu * 2 + prefs.is_webgl_supported, 8);
843 #endif
846 bool PepperPluginInstanceImpl::Initialize(
847 const std::vector<std::string>& arg_names,
848 const std::vector<std::string>& arg_values,
849 bool full_frame) {
850 if (!render_frame_)
851 return false;
852 message_channel_.reset(new MessageChannel(this));
854 full_frame_ = full_frame;
856 UpdateTouchEventRequest();
857 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
859 SetGPUHistogram(ppapi::Preferences(PpapiPreferencesBuilder::Build(
860 render_frame_->render_view()->webkit_preferences())),
861 arg_names,
862 arg_values);
864 argn_ = arg_names;
865 argv_ = arg_values;
866 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
867 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
868 bool success = PP_ToBool(instance_interface_->DidCreate(
869 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
870 // If this is a plugin that hosts external plugins, we should delay messages
871 // so that the child plugin that's created later will receive all the
872 // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
874 // A host for external plugins will call ResetAsProxied later, at which point
875 // we can Start() the message_channel_.
876 if (success && (!module_->renderer_ppapi_host()->IsExternalPluginHost()))
877 message_channel_->Start();
878 return success;
881 bool PepperPluginInstanceImpl::HandleDocumentLoad(
882 const blink::WebURLResponse& response) {
883 DCHECK(!document_loader_);
884 if (external_document_load_) {
885 // The external proxy isn't available, so save the response and record
886 // document load notifications for later replay.
887 external_document_response_ = response;
888 external_document_loader_.reset(new ExternalDocumentLoader());
889 document_loader_ = external_document_loader_.get();
890 return true;
893 if (module()->is_crashed()) {
894 // Don't create a resource for a crashed plugin.
895 container()->element().document().frame()->stopLoading();
896 return false;
899 DCHECK(!document_loader_);
901 // Create a loader resource host for this load. Note that we have to set
902 // the document_loader before issuing the in-process
903 // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
904 // call into the instance and expect it to be valid.
905 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
906 PepperURLLoaderHost* loader_host =
907 new PepperURLLoaderHost(host_impl, true, pp_instance(), 0);
908 // TODO(teravest): Remove set_document_loader() from instance and clean up
909 // this relationship.
910 set_document_loader(loader_host);
911 loader_host->didReceiveResponse(NULL, response);
913 // This host will be pending until the resource object attaches to it.
915 // PpapiHost now owns the pointer to loader_host, so we don't have to worry
916 // about managing it.
917 int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
918 scoped_ptr<ppapi::host::ResourceHost>(loader_host));
919 DCHECK(pending_host_id);
921 DataFromWebURLResponse(
922 host_impl,
923 pp_instance(),
924 response,
925 base::Bind(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
926 weak_factory_.GetWeakPtr(),
927 response,
928 pending_host_id));
930 // If the load was not abandoned, document_loader_ will now be set. It's
931 // possible that the load was canceled by now and document_loader_ was
932 // already nulled out.
933 return true;
936 bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
937 PP_InputEvent_Type type,
938 const base::string16& text) {
939 std::vector<blink::WebCompositionUnderline> empty;
940 return SendCompositionEventWithUnderlineInformationToPlugin(
941 type,
942 text,
943 empty,
944 static_cast<int>(text.size()),
945 static_cast<int>(text.size()));
948 bool
949 PepperPluginInstanceImpl::SendCompositionEventWithUnderlineInformationToPlugin(
950 PP_InputEvent_Type type,
951 const base::string16& text,
952 const std::vector<blink::WebCompositionUnderline>& underlines,
953 int selection_start,
954 int selection_end) {
955 // Keep a reference on the stack. See NOTE above.
956 scoped_refptr<PepperPluginInstanceImpl> ref(this);
958 if (!LoadInputEventInterface())
959 return false;
961 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
962 if (!(filtered_input_event_mask_ & event_class) &&
963 !(input_event_mask_ & event_class))
964 return false;
966 ppapi::InputEventData event;
967 event.event_type = type;
968 event.event_time_stamp =
969 ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
971 // Convert UTF16 text to UTF8 with offset conversion.
972 std::vector<size_t> utf16_offsets;
973 utf16_offsets.push_back(selection_start);
974 utf16_offsets.push_back(selection_end);
975 for (size_t i = 0; i < underlines.size(); ++i) {
976 utf16_offsets.push_back(underlines[i].startOffset);
977 utf16_offsets.push_back(underlines[i].endOffset);
979 std::vector<size_t> utf8_offsets(utf16_offsets);
980 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
982 // Set the converted selection range.
983 event.composition_selection_start =
984 (utf8_offsets[0] == std::string::npos ? event.character_text.size()
985 : utf8_offsets[0]);
986 event.composition_selection_end =
987 (utf8_offsets[1] == std::string::npos ? event.character_text.size()
988 : utf8_offsets[1]);
990 // Set the converted segmentation points.
991 // Be sure to add 0 and size(), and remove duplication or errors.
992 std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
993 offset_set.insert(0);
994 offset_set.insert(event.character_text.size());
995 offset_set.erase(std::string::npos);
996 event.composition_segment_offsets.assign(offset_set.begin(),
997 offset_set.end());
999 // Set the composition target.
1000 for (size_t i = 0; i < underlines.size(); ++i) {
1001 if (underlines[i].thick) {
1002 std::vector<uint32_t>::iterator it =
1003 std::find(event.composition_segment_offsets.begin(),
1004 event.composition_segment_offsets.end(),
1005 utf8_offsets[2 * i + 2]);
1006 if (it != event.composition_segment_offsets.end()) {
1007 event.composition_target_segment =
1008 it - event.composition_segment_offsets.begin();
1009 break;
1014 // Send the event.
1015 bool handled = false;
1016 if (filtered_input_event_mask_ & event_class)
1017 event.is_filtered = true;
1018 else
1019 handled = true; // Unfiltered events are assumed to be handled.
1020 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1021 new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
1022 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1023 pp_instance(), event_resource->pp_resource()));
1024 return handled;
1027 void PepperPluginInstanceImpl::RequestInputEventsHelper(
1028 uint32_t event_classes) {
1029 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
1030 UpdateTouchEventRequest();
1031 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
1032 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
1035 bool PepperPluginInstanceImpl::HandleCompositionStart(
1036 const base::string16& text) {
1037 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1038 text);
1041 bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1042 const base::string16& text,
1043 const std::vector<blink::WebCompositionUnderline>& underlines,
1044 int selection_start,
1045 int selection_end) {
1046 return SendCompositionEventWithUnderlineInformationToPlugin(
1047 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
1048 text,
1049 underlines,
1050 selection_start,
1051 selection_end);
1054 bool PepperPluginInstanceImpl::HandleCompositionEnd(
1055 const base::string16& text) {
1056 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1057 text);
1060 bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1061 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1064 void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1065 gfx::Range* range) const {
1066 std::vector<size_t> offsets;
1067 offsets.push_back(selection_anchor_);
1068 offsets.push_back(selection_caret_);
1069 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1070 range->set_start(offsets[0] == base::string16::npos ? text->size()
1071 : offsets[0]);
1072 range->set_end(offsets[1] == base::string16::npos ? text->size()
1073 : offsets[1]);
1076 bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1077 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1078 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1081 gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1082 if (!text_input_caret_set_) {
1083 // If it is never set by the plugin, use the bottom left corner.
1084 return gfx::Rect(view_data_.rect.point.x,
1085 view_data_.rect.point.y + view_data_.rect.size.height,
1090 // TODO(kinaba) Take CSS transformation into accont.
1091 // TODO(kinaba) Take bounding_box into account. On some platforms, an
1092 // "exclude rectangle" where candidate window must avoid the region can be
1093 // passed to IME. Currently, we pass only the caret rectangle because
1094 // it is the only information supported uniformly in Chromium.
1095 gfx::Rect caret(text_input_caret_);
1096 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1097 return caret;
1100 bool PepperPluginInstanceImpl::HandleInputEvent(
1101 const blink::WebInputEvent& event,
1102 WebCursorInfo* cursor_info) {
1103 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1105 if (!render_frame_)
1106 return false;
1107 if (WebInputEvent::isMouseEventType(event.type)) {
1108 render_frame_->PepperDidReceiveMouseEvent(this);
1111 // Don't dispatch input events to crashed plugins.
1112 if (module()->is_crashed())
1113 return false;
1115 // Don't send reserved system key events to plugins.
1116 if (IsReservedSystemInputEvent(event))
1117 return false;
1119 // Keep a reference on the stack. See NOTE above.
1120 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1122 bool rv = false;
1123 if (LoadInputEventInterface()) {
1124 PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
1125 if (!event_class)
1126 return false;
1128 if ((filtered_input_event_mask_ & event_class) ||
1129 (input_event_mask_ & event_class)) {
1130 // Actually send the event.
1131 std::vector<ppapi::InputEventData> events;
1132 CreateInputEventData(event, &events);
1134 // Allow the user gesture to be pending after the plugin handles the
1135 // event. This allows out-of-process plugins to respond to the user
1136 // gesture after processing has finished here.
1137 if (WebUserGestureIndicator::isProcessingUserGesture()) {
1138 pending_user_gesture_ =
1139 ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
1140 pending_user_gesture_token_ =
1141 WebUserGestureIndicator::currentUserGestureToken();
1142 pending_user_gesture_token_.setOutOfProcess();
1145 const ui::LatencyInfo* current_event_latency_info = NULL;
1146 if (render_frame_->GetRenderWidget()) {
1147 current_event_latency_info =
1148 render_frame_->GetRenderWidget()->current_event_latency_info();
1151 // Each input event may generate more than one PP_InputEvent.
1152 for (size_t i = 0; i < events.size(); i++) {
1153 if (is_tracking_latency_) {
1154 InitLatencyInfo(&events[i].latency_info,
1155 current_event_latency_info,
1156 event.type,
1157 last_input_number_++);
1159 if (filtered_input_event_mask_ & event_class)
1160 events[i].is_filtered = true;
1161 else
1162 rv = true; // Unfiltered events are assumed to be handled.
1163 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1164 new PPB_InputEvent_Shared(
1165 ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1167 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1168 pp_instance(), event_resource->pp_resource()));
1173 if (cursor_)
1174 *cursor_info = *cursor_;
1175 return rv;
1178 void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1179 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1180 ppapi::proxy::HostDispatcher* dispatcher =
1181 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1182 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1183 // The dispatcher should always be valid, and MessageChannel should never
1184 // send an 'object' var over PPP_Messaging.
1185 NOTREACHED();
1186 return;
1188 dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1189 ppapi::API_ID_PPP_MESSAGING,
1190 pp_instance(),
1191 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1192 pp_instance())));
1195 bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1196 ScopedPPVar* result) {
1197 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
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 false;
1206 ppapi::proxy::ReceiveSerializedVarReturnValue msg_reply;
1207 bool was_handled = false;
1208 dispatcher->Send(new PpapiMsg_PPPMessageHandler_HandleBlockingMessage(
1209 ppapi::API_ID_PPP_MESSAGING,
1210 pp_instance(),
1211 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1212 pp_instance()),
1213 &msg_reply,
1214 &was_handled));
1215 *result = ScopedPPVar(ScopedPPVar::PassRef(), msg_reply.Return(dispatcher));
1216 TRACE_EVENT0("ppapi",
1217 "PepperPluginInstanceImpl::HandleBlockingMessage return.");
1218 return was_handled;
1221 PP_Var PepperPluginInstanceImpl::GetInstanceObject() {
1222 // Keep a reference on the stack. See NOTE above.
1223 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1225 // If the plugin supports the private instance interface, try to retrieve its
1226 // instance object.
1227 if (LoadPrivateInterface())
1228 return plugin_private_interface_->GetInstanceObject(pp_instance());
1229 return PP_MakeUndefined();
1232 void PepperPluginInstanceImpl::ViewChanged(
1233 const gfx::Rect& position,
1234 const gfx::Rect& clip,
1235 const std::vector<gfx::Rect>& cut_outs_rects) {
1236 // WebKit can give weird (x,y) positions for empty clip rects (since the
1237 // position technically doesn't matter). But we want to make these
1238 // consistent since this is given to the plugin, so force everything to 0
1239 // in the "everything is clipped" case.
1240 gfx::Rect new_clip;
1241 if (!clip.IsEmpty())
1242 new_clip = clip;
1244 cut_outs_rects_ = cut_outs_rects;
1246 view_data_.rect = PP_FromGfxRect(position);
1247 view_data_.clip_rect = PP_FromGfxRect(clip);
1248 view_data_.device_scale = container_->deviceScaleFactor();
1249 view_data_.css_scale =
1250 container_->pageZoomFactor() * container_->pageScaleFactor();
1252 gfx::Size scroll_offset =
1253 container_->element().document().frame()->scrollOffset();
1254 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1255 scroll_offset.height());
1257 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1258 WebElement element = container_->element();
1259 WebDocument document = element.document();
1260 bool is_fullscreen_element = (element == document.fullScreenElement());
1261 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1262 render_frame()->GetRenderWidget()->is_fullscreen() &&
1263 is_fullscreen_element) {
1264 // Entered fullscreen. Only possible via SetFullscreen().
1265 view_data_.is_fullscreen = true;
1266 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1267 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1268 // so desired_fullscreen_state might be out-of-date.
1269 desired_fullscreen_state_ = false;
1270 view_data_.is_fullscreen = false;
1272 // This operation will cause the plugin to re-layout which will send more
1273 // DidChangeView updates. Schedule an asynchronous update and suppress
1274 // notifications until that completes to avoid sending intermediate sizes
1275 // to the plugins.
1276 ScheduleAsyncDidChangeView();
1278 // Reset the size attributes that we hacked to fill in the screen and
1279 // retrigger ViewChanged. Make sure we don't forward duplicates of
1280 // this view to the plugin.
1281 ResetSizeAttributesAfterFullscreen();
1282 return;
1286 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
1288 SendDidChangeView();
1291 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1292 if (has_webkit_focus_ == has_focus)
1293 return;
1295 bool old_plugin_focus = PluginHasFocus();
1296 has_webkit_focus_ = has_focus;
1297 if (PluginHasFocus() != old_plugin_focus)
1298 SendFocusChangeNotification();
1301 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1302 if (has_content_area_focus_ == has_focus)
1303 return;
1305 bool old_plugin_focus = PluginHasFocus();
1306 has_content_area_focus_ = has_focus;
1307 if (PluginHasFocus() != old_plugin_focus)
1308 SendFocusChangeNotification();
1311 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1312 if (is_visible == view_data_.is_page_visible)
1313 return; // Nothing to do.
1314 view_data_.is_page_visible = is_visible;
1316 // If the initial DidChangeView notification hasn't been sent to the plugin,
1317 // let it pass the visibility state for us, instead of sending a notification
1318 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1319 // hasn't been called for the first time. In that case, most of the fields in
1320 // |view_data_| haven't been properly initialized.
1321 if (sent_initial_did_change_view_)
1322 SendDidChangeView();
1325 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1326 if (bound_graphics_2d_platform_)
1327 bound_graphics_2d_platform_->ViewInitiatedPaint();
1328 else if (bound_graphics_3d_.get())
1329 bound_graphics_3d_->ViewInitiatedPaint();
1330 else if (bound_compositor_)
1331 bound_compositor_->ViewInitiatedPaint();
1334 void PepperPluginInstanceImpl::ViewFlushedPaint() {
1335 // Keep a reference on the stack. See NOTE above.
1336 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1337 if (bound_graphics_2d_platform_)
1338 bound_graphics_2d_platform_->ViewFlushedPaint();
1339 else if (bound_graphics_3d_.get())
1340 bound_graphics_3d_->ViewFlushedPaint();
1341 else if (bound_compositor_)
1342 bound_compositor_->ViewFlushedPaint();
1345 void PepperPluginInstanceImpl::SetSelectedText(
1346 const base::string16& selected_text) {
1347 selected_text_ = selected_text;
1350 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1351 link_under_cursor_ = base::UTF8ToUTF16(url);
1354 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1355 text_input_type_ = type;
1356 render_frame_->PepperTextInputTypeChanged(this);
1359 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1360 message_channel_->PostMessageToJavaScript(message);
1363 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1364 PP_Instance instance,
1365 void* user_data,
1366 const PPP_MessageHandler_0_1* handler,
1367 PP_Resource message_loop) {
1368 // Not supported in-process.
1369 NOTIMPLEMENTED();
1370 return PP_ERROR_FAILED;
1373 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1374 // Not supported in-process.
1375 NOTIMPLEMENTED();
1378 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1379 // Keep a reference on the stack. See NOTE above.
1380 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1381 if (!LoadSelectionInterface())
1382 return selected_text_;
1384 PP_Var rv = plugin_selection_interface_->GetSelectedText(pp_instance(),
1385 PP_FromBool(html));
1386 StringVar* string = StringVar::FromPPVar(rv);
1387 base::string16 selection;
1388 if (string)
1389 selection = base::UTF8ToUTF16(string->value());
1390 // Release the ref the plugin transfered to us.
1391 HostGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1392 return selection;
1395 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1396 const gfx::Point& point) {
1397 // Keep a reference on the stack. See NOTE above.
1398 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1399 if (!LoadPdfInterface()) {
1400 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1401 // return |link_under_cursor_| here because this is only ever called with
1402 // the current mouse coordinates.
1403 return link_under_cursor_;
1406 PP_Point p;
1407 p.x = point.x();
1408 p.y = point.y();
1409 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1410 // If the plugin returns undefined for this function it has switched to
1411 // providing us with the link under the cursor eagerly.
1412 if (rv.type == PP_VARTYPE_UNDEFINED)
1413 return link_under_cursor_;
1414 StringVar* string = StringVar::FromPPVar(rv);
1415 base::string16 link;
1416 if (string)
1417 link = base::UTF8ToUTF16(string->value());
1418 // Release the ref the plugin transfered to us.
1419 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1420 return link;
1423 void PepperPluginInstanceImpl::RequestSurroundingText(
1424 size_t desired_number_of_characters) {
1425 // Keep a reference on the stack. See NOTE above.
1426 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1427 if (!LoadTextInputInterface())
1428 return;
1429 plugin_textinput_interface_->RequestSurroundingText(
1430 pp_instance(), desired_number_of_characters);
1433 void PepperPluginInstanceImpl::Zoom(double factor, bool text_only) {
1434 // Keep a reference on the stack. See NOTE above.
1435 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1436 if (!LoadZoomInterface())
1437 return;
1438 plugin_zoom_interface_->Zoom(pp_instance(), factor, PP_FromBool(text_only));
1441 bool PepperPluginInstanceImpl::StartFind(const base::string16& search_text,
1442 bool case_sensitive,
1443 int identifier) {
1444 // Keep a reference on the stack. See NOTE above.
1445 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1446 if (!LoadFindInterface())
1447 return false;
1448 find_identifier_ = identifier;
1449 return PP_ToBool(
1450 plugin_find_interface_->StartFind(pp_instance(),
1451 base::UTF16ToUTF8(search_text).c_str(),
1452 PP_FromBool(case_sensitive)));
1455 void PepperPluginInstanceImpl::SelectFindResult(bool forward) {
1456 // Keep a reference on the stack. See NOTE above.
1457 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1458 if (LoadFindInterface())
1459 plugin_find_interface_->SelectFindResult(pp_instance(),
1460 PP_FromBool(forward));
1463 void PepperPluginInstanceImpl::StopFind() {
1464 // Keep a reference on the stack. See NOTE above.
1465 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1466 if (!LoadFindInterface())
1467 return;
1468 find_identifier_ = -1;
1469 plugin_find_interface_->StopFind(pp_instance());
1472 bool PepperPluginInstanceImpl::LoadFindInterface() {
1473 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1474 return false;
1475 if (!plugin_find_interface_) {
1476 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1477 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1480 return !!plugin_find_interface_;
1483 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1484 if (!checked_for_plugin_input_event_interface_) {
1485 checked_for_plugin_input_event_interface_ = true;
1486 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1487 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1489 return !!plugin_input_event_interface_;
1492 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1493 if (!plugin_mouse_lock_interface_) {
1494 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1495 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1498 return !!plugin_mouse_lock_interface_;
1501 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1502 if (!checked_for_plugin_pdf_interface_) {
1503 checked_for_plugin_pdf_interface_ = true;
1504 plugin_pdf_interface_ = static_cast<const PPP_Pdf_1*>(
1505 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1508 return !!plugin_pdf_interface_;
1511 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1512 // Only check for the interface if the plugin has dev permission.
1513 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1514 return false;
1515 if (!plugin_print_interface_) {
1516 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1517 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1519 return !!plugin_print_interface_;
1522 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1523 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1524 // call GetInstanceObject. This is necessary to ensure that the properties
1525 // the trusted plugin exposes (readyState and lastError) work properly. Note
1526 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1527 // so it's correct to never look up PPP_InstancePrivate for them.
1529 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1530 // to the "real" module.
1531 scoped_refptr<PluginModule> module =
1532 original_module_.get() ? original_module_ : module_;
1533 // Only check for the interface if the plugin has private permission.
1534 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1535 return false;
1536 if (!plugin_private_interface_) {
1537 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1538 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1541 return !!plugin_private_interface_;
1544 bool PepperPluginInstanceImpl::LoadSelectionInterface() {
1545 if (!plugin_selection_interface_) {
1546 plugin_selection_interface_ = static_cast<const PPP_Selection_Dev*>(
1547 module_->GetPluginInterface(PPP_SELECTION_DEV_INTERFACE));
1549 return !!plugin_selection_interface_;
1552 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1553 if (!plugin_textinput_interface_) {
1554 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1555 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1558 return !!plugin_textinput_interface_;
1561 bool PepperPluginInstanceImpl::LoadZoomInterface() {
1562 if (!plugin_zoom_interface_) {
1563 plugin_zoom_interface_ = static_cast<const PPP_Zoom_Dev*>(
1564 module_->GetPluginInterface(PPP_ZOOM_DEV_INTERFACE));
1567 return !!plugin_zoom_interface_;
1570 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1571 if (!bound_graphics_2d_platform_ || !texture_layer_.get()) {
1572 // Currently the transform is only applied for Graphics2D.
1573 return;
1575 // Set the UV coordinates of the texture based on the size of the Graphics2D
1576 // context. By default a texture gets scaled to the size of the layer. But
1577 // if the size of the Graphics2D context doesn't match the size of the plugin
1578 // then it will be incorrectly stretched. This also affects how the plugin
1579 // is painted when it is being resized. If the Graphics2D contents are
1580 // stretched when a plugin is resized while waiting for a new frame from the
1581 // plugin to be rendered, then flickering behavior occurs as in
1582 // crbug.com/353453.
1583 gfx::SizeF graphics_2d_size_in_dip =
1584 gfx::ScaleSize(bound_graphics_2d_platform_->Size(),
1585 bound_graphics_2d_platform_->GetScale());
1586 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1587 view_data_.rect.size.height);
1589 texture_layer_->SetUV(
1590 gfx::PointF(0.0f, 0.0f),
1591 gfx::PointF(
1592 plugin_size_in_dip.width() / graphics_2d_size_in_dip.width(),
1593 plugin_size_in_dip.height() / graphics_2d_size_in_dip.height()));
1596 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1597 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1600 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1601 // Keep a reference on the stack. RenderViewImpl::PepperFocusChanged may
1602 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1603 // drop its reference, usually the last one. This is similar to possible
1604 // plugin behavior described at the NOTE above Delete().
1605 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1607 if (!render_frame_)
1608 return;
1610 bool has_focus = PluginHasFocus();
1611 render_frame_->render_view()->PepperFocusChanged(this, has_focus);
1613 // instance_interface_ may have been cleared in Delete() if the
1614 // PepperWebPluginImpl is destroyed.
1615 if (instance_interface_)
1616 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1619 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1620 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1621 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1622 container_->requestTouchEventType(
1623 raw_touch
1624 ? blink::WebPluginContainer::TouchEventRequestTypeRaw
1625 : blink::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1628 bool PepperPluginInstanceImpl::IsAcceptingWheelEvents() const {
1629 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1630 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1633 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1634 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1635 return; // Already scheduled.
1636 base::MessageLoop::current()->PostTask(
1637 FROM_HERE,
1638 base::Bind(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1639 view_change_weak_ptr_factory_.GetWeakPtr()));
1642 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1643 // The bound callback that owns the weak pointer is still valid until after
1644 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1645 // invalidate them here.
1646 // NOTE: If we ever want to have more than one pending callback, it should
1647 // use a different factory, or we should have a different strategy here.
1648 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1649 SendDidChangeView();
1652 void PepperPluginInstanceImpl::SendDidChangeView() {
1653 // Don't send DidChangeView to crashed plugins.
1654 if (module()->is_crashed())
1655 return;
1657 if (view_change_weak_ptr_factory_.HasWeakPtrs() ||
1658 (sent_initial_did_change_view_ &&
1659 last_sent_view_data_.Equals(view_data_)))
1660 return; // Nothing to update.
1662 sent_initial_did_change_view_ = true;
1663 last_sent_view_data_ = view_data_;
1664 ScopedPPResource resource(
1665 ScopedPPResource::PassRef(),
1666 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data_))
1667 ->GetReference());
1669 UpdateLayerTransform();
1671 // It's possible that Delete() has been called but the renderer hasn't
1672 // released its reference to this object yet.
1673 if (instance_interface_) {
1674 instance_interface_->DidChangeView(
1675 pp_instance(), resource, &view_data_.rect, &view_data_.clip_rect);
1679 void PepperPluginInstanceImpl::ReportGeometry() {
1680 // If this call was delayed, we may have transitioned back to fullscreen in
1681 // the mean time, so only report the geometry if we are actually in normal
1682 // mode.
1683 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1684 container_->reportGeometry();
1687 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1688 PP_PrintOutputFormat_Dev* format) {
1689 // Keep a reference on the stack. See NOTE above.
1690 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1691 if (!LoadPrintInterface())
1692 return false;
1693 uint32_t supported_formats =
1694 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1695 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1696 *format = PP_PRINTOUTPUTFORMAT_PDF;
1697 return true;
1699 return false;
1702 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1703 PP_PrintOutputFormat_Dev format;
1704 return GetPreferredPrintOutputFormat(&format);
1707 bool PepperPluginInstanceImpl::IsPrintScalingDisabled() {
1708 DCHECK(plugin_print_interface_);
1709 if (!plugin_print_interface_)
1710 return false;
1711 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1714 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1715 // Keep a reference on the stack. See NOTE above.
1716 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1717 PP_PrintOutputFormat_Dev format;
1718 if (!GetPreferredPrintOutputFormat(&format)) {
1719 // PrintBegin should not have been called since SupportsPrintInterface
1720 // would have returned false;
1721 NOTREACHED();
1722 return 0;
1724 int num_pages = 0;
1725 PP_PrintSettings_Dev print_settings;
1726 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1727 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1728 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1729 print_settings.dpi = print_params.printerDPI;
1730 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1731 print_settings.grayscale = PP_FALSE;
1732 print_settings.print_scaling_option =
1733 static_cast<PP_PrintScalingOption_Dev>(print_params.printScalingOption);
1734 print_settings.format = format;
1735 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1736 if (!num_pages)
1737 return 0;
1738 current_print_settings_ = print_settings;
1739 canvas_.clear();
1740 ranges_.clear();
1741 return num_pages;
1744 bool PepperPluginInstanceImpl::PrintPage(int page_number,
1745 blink::WebCanvas* canvas) {
1746 #if defined(ENABLE_FULL_PRINTING)
1747 DCHECK(plugin_print_interface_);
1748 PP_PrintPageNumberRange_Dev page_range;
1749 page_range.first_page_number = page_range.last_page_number = page_number;
1750 // The canvas only has a metafile on it for print preview.
1751 bool save_for_later =
1752 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1753 #if defined(OS_MACOSX) || \
1754 (defined(OS_WIN) && !defined(WIN_PDF_METAFILE_FOR_PRINTING))
1755 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1756 #endif
1757 if (save_for_later) {
1758 ranges_.push_back(page_range);
1759 canvas_ = skia::SharePtr(canvas);
1760 return true;
1761 } else {
1762 return PrintPageHelper(&page_range, 1, canvas);
1764 #else // defined(ENABLED_PRINTING)
1765 return false;
1766 #endif
1769 bool PepperPluginInstanceImpl::PrintPageHelper(
1770 PP_PrintPageNumberRange_Dev* page_ranges,
1771 int num_ranges,
1772 blink::WebCanvas* canvas) {
1773 // Keep a reference on the stack. See NOTE above.
1774 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1775 DCHECK(plugin_print_interface_);
1776 if (!plugin_print_interface_)
1777 return false;
1778 PP_Resource print_output = plugin_print_interface_->PrintPages(
1779 pp_instance(), page_ranges, num_ranges);
1780 if (!print_output)
1781 return false;
1783 bool ret = false;
1785 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1786 ret = PrintPDFOutput(print_output, canvas);
1788 // Now we need to release the print output resource.
1789 PluginModule::GetCore()->ReleaseResource(print_output);
1791 return ret;
1794 void PepperPluginInstanceImpl::PrintEnd() {
1795 // Keep a reference on the stack. See NOTE above.
1796 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1797 if (!ranges_.empty())
1798 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1799 canvas_.clear();
1800 ranges_.clear();
1802 DCHECK(plugin_print_interface_);
1803 if (plugin_print_interface_)
1804 plugin_print_interface_->End(pp_instance());
1806 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1807 #if defined(OS_MACOSX)
1808 last_printed_page_ = NULL;
1809 #endif // defined(OS_MACOSX)
1812 bool PepperPluginInstanceImpl::CanRotateView() {
1813 if (!LoadPdfInterface())
1814 return false;
1816 return true;
1819 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
1820 if (!LoadPdfInterface())
1821 return;
1822 PP_PrivatePageTransformType transform_type =
1823 type == WebPlugin::RotationType90Clockwise
1824 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
1825 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1826 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1827 // NOTE: plugin instance may have been deleted.
1830 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
1831 return fullscreen_container_ != NULL;
1834 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
1835 return desired_fullscreen_state_;
1838 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
1839 // Keep a reference on the stack. See NOTE above.
1840 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1842 // Check whether we are trying to switch to the state we're already going
1843 // to (i.e. if we're already switching to fullscreen but the fullscreen
1844 // container isn't ready yet, don't do anything more).
1845 if (fullscreen == IsFullscreenOrPending())
1846 return false;
1848 if (!render_frame_)
1849 return false;
1850 if (fullscreen && !render_frame_->render_view()
1851 ->renderer_preferences()
1852 .plugin_fullscreen_allowed)
1853 return false;
1855 // Check whether we are trying to switch while the state is in transition.
1856 // The 2nd request gets dropped while messing up the internal state, so
1857 // disallow this.
1858 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1859 return false;
1861 if (fullscreen && !IsProcessingUserGesture())
1862 return false;
1864 VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1865 desired_fullscreen_state_ = fullscreen;
1867 if (fullscreen) {
1868 // Create the user gesture in case we're processing one that's pending.
1869 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1870 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1871 // so we will tweak plugin's attributes to support the expected behavior.
1872 KeepSizeAttributesBeforeFullscreen();
1873 SetSizeAttributesForFullscreen();
1874 container_->element().requestFullScreen();
1875 } else {
1876 container_->element().document().cancelFullScreen();
1878 return true;
1881 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
1882 bool flash_fullscreen) {
1883 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1885 if (flash_fullscreen == flash_fullscreen_) {
1886 // Manually clear callback when fullscreen fails with mouselock pending.
1887 if (!flash_fullscreen && is_mouselock_pending)
1888 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1889 return;
1892 UpdateLayer(false);
1894 bool old_plugin_focus = PluginHasFocus();
1895 flash_fullscreen_ = flash_fullscreen;
1896 if (is_mouselock_pending && !IsMouseLocked()) {
1897 if (!IsProcessingUserGesture() &&
1898 !module_->permissions().HasPermission(
1899 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1900 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1901 } else {
1902 // Open a user gesture here so the Webkit user gesture checks will succeed
1903 // for out-of-process plugins.
1904 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1905 if (!LockMouse())
1906 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1910 if (PluginHasFocus() != old_plugin_focus)
1911 SendFocusChangeNotification();
1914 bool PepperPluginInstanceImpl::IsViewAccelerated() {
1915 if (!container_)
1916 return false;
1918 WebDocument document = container_->element().document();
1919 WebLocalFrame* frame = document.frame();
1920 if (!frame)
1921 return false;
1922 WebView* view = frame->view();
1923 if (!view)
1924 return false;
1926 return view->isAcceleratedCompositingActive();
1929 bool PepperPluginInstanceImpl::PrintPDFOutput(PP_Resource print_output,
1930 blink::WebCanvas* canvas) {
1931 #if defined(ENABLE_FULL_PRINTING)
1932 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1933 if (enter.failed())
1934 return false;
1936 BufferAutoMapper mapper(enter.object());
1937 if (!mapper.data() || !mapper.size()) {
1938 NOTREACHED();
1939 return false;
1941 #if defined(OS_WIN)
1942 // For Windows, we need the PDF DLL to render the output PDF to a DC.
1943 HMODULE pdf_module = GetModuleHandle(L"pdf.dll");
1944 if (!pdf_module)
1945 return false;
1946 RenderPDFPageToDCProc render_proc = reinterpret_cast<RenderPDFPageToDCProc>(
1947 GetProcAddress(pdf_module, "RenderPDFPageToDC"));
1948 if (!render_proc)
1949 return false;
1950 #endif // defined(OS_WIN)
1952 bool ret = false;
1953 #if defined(OS_POSIX) && !defined(OS_ANDROID)
1954 // On Linux we just set the final bits in the native metafile
1955 // (NativeMetafile and PreviewMetafile must have compatible formats,
1956 // i.e. both PDF for this to work).
1957 printing::Metafile* metafile =
1958 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1959 DCHECK(metafile != NULL);
1960 if (metafile)
1961 ret = metafile->InitFromData(mapper.data(), mapper.size());
1962 #elif defined(OS_WIN)
1963 printing::Metafile* metafile =
1964 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1965 if (metafile) {
1966 // We only have a metafile when doing print preview, so we just want to
1967 // pass the PDF off to preview.
1968 ret = metafile->InitFromData(mapper.data(), mapper.size());
1969 } else {
1970 // On Windows, we now need to render the PDF to the DC that backs the
1971 // supplied canvas.
1972 HDC dc = skia::BeginPlatformPaint(canvas);
1973 DrawEmptyRectangle(dc);
1974 gfx::Size size_in_pixels;
1975 size_in_pixels.set_width(
1976 printing::ConvertUnit(current_print_settings_.printable_area.size.width,
1977 static_cast<int>(printing::kPointsPerInch),
1978 current_print_settings_.dpi));
1979 size_in_pixels.set_height(printing::ConvertUnit(
1980 current_print_settings_.printable_area.size.height,
1981 static_cast<int>(printing::kPointsPerInch),
1982 current_print_settings_.dpi));
1983 // We need to scale down DC to fit an entire page into DC available area.
1984 // First, we'll try to use default scaling based on the 72dpi that is
1985 // used in webkit for printing.
1986 // If default scaling is not enough to fit the entire PDF without
1987 // Current metafile is based on screen DC and have current screen size.
1988 // Writing outside of those boundaries will result in the cut-off output.
1989 // On metafiles (this is the case here), scaling down will still record
1990 // original coordinates and we'll be able to print in full resolution.
1991 // Before playback we'll need to counter the scaling up that will happen
1992 // in the browser (printed_document_win.cc).
1993 double dynamic_scale = gfx::CalculatePageScale(
1994 dc, size_in_pixels.width(), size_in_pixels.height());
1995 double page_scale = static_cast<double>(printing::kPointsPerInch) /
1996 static_cast<double>(current_print_settings_.dpi);
1998 if (dynamic_scale < page_scale) {
1999 page_scale = dynamic_scale;
2000 printing::MetafileSkiaWrapper::SetCustomScaleOnCanvas(*canvas,
2001 page_scale);
2004 gfx::ScaleDC(dc, page_scale);
2006 ret = render_proc(static_cast<unsigned char*>(mapper.data()),
2007 mapper.size(),
2010 current_print_settings_.dpi,
2011 current_print_settings_.dpi,
2014 size_in_pixels.width(),
2015 size_in_pixels.height(),
2016 true,
2017 false,
2018 true,
2019 true,
2020 true);
2021 skia::EndPlatformPaint(canvas);
2023 #endif // defined(OS_WIN)
2025 return ret;
2026 #else // defined(ENABLE_FULL_PRINTING)
2027 return false;
2028 #endif
2031 void PepperPluginInstanceImpl::UpdateLayer(bool device_changed) {
2032 if (!container_)
2033 return;
2035 gpu::Mailbox mailbox;
2036 uint32 sync_point = 0;
2037 if (bound_graphics_3d_.get()) {
2038 bound_graphics_3d_->GetBackingMailbox(&mailbox, &sync_point);
2039 DCHECK_EQ(mailbox.IsZero(), sync_point == 0);
2041 bool want_3d_layer = !mailbox.IsZero();
2042 bool want_2d_layer = !!bound_graphics_2d_platform_;
2043 bool want_texture_layer = want_3d_layer || want_2d_layer;
2044 bool want_compositor_layer = !!bound_compositor_;
2046 if (!device_changed && (want_texture_layer == !!texture_layer_.get()) &&
2047 (want_3d_layer == layer_is_hardware_) &&
2048 (want_compositor_layer == !!compositor_layer_.get()) &&
2049 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
2050 UpdateLayerTransform();
2051 return;
2054 if (texture_layer_.get() || compositor_layer_.get()) {
2055 if (!layer_bound_to_fullscreen_)
2056 container_->setWebLayer(NULL);
2057 else if (fullscreen_container_)
2058 fullscreen_container_->SetLayer(NULL);
2059 web_layer_.reset();
2060 texture_layer_ = NULL;
2061 compositor_layer_ = NULL;
2064 if (want_texture_layer) {
2065 bool opaque = false;
2066 if (want_3d_layer) {
2067 DCHECK(bound_graphics_3d_.get());
2068 texture_layer_ = cc::TextureLayer::CreateForMailbox(NULL);
2069 opaque = bound_graphics_3d_->IsOpaque();
2070 texture_layer_->SetTextureMailboxWithoutReleaseCallback(
2071 cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point));
2072 } else {
2073 DCHECK(bound_graphics_2d_platform_);
2074 texture_layer_ = cc::TextureLayer::CreateForMailbox(this);
2075 bound_graphics_2d_platform_->AttachedToNewLayer();
2076 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2077 texture_layer_->SetFlipped(false);
2080 // Ignore transparency in fullscreen, since that's what Flash always
2081 // wants to do, and that lets it not recreate a context if
2082 // wmode=transparent was specified.
2083 opaque = opaque || fullscreen_container_;
2084 texture_layer_->SetContentsOpaque(opaque);
2085 web_layer_.reset(new cc_blink::WebLayerImpl(texture_layer_));
2086 } else if (want_compositor_layer) {
2087 compositor_layer_ = bound_compositor_->layer();
2088 web_layer_.reset(new cc_blink::WebLayerImpl(compositor_layer_));
2091 if (web_layer_) {
2092 if (fullscreen_container_) {
2093 fullscreen_container_->SetLayer(web_layer_.get());
2094 } else {
2095 container_->setWebLayer(web_layer_.get());
2099 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2100 layer_is_hardware_ = want_3d_layer;
2101 UpdateLayerTransform();
2104 bool PepperPluginInstanceImpl::PrepareTextureMailbox(
2105 cc::TextureMailbox* mailbox,
2106 scoped_ptr<cc::SingleReleaseCallback>* release_callback,
2107 bool use_shared_memory) {
2108 if (!bound_graphics_2d_platform_)
2109 return false;
2110 return bound_graphics_2d_platform_->PrepareTextureMailbox(mailbox,
2111 release_callback);
2114 void PepperPluginInstanceImpl::OnDestruct() { render_frame_ = NULL; }
2116 void PepperPluginInstanceImpl::AddLatencyInfo(
2117 const std::vector<ui::LatencyInfo>& latency_info) {
2118 if (render_frame_ && render_frame_->GetRenderWidget()) {
2119 RenderWidgetCompositor* compositor =
2120 render_frame_->GetRenderWidget()->compositor();
2121 if (compositor) {
2122 for (size_t i = 0; i < latency_info.size(); i++) {
2123 scoped_ptr<cc::SwapPromise> swap_promise(
2124 new cc::LatencyInfoSwapPromise(latency_info[i]));
2125 compositor->QueueSwapPromise(swap_promise.Pass());
2131 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2132 DCHECK(live_plugin_objects_.find(plugin_object) ==
2133 live_plugin_objects_.end());
2134 live_plugin_objects_.insert(plugin_object);
2137 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2138 // Don't actually verify that the object is in the set since during module
2139 // deletion we'll be in the process of freeing them.
2140 live_plugin_objects_.erase(plugin_object);
2143 bool PepperPluginInstanceImpl::IsProcessingUserGesture() {
2144 PP_TimeTicks now = ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
2145 // Give a lot of slack so tests won't be flaky.
2146 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
2147 return pending_user_gesture_token_.hasGestures() &&
2148 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
2151 WebUserGestureToken PepperPluginInstanceImpl::CurrentUserGestureToken() {
2152 if (!IsProcessingUserGesture())
2153 pending_user_gesture_token_ = WebUserGestureToken();
2154 return pending_user_gesture_token_;
2157 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2158 if (TrackedCallback::IsPending(lock_mouse_callback_))
2159 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2162 void PepperPluginInstanceImpl::OnMouseLockLost() {
2163 if (LoadMouseLockInterface())
2164 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2167 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2168 const blink::WebMouseEvent& event) {
2169 // |cursor_info| is ignored since it is hidden when the mouse is locked.
2170 blink::WebCursorInfo cursor_info;
2171 HandleInputEvent(event, &cursor_info);
2174 void PepperPluginInstanceImpl::SimulateInputEvent(
2175 const InputEventData& input_event) {
2176 WebView* web_view = container()->element().document().frame()->view();
2177 if (!web_view) {
2178 NOTREACHED();
2179 return;
2182 bool handled = SimulateIMEEvent(input_event);
2183 if (handled)
2184 return;
2186 std::vector<linked_ptr<WebInputEvent> > events =
2187 CreateSimulatedWebInputEvents(
2188 input_event,
2189 view_data_.rect.point.x + view_data_.rect.size.width / 2,
2190 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2191 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
2192 it != events.end();
2193 ++it) {
2194 web_view->handleInputEvent(*it->get());
2198 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2199 const InputEventData& input_event) {
2200 switch (input_event.event_type) {
2201 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2202 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2203 SimulateImeSetCompositionEvent(input_event);
2204 break;
2205 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2206 DCHECK(input_event.character_text.empty());
2207 SimulateImeSetCompositionEvent(input_event);
2208 break;
2209 case PP_INPUTEVENT_TYPE_IME_TEXT:
2210 if (!render_frame_)
2211 return false;
2212 render_frame_->SimulateImeConfirmComposition(
2213 base::UTF8ToUTF16(input_event.character_text), gfx::Range());
2214 break;
2215 default:
2216 return false;
2218 return true;
2221 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2222 const InputEventData& input_event) {
2223 if (!render_frame_)
2224 return;
2226 std::vector<size_t> offsets;
2227 offsets.push_back(input_event.composition_selection_start);
2228 offsets.push_back(input_event.composition_selection_end);
2229 offsets.insert(offsets.end(),
2230 input_event.composition_segment_offsets.begin(),
2231 input_event.composition_segment_offsets.end());
2233 base::string16 utf16_text =
2234 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2236 std::vector<blink::WebCompositionUnderline> underlines;
2237 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2238 blink::WebCompositionUnderline underline;
2239 underline.startOffset = offsets[i];
2240 underline.endOffset = offsets[i + 1];
2241 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2242 underline.thick = true;
2243 underlines.push_back(underline);
2246 render_frame_->SimulateImeSetComposition(
2247 utf16_text, underlines, offsets[0], offsets[1]);
2250 ContentDecryptorDelegate*
2251 PepperPluginInstanceImpl::GetContentDecryptorDelegate() {
2252 if (content_decryptor_delegate_)
2253 return content_decryptor_delegate_.get();
2255 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
2256 static_cast<const PPP_ContentDecryptor_Private*>(
2257 module_->GetPluginInterface(PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
2258 if (!plugin_decryption_interface)
2259 return NULL;
2261 content_decryptor_delegate_.reset(
2262 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
2263 return content_decryptor_delegate_.get();
2266 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2267 PP_Resource device) {
2268 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2269 // The Graphics3D instance can't be destroyed until we call
2270 // UpdateLayer().
2271 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2272 if (bound_graphics_3d_.get()) {
2273 bound_graphics_3d_->BindToInstance(false);
2274 bound_graphics_3d_ = NULL;
2276 if (bound_graphics_2d_platform_) {
2277 bound_graphics_2d_platform_->BindToInstance(NULL);
2278 bound_graphics_2d_platform_ = NULL;
2280 if (bound_compositor_) {
2281 bound_compositor_->BindToInstance(NULL);
2282 bound_compositor_ = NULL;
2285 // Special-case clearing the current device.
2286 if (!device) {
2287 UpdateLayer(true);
2288 InvalidateRect(gfx::Rect());
2289 return PP_TRUE;
2292 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2293 // to/from fullscreen with PPB_Fullscreen.
2294 if ((fullscreen_container_ && !flash_fullscreen_) ||
2295 desired_fullscreen_state_ != view_data_.is_fullscreen)
2296 return PP_FALSE;
2298 const ppapi::host::PpapiHost* ppapi_host =
2299 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2300 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2301 PepperGraphics2DHost* graphics_2d = NULL;
2302 PepperCompositorHost* compositor = NULL;
2303 if (host) {
2304 if (host->IsGraphics2DHost()) {
2305 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2306 } else if (host->IsCompositorHost()) {
2307 compositor = static_cast<PepperCompositorHost*>(host);
2308 } else {
2309 DLOG(ERROR) <<
2310 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2314 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2315 PPB_Graphics3D_Impl* graphics_3d =
2316 enter_3d.succeeded()
2317 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2318 : NULL;
2320 if (compositor) {
2321 if (compositor->BindToInstance(this)) {
2322 bound_compositor_ = compositor;
2323 UpdateLayer(true);
2324 return PP_TRUE;
2326 } else if (graphics_2d) {
2327 if (graphics_2d->BindToInstance(this)) {
2328 bound_graphics_2d_platform_ = graphics_2d;
2329 UpdateLayer(true);
2330 return PP_TRUE;
2332 } else if (graphics_3d) {
2333 // Make sure graphics can only be bound to the instance it is
2334 // associated with.
2335 if (graphics_3d->pp_instance() == pp_instance() &&
2336 graphics_3d->BindToInstance(true)) {
2337 bound_graphics_3d_ = graphics_3d;
2338 UpdateLayer(true);
2339 return PP_TRUE;
2343 // The instance cannot be bound or the device is not a valid resource type.
2344 return PP_FALSE;
2347 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2348 return PP_FromBool(full_frame());
2351 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2352 return &view_data_;
2355 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2356 return PP_FromBool(flash_fullscreen_);
2359 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2360 if (!container_)
2361 return PP_MakeUndefined();
2363 WebLocalFrame* frame = container_->element().document().frame();
2364 if (!frame)
2365 return PP_MakeUndefined();
2367 return NPObjectToPPVar(this, frame->windowObject());
2370 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2371 if (!container_)
2372 return PP_MakeUndefined();
2373 return NPObjectToPPVar(this, container_->scriptableObjectForElement());
2376 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2377 PP_Var script,
2378 PP_Var* exception) {
2379 // Executing the script may remove the plugin from the DOM, so we need to keep
2380 // a reference to ourselves so that we can still process the result after the
2381 // WebBindings::evaluate() below.
2382 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2383 TryCatch try_catch(exception);
2384 if (try_catch.has_exception())
2385 return PP_MakeUndefined();
2387 // Convert the script into an inconvenient NPString object.
2388 StringVar* script_string = StringVar::FromPPVar(script);
2389 if (!script_string) {
2390 try_catch.SetException("Script param to ExecuteScript must be a string.");
2391 return PP_MakeUndefined();
2393 NPString np_script;
2394 np_script.UTF8Characters = script_string->value().c_str();
2395 np_script.UTF8Length = script_string->value().length();
2397 // Get the current frame to pass to the evaluate function.
2398 WebLocalFrame* frame = NULL;
2399 if (container_)
2400 frame = container_->element().document().frame();
2401 if (!frame || !frame->windowObject()) {
2402 try_catch.SetException("No context in which to execute script.");
2403 return PP_MakeUndefined();
2406 NPVariant result;
2407 bool ok = false;
2408 if (IsProcessingUserGesture()) {
2409 blink::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2410 ok =
2411 WebBindings::evaluate(NULL, frame->windowObject(), &np_script, &result);
2412 } else {
2413 ok =
2414 WebBindings::evaluate(NULL, frame->windowObject(), &np_script, &result);
2416 if (!ok) {
2417 // TryCatch doesn't catch the exceptions properly. Since this is only for
2418 // a trusted API, just set to a general exception message.
2419 try_catch.SetException("Exception caught");
2420 WebBindings::releaseVariantValue(&result);
2421 return PP_MakeUndefined();
2424 PP_Var ret = NPVariantToPPVar(this, &result);
2425 WebBindings::releaseVariantValue(&result);
2426 return ret;
2429 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2430 PP_Instance instance) {
2431 RenderThreadImpl* thread = RenderThreadImpl::current();
2432 return thread->GetAudioHardwareConfig()->GetOutputSampleRate();
2435 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2436 PP_Instance instance) {
2437 RenderThreadImpl* thread = RenderThreadImpl::current();
2438 return thread->GetAudioHardwareConfig()->GetOutputBufferSize();
2441 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2442 if (!render_frame_)
2443 return PP_MakeUndefined();
2444 return StringVar::StringToPPVar(
2445 render_frame_->render_view()->webkit_preferences().default_encoding);
2448 // These PPB_ContentDecryptor_Private calls are responses to
2449 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2450 // Therefore, |content_decryptor_delegate_| must have been initialized when
2451 // the following methods are called.
2452 void PepperPluginInstanceImpl::PromiseResolved(PP_Instance instance,
2453 uint32 promise_id) {
2454 content_decryptor_delegate_->OnPromiseResolved(promise_id);
2457 void PepperPluginInstanceImpl::PromiseResolvedWithSession(
2458 PP_Instance instance,
2459 uint32 promise_id,
2460 PP_Var web_session_id_var) {
2461 content_decryptor_delegate_->OnPromiseResolvedWithSession(promise_id,
2462 web_session_id_var);
2465 void PepperPluginInstanceImpl::PromiseRejected(
2466 PP_Instance instance,
2467 uint32 promise_id,
2468 PP_CdmExceptionCode exception_code,
2469 uint32 system_code,
2470 PP_Var error_description_var) {
2471 content_decryptor_delegate_->OnPromiseRejected(
2472 promise_id, exception_code, system_code, error_description_var);
2475 void PepperPluginInstanceImpl::SessionMessage(PP_Instance instance,
2476 PP_Var web_session_id_var,
2477 PP_Var message_var,
2478 PP_Var destination_url_var) {
2479 content_decryptor_delegate_->OnSessionMessage(
2480 web_session_id_var, message_var, destination_url_var);
2483 void PepperPluginInstanceImpl::SessionReady(PP_Instance instance,
2484 PP_Var web_session_id_var) {
2485 content_decryptor_delegate_->OnSessionReady(web_session_id_var);
2488 void PepperPluginInstanceImpl::SessionClosed(PP_Instance instance,
2489 PP_Var web_session_id_var) {
2490 content_decryptor_delegate_->OnSessionClosed(web_session_id_var);
2493 void PepperPluginInstanceImpl::SessionError(PP_Instance instance,
2494 PP_Var web_session_id_var,
2495 PP_CdmExceptionCode exception_code,
2496 uint32 system_code,
2497 PP_Var error_description_var) {
2498 content_decryptor_delegate_->OnSessionError(
2499 web_session_id_var, exception_code, system_code, error_description_var);
2502 void PepperPluginInstanceImpl::DeliverBlock(
2503 PP_Instance instance,
2504 PP_Resource decrypted_block,
2505 const PP_DecryptedBlockInfo* block_info) {
2506 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2509 void PepperPluginInstanceImpl::DecoderInitializeDone(
2510 PP_Instance instance,
2511 PP_DecryptorStreamType decoder_type,
2512 uint32_t request_id,
2513 PP_Bool success) {
2514 content_decryptor_delegate_->DecoderInitializeDone(
2515 decoder_type, request_id, success);
2518 void PepperPluginInstanceImpl::DecoderDeinitializeDone(
2519 PP_Instance instance,
2520 PP_DecryptorStreamType decoder_type,
2521 uint32_t request_id) {
2522 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2523 request_id);
2526 void PepperPluginInstanceImpl::DecoderResetDone(
2527 PP_Instance instance,
2528 PP_DecryptorStreamType decoder_type,
2529 uint32_t request_id) {
2530 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2533 void PepperPluginInstanceImpl::DeliverFrame(
2534 PP_Instance instance,
2535 PP_Resource decrypted_frame,
2536 const PP_DecryptedFrameInfo* frame_info) {
2537 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2540 void PepperPluginInstanceImpl::DeliverSamples(
2541 PP_Instance instance,
2542 PP_Resource audio_frames,
2543 const PP_DecryptedSampleInfo* sample_info) {
2544 content_decryptor_delegate_->DeliverSamples(audio_frames, sample_info);
2547 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2548 PP_Instance instance) {
2549 if (!LoadFindInterface())
2550 return;
2551 bool is_main_frame =
2552 render_frame_ &&
2553 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2554 if (!is_main_frame)
2555 return;
2556 render_frame_->render_view()->set_plugin_find_handler(this);
2559 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2560 PP_Instance instance,
2561 int32_t total,
2562 PP_Bool final_result) {
2563 DCHECK_NE(find_identifier_, -1);
2564 if (render_frame_) {
2565 render_frame_->reportFindInPageMatchCount(
2566 find_identifier_, total, PP_ToBool(final_result));
2570 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2571 int32_t index) {
2572 DCHECK_NE(find_identifier_, -1);
2573 if (render_frame_) {
2574 render_frame_->reportFindInPageSelection(
2575 find_identifier_, index + 1, blink::WebRect());
2579 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2580 const PP_Rect* tickmarks,
2581 uint32_t count) {
2582 if (!render_frame_ || !render_frame_->GetWebFrame())
2583 return;
2585 blink::WebVector<blink::WebRect> tickmarks_converted(
2586 static_cast<size_t>(count));
2587 for (uint32 i = 0; i < count; ++i) {
2588 tickmarks_converted[i] = blink::WebRect(tickmarks[i].point.x,
2589 tickmarks[i].point.y,
2590 tickmarks[i].size.width,
2591 tickmarks[i].size.height);
2594 blink::WebFrame* frame = render_frame_->GetWebFrame();
2595 frame->setTickmarks(tickmarks_converted);
2598 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2599 return PP_FromBool(view_data_.is_fullscreen);
2602 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2603 PP_Bool fullscreen) {
2604 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2607 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2608 PP_Size* size) {
2609 blink::WebScreenInfo info = render_frame()->GetRenderWidget()->screenInfo();
2610 *size = PP_MakeSize(info.rect.width, info.rect.height);
2611 return PP_TRUE;
2614 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2615 PP_Instance instance,
2616 ppapi::SingletonResourceID id) {
2617 // Flash APIs and some others aren't implemented in-process.
2618 switch (id) {
2619 case ppapi::BROKER_SINGLETON_ID:
2620 case ppapi::BROWSER_FONT_SINGLETON_ID:
2621 case ppapi::FILE_MAPPING_SINGLETON_ID:
2622 case ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2623 case ppapi::FLASH_FILE_SINGLETON_ID:
2624 case ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2625 case ppapi::FLASH_SINGLETON_ID:
2626 case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID:
2627 case ppapi::NETWORK_PROXY_SINGLETON_ID:
2628 case ppapi::PDF_SINGLETON_ID:
2629 case ppapi::TRUETYPE_FONT_SINGLETON_ID:
2630 NOTIMPLEMENTED();
2631 return NULL;
2632 case ppapi::GAMEPAD_SINGLETON_ID:
2633 return gamepad_impl_.get();
2634 case ppapi::UMA_SINGLETON_ID: {
2635 if (!uma_private_impl_.get()) {
2636 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
2637 if (host_impl->in_process_router()) {
2638 uma_private_impl_ = new ppapi::proxy::UMAPrivateResource(
2639 host_impl->in_process_router()->GetPluginConnection(instance),
2640 instance);
2643 return uma_private_impl_.get();
2647 NOTREACHED();
2648 return NULL;
2651 int32_t PepperPluginInstanceImpl::RequestInputEvents(PP_Instance instance,
2652 uint32_t event_classes) {
2653 input_event_mask_ |= event_classes;
2654 filtered_input_event_mask_ &= ~(event_classes);
2655 RequestInputEventsHelper(event_classes);
2656 return ValidateRequestInputEvents(false, event_classes);
2659 int32_t PepperPluginInstanceImpl::RequestFilteringInputEvents(
2660 PP_Instance instance,
2661 uint32_t event_classes) {
2662 filtered_input_event_mask_ |= event_classes;
2663 input_event_mask_ &= ~(event_classes);
2664 RequestInputEventsHelper(event_classes);
2665 return ValidateRequestInputEvents(true, event_classes);
2668 void PepperPluginInstanceImpl::ClearInputEventRequest(PP_Instance instance,
2669 uint32_t event_classes) {
2670 input_event_mask_ &= ~(event_classes);
2671 filtered_input_event_mask_ &= ~(event_classes);
2672 RequestInputEventsHelper(event_classes);
2675 void PepperPluginInstanceImpl::StartTrackingLatency(PP_Instance instance) {
2676 if (module_->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
2677 is_tracking_latency_ = true;
2680 void PepperPluginInstanceImpl::ZoomChanged(PP_Instance instance,
2681 double factor) {
2682 // We only want to tell the page to change its zoom if the whole page is the
2683 // plugin. If we're in an iframe, then don't do anything.
2684 if (!IsFullPagePlugin())
2685 return;
2686 container()->zoomLevelChanged(content::ZoomFactorToZoomLevel(factor));
2689 void PepperPluginInstanceImpl::ZoomLimitsChanged(PP_Instance instance,
2690 double minimum_factor,
2691 double maximum_factor) {
2692 if (!render_frame_)
2693 return;
2694 if (minimum_factor > maximum_factor) {
2695 NOTREACHED();
2696 return;
2698 double minimum_level = ZoomFactorToZoomLevel(minimum_factor);
2699 double maximum_level = ZoomFactorToZoomLevel(maximum_factor);
2700 render_frame_->render_view()->webview()->zoomLimitsChanged(minimum_level,
2701 maximum_level);
2704 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2705 PP_Var message) {
2706 PostMessageToJavaScript(message);
2709 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2710 PP_MouseCursor_Type type,
2711 PP_Resource image,
2712 const PP_Point* hot_spot) {
2713 if (!ValidateSetCursorParams(type, image, hot_spot))
2714 return PP_FALSE;
2716 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2717 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2718 return PP_TRUE;
2721 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2722 if (enter.failed())
2723 return PP_FALSE;
2724 PPB_ImageData_Impl* image_data =
2725 static_cast<PPB_ImageData_Impl*>(enter.object());
2727 ImageDataAutoMapper auto_mapper(image_data);
2728 if (!auto_mapper.is_valid())
2729 return PP_FALSE;
2731 scoped_ptr<WebCursorInfo> custom_cursor(
2732 new WebCursorInfo(WebCursorInfo::TypeCustom));
2733 custom_cursor->hotSpot.x = hot_spot->x;
2734 custom_cursor->hotSpot.y = hot_spot->y;
2736 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2737 // Make a deep copy, so that the cursor remains valid even after the original
2738 // image data gets freed.
2739 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap())) {
2740 return PP_FALSE;
2743 DoSetCursor(custom_cursor.release());
2744 return PP_TRUE;
2747 int32_t PepperPluginInstanceImpl::LockMouse(
2748 PP_Instance instance,
2749 scoped_refptr<TrackedCallback> callback) {
2750 if (TrackedCallback::IsPending(lock_mouse_callback_))
2751 return PP_ERROR_INPROGRESS;
2753 if (IsMouseLocked())
2754 return PP_OK;
2756 if (!CanAccessMainFrame())
2757 return PP_ERROR_NOACCESS;
2759 if (!IsProcessingUserGesture())
2760 return PP_ERROR_NO_USER_GESTURE;
2762 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2763 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2764 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2765 // Open a user gesture here so the Webkit user gesture checks will succeed
2766 // for out-of-process plugins.
2767 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2768 if (!LockMouse())
2769 return PP_ERROR_FAILED;
2772 // Either mouselock succeeded or a Flash fullscreen is pending.
2773 lock_mouse_callback_ = callback;
2774 return PP_OK_COMPLETIONPENDING;
2777 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2778 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2781 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2782 PP_TextInput_Type type) {
2783 if (!render_frame_)
2784 return;
2785 int itype = type;
2786 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2787 itype = ui::TEXT_INPUT_TYPE_NONE;
2788 SetTextInputType(static_cast<ui::TextInputType>(itype));
2791 void PepperPluginInstanceImpl::UpdateCaretPosition(
2792 PP_Instance instance,
2793 const PP_Rect& caret,
2794 const PP_Rect& bounding_box) {
2795 if (!render_frame_)
2796 return;
2797 text_input_caret_ = PP_ToGfxRect(caret);
2798 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2799 text_input_caret_set_ = true;
2800 render_frame_->PepperCaretPositionChanged(this);
2803 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2804 if (render_frame_)
2805 render_frame_->PepperCancelComposition(this);
2808 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2809 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2810 // It can be optimized so that it won't call it back until the information
2811 // is really needed.
2813 // Avoid calling in nested context or else this will reenter the plugin. This
2814 // uses a weak pointer rather than exploiting the fact that this class is
2815 // refcounted because we don't actually want this operation to affect the
2816 // lifetime of the instance.
2817 base::MessageLoop::current()->PostTask(
2818 FROM_HERE,
2819 base::Bind(&PepperPluginInstanceImpl::RequestSurroundingText,
2820 weak_factory_.GetWeakPtr(),
2821 static_cast<size_t>(kExtraCharsForTextInput)));
2824 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2825 const char* text,
2826 uint32_t caret,
2827 uint32_t anchor) {
2828 if (!render_frame_)
2829 return;
2830 surrounding_text_ = text;
2831 selection_caret_ = caret;
2832 selection_anchor_ = anchor;
2833 render_frame_->PepperSelectionChanged(this);
2836 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2837 PP_Instance instance,
2838 PP_Var relative,
2839 PP_URLComponents_Dev* components) {
2840 StringVar* relative_string = StringVar::FromPPVar(relative);
2841 if (!relative_string)
2842 return PP_MakeNull();
2844 WebElement plugin_element = container()->element();
2845 GURL document_url = plugin_element.document().baseURL();
2846 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2847 document_url.Resolve(relative_string->value()), components);
2850 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2851 PP_Var url) {
2852 StringVar* url_string = StringVar::FromPPVar(url);
2853 if (!url_string)
2854 return PP_FALSE;
2856 blink::WebSecurityOrigin security_origin;
2857 if (!SecurityOriginForInstance(instance, &security_origin))
2858 return PP_FALSE;
2860 GURL gurl(url_string->value());
2861 if (!gurl.is_valid())
2862 return PP_FALSE;
2864 return PP_FromBool(security_origin.canRequest(gurl));
2867 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2868 PP_Instance instance,
2869 PP_Instance target) {
2870 blink::WebSecurityOrigin our_origin;
2871 if (!SecurityOriginForInstance(instance, &our_origin))
2872 return PP_FALSE;
2874 blink::WebSecurityOrigin target_origin;
2875 if (!SecurityOriginForInstance(instance, &target_origin))
2876 return PP_FALSE;
2878 return PP_FromBool(our_origin.canAccess(target_origin));
2881 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2882 PP_Instance instance,
2883 PP_URLComponents_Dev* components) {
2884 blink::WebDocument document = container()->element().document();
2885 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2886 components);
2889 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2890 PP_Instance instance,
2891 PP_URLComponents_Dev* components) {
2892 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2895 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2896 PP_Instance instance,
2897 PP_URLComponents_Dev* components) {
2898 blink::WebDocument document = container()->element().document();
2899 if (!full_frame_)
2900 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2901 components);
2902 WebLocalFrame* frame = document.frame();
2903 if (!frame)
2904 return PP_MakeUndefined();
2905 const WebURLRequest& request = frame->dataSource()->originalRequest();
2906 WebString referer = request.httpHeaderField("Referer");
2907 if (referer.isEmpty())
2908 return PP_MakeUndefined();
2909 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(GURL(referer),
2910 components);
2913 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2914 scoped_refptr<PluginModule> module) {
2915 // Save the original module and switch over to the new one now that this
2916 // plugin is using the IPC-based proxy.
2917 original_module_ = module_;
2918 module_ = module;
2920 // For NaCl instances, remember the NaCl plugin instance interface, so we
2921 // can shut it down by calling its DidDestroy in our Delete() method.
2922 original_instance_interface_.reset(instance_interface_.release());
2924 base::Callback<const void*(const char*)> get_plugin_interface_func =
2925 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2926 PPP_Instance_Combined* ppp_instance_combined =
2927 PPP_Instance_Combined::Create(get_plugin_interface_func);
2928 if (!ppp_instance_combined) {
2929 // The proxy must support at least one usable PPP_Instance interface.
2930 // While this could be a failure to implement the interface in the NaCl
2931 // module, it is more likely that the NaCl process has crashed. Either
2932 // way, report that module initialization failed.
2933 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2936 instance_interface_.reset(ppp_instance_combined);
2937 // Clear all PPP interfaces we may have cached.
2938 plugin_find_interface_ = NULL;
2939 plugin_input_event_interface_ = NULL;
2940 checked_for_plugin_input_event_interface_ = false;
2941 plugin_mouse_lock_interface_ = NULL;
2942 plugin_pdf_interface_ = NULL;
2943 checked_for_plugin_pdf_interface_ = false;
2944 plugin_private_interface_ = NULL;
2945 plugin_selection_interface_ = NULL;
2946 plugin_textinput_interface_ = NULL;
2947 plugin_zoom_interface_ = NULL;
2949 // Re-send the DidCreate event via the proxy.
2950 scoped_ptr<const char * []> argn_array(StringVectorToArgArray(argn_));
2951 scoped_ptr<const char * []> argv_array(StringVectorToArgArray(argv_));
2952 if (!instance_interface_->DidCreate(
2953 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2954 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2955 message_channel_->Start();
2957 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2958 // event. This way, SendDidChangeView will send the "current" view
2959 // immediately (before other events like HandleDocumentLoad).
2960 sent_initial_did_change_view_ = false;
2961 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2962 SendDidChangeView();
2964 DCHECK(external_document_load_);
2965 external_document_load_ = false;
2966 if (!external_document_response_.isNull()) {
2967 document_loader_ = NULL;
2968 // Pass the response to the new proxy.
2969 HandleDocumentLoad(external_document_response_);
2970 external_document_response_ = blink::WebURLResponse();
2971 // Replay any document load events we've received to the real loader.
2972 external_document_loader_->ReplayReceivedData(document_loader_);
2973 external_document_loader_.reset(NULL);
2976 return PP_EXTERNAL_PLUGIN_OK;
2979 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2980 DCHECK(module);
2981 return module == module_.get() || module == original_module_.get();
2984 NPP PepperPluginInstanceImpl::instanceNPP() { return npp_.get(); }
2986 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
2987 return HostGlobals::Get()->GetInstance(instance_id);
2990 RenderView* PepperPluginInstanceImpl::GetRenderView() {
2991 return render_frame_ ? render_frame_->render_view() : NULL;
2994 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2995 return container_;
2998 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() const { return isolate_; }
3000 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
3001 return HostGlobals::Get()->GetVarTracker();
3004 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
3006 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
3007 return module_->path();
3010 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
3011 float scale) {
3012 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
3014 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
3015 return 0;
3017 scoped_refptr<PPB_ImageData_Impl> image_data(
3018 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
3019 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
3020 image_skia_rep.pixel_width(),
3021 image_skia_rep.pixel_height(),
3022 false)) {
3023 return 0;
3026 ImageDataAutoMapper mapper(image_data.get());
3027 if (!mapper.is_valid())
3028 return 0;
3030 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
3031 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
3032 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
3033 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
3035 return image_data->GetReference();
3038 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
3039 const base::FilePath& file_path,
3040 ppapi::PpapiPermissions permissions,
3041 const IPC::ChannelHandle& channel_handle,
3042 base::ProcessId plugin_pid,
3043 int plugin_child_id) {
3044 // Create a new module for each instance of the external plugin that is using
3045 // the IPC based out-of-process proxy. We can't use the existing module,
3046 // because it is configured for the in-process plugin, and we must keep it
3047 // that way to allow the page to create other instances.
3048 scoped_refptr<PluginModule> external_plugin_module(
3049 module_->CreateModuleForExternalPluginInstance());
3051 RendererPpapiHostImpl* renderer_ppapi_host =
3052 external_plugin_module->CreateOutOfProcessModule(render_frame_,
3053 file_path,
3054 permissions,
3055 channel_handle,
3056 plugin_pid,
3057 plugin_child_id,
3058 true);
3059 if (!renderer_ppapi_host) {
3060 DLOG(ERROR) << "CreateExternalPluginModule() failed";
3061 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
3064 // Finally, switch the instance to the proxy.
3065 return external_plugin_module->InitAsProxiedExternalPlugin(this);
3068 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3069 always_on_top_ = on_top;
3072 void PepperPluginInstanceImpl::DoSetCursor(WebCursorInfo* cursor) {
3073 cursor_.reset(cursor);
3074 if (fullscreen_container_) {
3075 fullscreen_container_->DidChangeCursor(*cursor);
3076 } else if (render_frame_) {
3077 render_frame_->PepperDidChangeCursor(this, *cursor);
3081 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3082 WebLocalFrame* frame = container()->element().document().frame();
3083 return frame->view()->mainFrame()->document().isPluginDocument();
3086 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3087 bool delay_report) {
3088 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3089 // Keep a reference on the stack. See NOTE above.
3090 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3092 // We check whether we are trying to switch to the state we're already going
3093 // to (i.e. if we're already switching to fullscreen but the fullscreen
3094 // container isn't ready yet, don't do anything more).
3095 if (fullscreen == FlashIsFullscreenOrPending())
3096 return true;
3098 if (!render_frame_)
3099 return false;
3100 if (fullscreen && !render_frame_->render_view()
3101 ->renderer_preferences()
3102 .plugin_fullscreen_allowed)
3103 return false;
3105 // Unbind current 2D or 3D graphics context.
3106 VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3107 if (fullscreen) {
3108 DCHECK(!fullscreen_container_);
3109 fullscreen_container_ =
3110 render_frame_->CreatePepperFullscreenContainer(this);
3111 UpdateLayer(false);
3112 } else {
3113 DCHECK(fullscreen_container_);
3114 fullscreen_container_->Destroy();
3115 fullscreen_container_ = NULL;
3116 UpdateFlashFullscreenState(false);
3117 if (!delay_report) {
3118 ReportGeometry();
3119 } else {
3120 base::MessageLoop::current()->PostTask(
3121 FROM_HERE,
3122 base::Bind(&PepperPluginInstanceImpl::ReportGeometry, this));
3126 return true;
3129 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3130 if (flash_fullscreen_)
3131 return true;
3133 return container_->isRectTopmost(rect);
3136 int32_t PepperPluginInstanceImpl::Navigate(
3137 const ppapi::URLRequestInfoData& request,
3138 const char* target,
3139 bool from_user_action) {
3140 if (!container_)
3141 return PP_ERROR_FAILED;
3143 WebDocument document = container_->element().document();
3144 WebLocalFrame* frame = document.frame();
3145 if (!frame)
3146 return PP_ERROR_FAILED;
3148 ppapi::URLRequestInfoData completed_request = request;
3150 WebURLRequest web_request;
3151 if (!CreateWebURLRequest(
3152 pp_instance_, &completed_request, frame, &web_request)) {
3153 return PP_ERROR_FAILED;
3155 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
3156 web_request.setHasUserGesture(from_user_action);
3158 GURL gurl(web_request.url());
3159 if (gurl.SchemeIs("javascript")) {
3160 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3161 // allowed for security reasons.
3162 WebFrame* target_frame =
3163 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
3164 if (target_frame != frame)
3165 return PP_ERROR_NOACCESS;
3167 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3168 // need that?
3169 WebString result = container_->executeScriptURL(gurl, from_user_action);
3170 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
3173 // Only GETs and POSTs are supported.
3174 if (web_request.httpMethod() != "GET" && web_request.httpMethod() != "POST")
3175 return PP_ERROR_BADARGUMENT;
3177 WebString target_str = WebString::fromUTF8(target);
3178 container_->loadFrameRequest(web_request, target_str, false, NULL);
3179 return PP_OK;
3182 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3183 const base::FilePath& path) {
3184 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3185 PepperFileRefRendererHost* file_ref_host(
3186 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3187 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3188 scoped_ptr<ppapi::host::ResourceHost>(file_ref_host));
3191 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3192 message_channel_->SetReadOnlyProperty(key, value);
3195 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3196 if (!container_)
3197 return false;
3198 blink::WebDocument containing_document = container_->element().document();
3200 if (!containing_document.frame() || !containing_document.frame()->view() ||
3201 !containing_document.frame()->view()->mainFrame()) {
3202 return false;
3204 blink::WebDocument main_document =
3205 containing_document.frame()->view()->mainFrame()->document();
3207 return containing_document.securityOrigin().canAccess(
3208 main_document.securityOrigin());
3211 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3212 WebElement element = container_->element();
3213 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
3214 height_before_fullscreen_ =
3215 element.getAttribute(WebString::fromUTF8(kHeight));
3216 border_before_fullscreen_ =
3217 element.getAttribute(WebString::fromUTF8(kBorder));
3218 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
3221 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3222 if (!render_frame_)
3223 return;
3224 blink::WebScreenInfo info = render_frame_->GetRenderWidget()->screenInfo();
3225 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3226 std::string width = StringPrintf("%d", screen_size_for_fullscreen_.width());
3227 std::string height = StringPrintf("%d", screen_size_for_fullscreen_.height());
3229 WebElement element = container_->element();
3230 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
3231 element.setAttribute(WebString::fromUTF8(kHeight),
3232 WebString::fromUTF8(height));
3233 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
3235 // There should be no style settings that matter in fullscreen mode,
3236 // so just replace them instead of appending.
3237 // NOTE: "position: fixed" and "display: block" reset the plugin and
3238 // using %% settings might not work without them (e.g. if the plugin is a
3239 // child of a container element).
3240 std::string style;
3241 style += StringPrintf("width: %s !important; ", width.c_str());
3242 style += StringPrintf("height: %s !important; ", height.c_str());
3243 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3244 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
3247 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3248 screen_size_for_fullscreen_ = gfx::Size();
3249 WebElement element = container_->element();
3250 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
3251 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
3252 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
3253 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
3256 bool PepperPluginInstanceImpl::IsMouseLocked() {
3257 return GetMouseLockDispatcher()->IsMouseLockedTo(
3258 GetOrCreateLockTargetAdapter());
3261 bool PepperPluginInstanceImpl::LockMouse() {
3262 return GetMouseLockDispatcher()->LockMouse(GetOrCreateLockTargetAdapter());
3265 MouseLockDispatcher::LockTarget*
3266 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3267 if (!lock_target_.get()) {
3268 lock_target_.reset(new PluginInstanceLockTarget(this));
3270 return lock_target_.get();
3273 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3274 if (flash_fullscreen_) {
3275 RenderWidgetFullscreenPepper* container =
3276 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3277 return container->mouse_lock_dispatcher();
3278 } else if (render_frame_) {
3279 return render_frame_->render_view()->mouse_lock_dispatcher();
3281 return NULL;
3284 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3285 if (lock_target_.get()) {
3286 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3287 lock_target_.reset();
3291 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3292 const blink::WebURLResponse& response,
3293 int pending_host_id,
3294 const ppapi::URLResponseInfoData& data) {
3295 if (is_deleted_)
3296 return;
3298 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3300 if (host_impl->in_process_router()) {
3301 // Running in-process, we can just create the resource and call the
3302 // PPP_Instance function directly.
3303 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3304 new ppapi::proxy::URLLoaderResource(
3305 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3306 pp_instance(),
3307 pending_host_id,
3308 data));
3310 PP_Resource loader_pp_resource = loader_resource->GetReference();
3311 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3312 loader_pp_resource))
3313 loader_resource->Close();
3314 // We don't pass a ref into the plugin, if it wants one, it will have taken
3315 // an additional one.
3316 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3317 loader_pp_resource);
3318 } else {
3319 // Running out-of-process. Initiate an IPC call to notify the plugin
3320 // process.
3321 ppapi::proxy::HostDispatcher* dispatcher =
3322 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3323 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3324 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3328 } // namespace content