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.
4
5 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
6
7 #include <utility>
8
9 #include "base/bind.h"
10 #include "base/bit_cast.h"
11 #include "base/callback_helpers.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/strings/utf_offset_string_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/threading/thread_task_runner_handle.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/trace_event.h"
24 #include "build/build_config.h"
25 #include "cc/layers/texture_layer.h"
26 #include "content/common/content_constants_internal.h"
27 #include "content/common/frame_messages.h"
28 #include "content/public/common/content_constants.h"
29 #include "content/public/renderer/content_renderer_client.h"
30 #include "content/renderer/media/audio/audio_device_factory.h"
31 #include "content/renderer/pepper/event_conversion.h"
32 #include "content/renderer/pepper/fullscreen_container.h"
33 #include "content/renderer/pepper/gfx_conversion.h"
34 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
35 #include "content/renderer/pepper/host_globals.h"
36 #include "content/renderer/pepper/message_channel.h"
37 #include "content/renderer/pepper/pepper_audio_controller.h"
38 #include "content/renderer/pepper/pepper_browser_connection.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_try_catch.h"
43 #include "content/renderer/pepper/pepper_url_loader_host.h"
44 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
45 #include "content/renderer/pepper/plugin_module.h"
46 #include "content/renderer/pepper/plugin_object.h"
47 #include "content/renderer/pepper/ppapi_preferences_builder.h"
48 #include "content/renderer/pepper/ppb_buffer_impl.h"
49 #include "content/renderer/pepper/ppb_graphics_3d_impl.h"
50 #include "content/renderer/pepper/ppb_image_data_impl.h"
51 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
52 #include "content/renderer/pepper/url_request_info_util.h"
53 #include "content/renderer/pepper/url_response_info_util.h"
54 #include "content/renderer/render_frame_impl.h"
55 #include "content/renderer/render_thread_impl.h"
56 #include "content/renderer/render_view_impl.h"
57 #include "content/renderer/render_widget.h"
58 #include "content/renderer/render_widget_fullscreen_pepper.h"
59 #include "content/renderer/sad_plugin.h"
60 #include "device/gamepad/public/cpp/gamepads.h"
61 #include "ppapi/c/dev/ppp_text_input_dev.h"
62 #include "ppapi/c/pp_rect.h"
63 #include "ppapi/c/ppb_audio_config.h"
64 #include "ppapi/c/ppb_core.h"
65 #include "ppapi/c/ppb_gamepad.h"
66 #include "ppapi/c/ppp_input_event.h"
67 #include "ppapi/c/ppp_instance.h"
68 #include "ppapi/c/ppp_messaging.h"
69 #include "ppapi/c/ppp_mouse_lock.h"
70 #include "ppapi/c/private/ppb_find_private.h"
71 #include "ppapi/c/private/ppp_find_private.h"
72 #include "ppapi/c/private/ppp_instance_private.h"
73 #include "ppapi/c/private/ppp_pdf.h"
74 #include "ppapi/host/ppapi_host.h"
75 #include "ppapi/proxy/ppapi_messages.h"
76 #include "ppapi/proxy/serialized_var.h"
77 #include "ppapi/proxy/uma_private_resource.h"
78 #include "ppapi/proxy/url_loader_resource.h"
79 #include "ppapi/shared_impl/ppapi_permissions.h"
80 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
81 #include "ppapi/shared_impl/ppb_input_event_shared.h"
82 #include "ppapi/shared_impl/ppb_url_util_shared.h"
83 #include "ppapi/shared_impl/ppb_view_shared.h"
84 #include "ppapi/shared_impl/ppp_instance_combined.h"
85 #include "ppapi/shared_impl/resource.h"
86 #include "ppapi/shared_impl/scoped_pp_resource.h"
87 #include "ppapi/shared_impl/scoped_pp_var.h"
88 #include "ppapi/shared_impl/time_conversion.h"
89 #include "ppapi/shared_impl/url_request_info_data.h"
90 #include "ppapi/shared_impl/var.h"
91 #include "ppapi/thunk/enter.h"
92 #include "ppapi/thunk/ppb_buffer_api.h"
93 #include "printing/buildflags/buildflags.h"
94 #include "skia/ext/platform_canvas.h"
95 #include "third_party/blink/public/common/input/web_input_event.h"
96 #include "third_party/blink/public/common/input/web_keyboard_event.h"
97 #include "third_party/blink/public/common/input/web_mouse_event.h"
98 #include "third_party/blink/public/common/input/web_pointer_event.h"
99 #include "third_party/blink/public/common/input/web_touch_event.h"
100 #include "third_party/blink/public/platform/url_conversion.h"
101 #include "third_party/blink/public/platform/web_coalesced_input_event.h"
102 #include "third_party/blink/public/platform/web_float_rect.h"
103 #include "third_party/blink/public/platform/web_rect.h"
104 #include "third_party/blink/public/platform/web_security_origin.h"
105 #include "third_party/blink/public/platform/web_string.h"
106 #include "third_party/blink/public/platform/web_url.h"
107 #include "third_party/blink/public/platform/web_url_error.h"
108 #include "third_party/blink/public/platform/web_url_request.h"
109 #include "third_party/blink/public/web/web_document.h"
110 #include "third_party/blink/public/web/web_document_loader.h"
111 #include "third_party/blink/public/web/web_frame_widget.h"
112 #include "third_party/blink/public/web/web_ime_text_span.h"
113 #include "third_party/blink/public/web/web_local_frame.h"
114 #include "third_party/blink/public/web/web_plugin_container.h"
115 #include "third_party/blink/public/web/web_plugin_script_forbidden_scope.h"
116 #include "third_party/blink/public/web/web_print_params.h"
117 #include "third_party/blink/public/web/web_print_preset_options.h"
118 #include "third_party/blink/public/web/web_print_scaling_option.h"
119 #include "third_party/blink/public/web/web_script_source.h"
120 #include "third_party/blink/public/web/web_view.h"
121 #include "third_party/khronos/GLES2/gl2.h"
122 #include "ui/base/cursor/cursor_lookup.h"
123 #include "ui/events/blink/blink_event_util.h"
124 #include "ui/events/blink/web_input_event.h"
125 #include "ui/events/keycodes/dom/dom_code.h"
126 #include "ui/gfx/geometry/point.h"
127 #include "ui/gfx/geometry/rect_conversions.h"
128 #include "ui/gfx/image/image_skia.h"
129 #include "ui/gfx/image/image_skia_rep.h"
130 #include "ui/gfx/range/range.h"
131 #include "url/origin.h"
132 #include "v8/include/v8.h"
133
134 #if BUILDFLAG(ENABLE_PRINTING)
135 // nogncheck because dependency on //printing is conditional upon
136 // enable_basic_printing flags.
137 #include "printing/metafile_skia.h" // nogncheck
138 #endif
139
140 #if defined(OS_CHROMEOS)
141 #include "ui/events/keycodes/keyboard_codes_posix.h"
142 #endif
143
144 // Windows defines 'PostMessage', so we have to undef it.
145 #ifdef PostMessage
146 #undef PostMessage
147 #endif
148
149 using base::StringPrintf;
150 using ppapi::InputEventData;
151 using ppapi::PpapiGlobals;
152 using ppapi::PPB_InputEvent_Shared;
153 using ppapi::PPB_View_Shared;
154 using ppapi::PPP_Instance_Combined;
155 using ppapi::Resource;
156 using ppapi::ScopedPPResource;
157 using ppapi::ScopedPPVar;
158 using ppapi::StringVar;
159 using ppapi::TrackedCallback;
160 using ppapi::thunk::EnterResourceNoLock;
161 using ppapi::thunk::PPB_Buffer_API;
162 using ppapi::thunk::PPB_Gamepad_API;
163 using ppapi::thunk::PPB_Graphics2D_API;
164 using ppapi::thunk::PPB_Graphics3D_API;
165 using ppapi::thunk::PPB_ImageData_API;
166 using ppapi::Var;
167 using ppapi::ArrayBufferVar;
168 using ppapi::ViewData;
169 using blink::WebDocument;
170 using blink::WebElement;
171 using blink::WebFrame;
172 using blink::WebInputEvent;
173 using blink::WebLocalFrame;
174 using blink::WebPlugin;
175 using blink::WebPluginContainer;
176 using blink::WebPrintParams;
177 using blink::WebPrintScalingOption;
178 using blink::WebString;
179 using blink::WebURLError;
180 using blink::WebAssociatedURLLoaderClient;
181 using blink::WebURLRequest;
182 using blink::WebURLResponse;
183 using blink::WebView;
184 using blink::WebWidget;
185
186 namespace content {
187
188 namespace {
189
190 #ifndef STATIC_ASSERT_ENUM
191 #define STATIC_ASSERT_ENUM(a, b) \
192 static_assert(static_cast<int>(a) == static_cast<int>(b), \
193 "mismatching enums: " #a)
194 #endif
195
196 // Check PP_TextInput_Type and ui::TextInputType are kept in sync.
197 STATIC_ASSERT_ENUM(ui::TEXT_INPUT_TYPE_NONE, PP_TEXTINPUT_TYPE_NONE);
198 STATIC_ASSERT_ENUM(ui::TEXT_INPUT_TYPE_TEXT, PP_TEXTINPUT_TYPE_TEXT);
199 STATIC_ASSERT_ENUM(ui::TEXT_INPUT_TYPE_PASSWORD, PP_TEXTINPUT_TYPE_PASSWORD);
200 STATIC_ASSERT_ENUM(ui::TEXT_INPUT_TYPE_SEARCH, PP_TEXTINPUT_TYPE_SEARCH);
201 STATIC_ASSERT_ENUM(ui::TEXT_INPUT_TYPE_EMAIL, PP_TEXTINPUT_TYPE_EMAIL);
202 STATIC_ASSERT_ENUM(ui::TEXT_INPUT_TYPE_NUMBER, PP_TEXTINPUT_TYPE_NUMBER);
203 STATIC_ASSERT_ENUM(ui::TEXT_INPUT_TYPE_TELEPHONE, PP_TEXTINPUT_TYPE_TELEPHONE);
204 STATIC_ASSERT_ENUM(ui::TEXT_INPUT_TYPE_URL, PP_TEXTINPUT_TYPE_URL);
205
206 // The default text input type is to regard the plugin always accept text input.
207 // This is for allowing users to use input methods even on completely-IME-
208 // unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
209 // Plugins need to explicitly opt out the text input mode if they know
210 // that they don't accept texts.
211 const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
212
213 // <embed>/<object> attributes.
214 const char kWidth[] = "width";
215 const char kHeight[] = "height";
216 const char kBorder[] = "border"; // According to w3c, deprecated.
217 const char kStyle[] = "style";
218
219 #define STATIC_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
220 static_assert(static_cast<int>(ui::mojom::CursorType::webkit_name) == \
221 static_cast<int>(np_name), \
222 "mismatching enums: " #webkit_name)
223
224 STATIC_ASSERT_MATCHING_ENUM(kPointer, PP_MOUSECURSOR_TYPE_POINTER);
225 STATIC_ASSERT_MATCHING_ENUM(kCross, PP_MOUSECURSOR_TYPE_CROSS);
226 STATIC_ASSERT_MATCHING_ENUM(kHand, PP_MOUSECURSOR_TYPE_HAND);
227 STATIC_ASSERT_MATCHING_ENUM(kIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
228 STATIC_ASSERT_MATCHING_ENUM(kWait, PP_MOUSECURSOR_TYPE_WAIT);
229 STATIC_ASSERT_MATCHING_ENUM(kHelp, PP_MOUSECURSOR_TYPE_HELP);
230 STATIC_ASSERT_MATCHING_ENUM(kEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
231 STATIC_ASSERT_MATCHING_ENUM(kNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
232 STATIC_ASSERT_MATCHING_ENUM(kNorthEastResize,
233 PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
234 STATIC_ASSERT_MATCHING_ENUM(kNorthWestResize,
235 PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
236 STATIC_ASSERT_MATCHING_ENUM(kSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
237 STATIC_ASSERT_MATCHING_ENUM(kSouthEastResize,
238 PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
239 STATIC_ASSERT_MATCHING_ENUM(kSouthWestResize,
240 PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
241 STATIC_ASSERT_MATCHING_ENUM(kWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
242 STATIC_ASSERT_MATCHING_ENUM(kNorthSouthResize,
243 PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
244 STATIC_ASSERT_MATCHING_ENUM(kEastWestResize,
245 PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
246 STATIC_ASSERT_MATCHING_ENUM(kNorthEastSouthWestResize,
247 PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
248 STATIC_ASSERT_MATCHING_ENUM(kNorthWestSouthEastResize,
249 PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
250 STATIC_ASSERT_MATCHING_ENUM(kColumnResize, PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
251 STATIC_ASSERT_MATCHING_ENUM(kRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
252 STATIC_ASSERT_MATCHING_ENUM(kMiddlePanning, PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
253 STATIC_ASSERT_MATCHING_ENUM(kEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
254 STATIC_ASSERT_MATCHING_ENUM(kNorthPanning, PP_MOUSECURSOR_TYPE_NORTHPANNING);
255 STATIC_ASSERT_MATCHING_ENUM(kNorthEastPanning,
256 PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
257 STATIC_ASSERT_MATCHING_ENUM(kNorthWestPanning,
258 PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
259 STATIC_ASSERT_MATCHING_ENUM(kSouthPanning, PP_MOUSECURSOR_TYPE_SOUTHPANNING);
260 STATIC_ASSERT_MATCHING_ENUM(kSouthEastPanning,
261 PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
262 STATIC_ASSERT_MATCHING_ENUM(kSouthWestPanning,
263 PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
264 STATIC_ASSERT_MATCHING_ENUM(kWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
265 STATIC_ASSERT_MATCHING_ENUM(kMove, PP_MOUSECURSOR_TYPE_MOVE);
266 STATIC_ASSERT_MATCHING_ENUM(kVerticalText, PP_MOUSECURSOR_TYPE_VERTICALTEXT);
267 STATIC_ASSERT_MATCHING_ENUM(kCell, PP_MOUSECURSOR_TYPE_CELL);
268 STATIC_ASSERT_MATCHING_ENUM(kContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
269 STATIC_ASSERT_MATCHING_ENUM(kAlias, PP_MOUSECURSOR_TYPE_ALIAS);
270 STATIC_ASSERT_MATCHING_ENUM(kProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
271 STATIC_ASSERT_MATCHING_ENUM(kNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
272 STATIC_ASSERT_MATCHING_ENUM(kCopy, PP_MOUSECURSOR_TYPE_COPY);
273 STATIC_ASSERT_MATCHING_ENUM(kNone, PP_MOUSECURSOR_TYPE_NONE);
274 STATIC_ASSERT_MATCHING_ENUM(kNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
275 STATIC_ASSERT_MATCHING_ENUM(kZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
276 STATIC_ASSERT_MATCHING_ENUM(kZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
277 STATIC_ASSERT_MATCHING_ENUM(kGrab, PP_MOUSECURSOR_TYPE_GRAB);
278 STATIC_ASSERT_MATCHING_ENUM(kGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
279 STATIC_ASSERT_MATCHING_ENUM(kMiddlePanningVertical,
280 PP_MOUSECURSOR_TYPE_MIDDLEPANNINGVERTICAL);
281 STATIC_ASSERT_MATCHING_ENUM(kMiddlePanningHorizontal,
282 PP_MOUSECURSOR_TYPE_MIDDLEPANNINGHORIZONTAL);
283 // Do not assert kCustom == PP_CURSORTYPE_CUSTOM;
284 // PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
285
286 #undef STATIC_ASSERT_MATCHING_ENUM
287
288 STATIC_ASSERT_ENUM(blink::kWebPrintScalingOptionNone,
289 PP_PRINTSCALINGOPTION_NONE);
290 STATIC_ASSERT_ENUM(blink::kWebPrintScalingOptionFitToPrintableArea,
291 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
292 STATIC_ASSERT_ENUM(blink::kWebPrintScalingOptionSourceSize,
293 PP_PRINTSCALINGOPTION_SOURCE_SIZE);
294 STATIC_ASSERT_ENUM(blink::kWebPrintScalingOptionFitToPaper,
295 PP_PRINTSCALINGOPTION_FIT_TO_PAPER);
296
297 #undef STATIC_ASSERT_ENUM
298
299 // Sets |*security_origin| to be the WebKit security origin associated with the
300 // document containing the given plugin instance. On success, returns true. If
301 // the instance is invalid, returns false and |*security_origin| will be
302 // unchanged.
SecurityOriginForInstance(PP_Instance instance_id,blink::WebSecurityOrigin * security_origin)303 bool SecurityOriginForInstance(PP_Instance instance_id,
304 blink::WebSecurityOrigin* security_origin) {
305 PepperPluginInstanceImpl* instance =
306 HostGlobals::Get()->GetInstance(instance_id);
307 if (!instance)
308 return false;
309
310 *security_origin = instance->container()->GetDocument().GetSecurityOrigin();
311 return true;
312 }
313
314 // Convert the given vector to an array of C-strings. The strings in the
315 // returned vector are only guaranteed valid so long as the vector of strings
316 // is not modified.
StringVectorToArgArray(const std::vector<std::string> & vector)317 std::unique_ptr<const char* []> StringVectorToArgArray(
318 const std::vector<std::string>& vector) {
319 auto array = std::make_unique<const char* []>(vector.size());
320 for (size_t i = 0; i < vector.size(); ++i)
321 array[i] = vector[i].c_str();
322 return array;
323 }
324
325 // Returns true if this is a "system reserved" key which should not be sent to
326 // a plugin. Some poorly behaving plugins (like Flash) incorrectly report that
327 // they handle all keys sent to them. This can prevent keystrokes from working
328 // for things like screen brightness and volume control.
IsReservedSystemInputEvent(const blink::WebInputEvent & event)329 bool IsReservedSystemInputEvent(const blink::WebInputEvent& event) {
330 #if defined(OS_CHROMEOS)
331 if (event.GetType() != WebInputEvent::kKeyDown &&
332 event.GetType() != WebInputEvent::kKeyUp)
333 return false;
334 const blink::WebKeyboardEvent& key_event =
335 static_cast<const blink::WebKeyboardEvent&>(event);
336 switch (key_event.windows_key_code) {
337 case ui::VKEY_BRIGHTNESS_DOWN:
338 case ui::VKEY_BRIGHTNESS_UP:
339 case ui::VKEY_KBD_BRIGHTNESS_DOWN:
340 case ui::VKEY_KBD_BRIGHTNESS_UP:
341 case ui::VKEY_VOLUME_MUTE:
342 case ui::VKEY_VOLUME_DOWN:
343 case ui::VKEY_VOLUME_UP:
344 return true;
345 default:
346 return false;
347 }
348 #endif // defined(OS_CHROMEOS)
349 return false;
350 }
351
352 class PluginInstanceLockTarget : public MouseLockDispatcher::LockTarget {
353 public:
PluginInstanceLockTarget(PepperPluginInstanceImpl * plugin)354 explicit PluginInstanceLockTarget(PepperPluginInstanceImpl* plugin)
355 : plugin_(plugin) {}
356
OnLockMouseACK(bool succeeded)357 void OnLockMouseACK(bool succeeded) override {
358 plugin_->OnLockMouseACK(succeeded);
359 }
360
OnMouseLockLost()361 void OnMouseLockLost() override { plugin_->OnMouseLockLost(); }
362
HandleMouseLockedInputEvent(const blink::WebMouseEvent & event)363 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
364 plugin_->HandleMouseLockedInputEvent(event);
365 return true;
366 }
367
368 private:
369 PepperPluginInstanceImpl* plugin_;
370 };
371
PrintPDFOutput(PP_Resource print_output,printing::MetafileSkia * metafile)372 void PrintPDFOutput(PP_Resource print_output,
373 printing::MetafileSkia* metafile) {
374 #if BUILDFLAG(ENABLE_PRINTING)
375 DCHECK(metafile);
376
377 ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
378 if (enter.failed())
379 return;
380
381 BufferAutoMapper mapper(enter.object());
382 if (!mapper.data() || !mapper.size()) {
383 NOTREACHED();
384 return;
385 }
386
387 metafile->InitFromData(mapper);
388 #endif // BUILDFLAG(ENABLE_PRINTING)
389 }
390
391 } // namespace
392
393 // static
Create(RenderFrameImpl * render_frame,PluginModule * module,WebPluginContainer * container,const GURL & plugin_url)394 PepperPluginInstanceImpl* PepperPluginInstanceImpl::Create(
395 RenderFrameImpl* render_frame,
396 PluginModule* module,
397 WebPluginContainer* container,
398 const GURL& plugin_url) {
399 base::RepeatingCallback<const void*(const char*)> get_plugin_interface_func =
400 base::BindRepeating(&PluginModule::GetPluginInterface, module);
401 PPP_Instance_Combined* ppp_instance_combined =
402 PPP_Instance_Combined::Create(std::move(get_plugin_interface_func));
403 if (!ppp_instance_combined)
404 return nullptr;
405
406 return new PepperPluginInstanceImpl(render_frame,
407 module,
408 ppp_instance_combined,
409 container,
410 plugin_url);
411 }
412
413 // static
Get(PP_Instance instance_id)414 PepperPluginInstance* PepperPluginInstance::Get(PP_Instance instance_id) {
415 PepperPluginInstanceImpl* instance =
416 PepperPluginInstanceImpl::GetForTesting(instance_id);
417 if (instance && !instance->is_deleted())
418 return instance;
419 return nullptr;
420 }
421
422 // static
GetForTesting(PP_Instance instance_id)423 PepperPluginInstanceImpl* PepperPluginInstanceImpl::GetForTesting(
424 PP_Instance instance_id) {
425 PepperPluginInstanceImpl* instance =
426 HostGlobals::Get()->GetInstance(instance_id);
427 return instance;
428 }
429
ExternalDocumentLoader()430 PepperPluginInstanceImpl::ExternalDocumentLoader::ExternalDocumentLoader()
431 : finished_loading_(false) {}
432
~ExternalDocumentLoader()433 PepperPluginInstanceImpl::ExternalDocumentLoader::~ExternalDocumentLoader() {}
434
ReplayReceivedData(WebAssociatedURLLoaderClient * document_loader)435 void PepperPluginInstanceImpl::ExternalDocumentLoader::ReplayReceivedData(
436 WebAssociatedURLLoaderClient* document_loader) {
437 for (auto it = data_.begin(); it != data_.end(); ++it) {
438 document_loader->DidReceiveData(it->c_str(), it->length());
439 }
440 if (finished_loading_) {
441 document_loader->DidFinishLoading();
442 } else if (error_.get()) {
443 DCHECK(!finished_loading_);
444 document_loader->DidFail(*error_);
445 }
446 }
447
DidReceiveData(const char * data,int data_length)448 void PepperPluginInstanceImpl::ExternalDocumentLoader::DidReceiveData(
449 const char* data,
450 int data_length) {
451 data_.push_back(std::string(data, data_length));
452 }
453
DidFinishLoading()454 void PepperPluginInstanceImpl::ExternalDocumentLoader::DidFinishLoading() {
455 DCHECK(!finished_loading_);
456
457 if (error_.get())
458 return;
459
460 finished_loading_ = true;
461 }
462
DidFail(const WebURLError & error)463 void PepperPluginInstanceImpl::ExternalDocumentLoader::DidFail(
464 const WebURLError& error) {
465 DCHECK(!error_.get());
466
467 if (finished_loading_)
468 return;
469
470 error_ = std::make_unique<WebURLError>(error);
471 }
472
GamepadImpl()473 PepperPluginInstanceImpl::GamepadImpl::GamepadImpl()
474 : Resource(ppapi::Resource::Untracked()) {}
475
~GamepadImpl()476 PepperPluginInstanceImpl::GamepadImpl::~GamepadImpl() {}
477
AsPPB_Gamepad_API()478 PPB_Gamepad_API* PepperPluginInstanceImpl::GamepadImpl::AsPPB_Gamepad_API() {
479 return this;
480 }
481
Sample(PP_Instance instance,PP_GamepadsSampleData * data)482 void PepperPluginInstanceImpl::GamepadImpl::Sample(
483 PP_Instance instance,
484 PP_GamepadsSampleData* data) {
485 // This gamepad singleton resource method should not be called
486 NOTREACHED();
487 }
488
PepperPluginInstanceImpl(RenderFrameImpl * render_frame,PluginModule * module,ppapi::PPP_Instance_Combined * instance_interface,WebPluginContainer * container,const GURL & plugin_url)489 PepperPluginInstanceImpl::PepperPluginInstanceImpl(
490 RenderFrameImpl* render_frame,
491 PluginModule* module,
492 ppapi::PPP_Instance_Combined* instance_interface,
493 WebPluginContainer* container,
494 const GURL& plugin_url)
495 : RenderFrameObserver(render_frame),
496 render_frame_(render_frame),
497 module_(module),
498 instance_interface_(instance_interface),
499 pp_instance_(0),
500 graphics2d_translation_(0, 0),
501 graphics2d_scale_(1.f),
502 container_(container),
503 layer_bound_to_fullscreen_(false),
504 layer_is_hardware_(false),
505 plugin_url_(plugin_url),
506 document_url_(container ? GURL(container->GetDocument().Url()) : GURL()),
507 is_flash_plugin_(module->name() == kFlashPluginName),
508 has_been_clicked_(false),
509 full_frame_(false),
510 viewport_to_dip_scale_(1.0f),
511 sent_initial_did_change_view_(false),
512 bound_graphics_2d_platform_(nullptr),
513 has_webkit_focus_(false),
514 has_content_area_focus_(false),
515 find_identifier_(-1),
516 plugin_find_interface_(nullptr),
517 plugin_input_event_interface_(nullptr),
518 plugin_mouse_lock_interface_(nullptr),
519 plugin_pdf_interface_(nullptr),
520 plugin_private_interface_(nullptr),
521 plugin_textinput_interface_(nullptr),
522 checked_for_plugin_input_event_interface_(false),
523 checked_for_plugin_pdf_interface_(false),
524 metafile_(nullptr),
525 gamepad_impl_(new GamepadImpl()),
526 uma_private_impl_(nullptr),
527 plugin_print_interface_(nullptr),
528 always_on_top_(false),
529 fullscreen_container_(nullptr),
530 flash_fullscreen_(false),
531 desired_fullscreen_state_(false),
532 message_channel_(nullptr),
533 input_event_mask_(0),
534 filtered_input_event_mask_(0),
535 text_input_type_(kPluginDefaultTextInputType),
536 selection_caret_(0),
537 selection_anchor_(0),
538 document_loader_(nullptr),
539 external_document_load_(false),
540 isolate_(v8::Isolate::GetCurrent()),
541 is_deleted_(false),
542 initialized_(false),
543 created_in_process_instance_(false),
544 audio_controller_(std::make_unique<PepperAudioController>(this)) {
545 pp_instance_ = HostGlobals::Get()->AddInstance(this);
546
547 memset(¤t_print_settings_, 0, sizeof(current_print_settings_));
548 module_->InstanceCreated(this);
549
550 if (render_frame_) { // NULL in tests or if the frame has been destroyed.
551 render_frame_->PepperInstanceCreated(this);
552 view_data_.is_page_visible =
553 !render_frame_->GetLocalRootRenderWidget()->is_hidden();
554
555 // Set the initial focus.
556 SetContentAreaFocus(render_frame_->GetLocalRootRenderWidget()->has_focus());
557
558 if (!module_->IsProxied()) {
559 created_in_process_instance_ = true;
560 PepperBrowserConnection* browser_connection =
561 PepperBrowserConnection::Get(render_frame_);
562 browser_connection->DidCreateInProcessInstance(
563 pp_instance(),
564 render_frame_->GetRoutingID(),
565 document_url_,
566 GetPluginURL());
567 }
568 }
569
570 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
571 resource_creation_ = host_impl->CreateInProcessResourceCreationAPI(this);
572
573 if (GetContentClient()->renderer() && // NULL in unit tests.
574 GetContentClient()->renderer()->IsExternalPepperPlugin(module->name()))
575 external_document_load_ = true;
576 }
577
~PepperPluginInstanceImpl()578 PepperPluginInstanceImpl::~PepperPluginInstanceImpl() {
579 DCHECK(!fullscreen_container_);
580
581 // Notify all the plugin objects of deletion. This will prevent blink from
582 // calling into the plugin any more.
583 //
584 // Swap out the set so we can delete from it (the objects will try to
585 // unregister themselves inside the delete call).
586 PluginObjectSet plugin_object_copy;
587 live_plugin_objects_.swap(plugin_object_copy);
588 for (auto i = plugin_object_copy.begin(); i != plugin_object_copy.end();
589 ++i) {
590 (*i)->InstanceDeleted();
591 }
592
593 if (message_channel_)
594 message_channel_->InstanceDeleted();
595 message_channel_object_.Reset();
596
597 if (TrackedCallback::IsPending(lock_mouse_callback_))
598 lock_mouse_callback_->Abort();
599
600 audio_controller_->OnPepperInstanceDeleted();
601
602 if (render_frame_)
603 render_frame_->PepperInstanceDeleted(this);
604
605 if (created_in_process_instance_) {
606 PepperBrowserConnection* browser_connection =
607 PepperBrowserConnection::Get(render_frame_);
608 browser_connection->DidDeleteInProcessInstance(pp_instance());
609 }
610
611 UnSetAndDeleteLockTargetAdapter();
612 module_->InstanceDeleted(this);
613 // If we switched from the NaCl plugin module, notify it too.
614 if (original_module_.get())
615 original_module_->InstanceDeleted(this);
616
617 // This should be last since some of the above "instance deleted" calls will
618 // want to look up in the global map to get info off of our object.
619 HostGlobals::Get()->InstanceDeleted(pp_instance_);
620
621 if (throttler_)
622 throttler_->RemoveObserver(this);
623 }
624
625 // NOTE: Any of these methods that calls into the plugin needs to take into
626 // account that the plugin may use Var to remove the <embed> from the DOM, which
627 // will make the PepperWebPluginImpl drop its reference, usually the last one.
628 // If a method needs to access a member of the instance after the call has
629 // returned, then it needs to keep its own reference on the stack.
630
GetMessageChannelObject()631 v8::Local<v8::Object> PepperPluginInstanceImpl::GetMessageChannelObject() {
632 return v8::Local<v8::Object>::New(isolate_, message_channel_object_);
633 }
634
MessageChannelDestroyed()635 void PepperPluginInstanceImpl::MessageChannelDestroyed() {
636 message_channel_ = nullptr;
637 message_channel_object_.Reset();
638 }
639
GetMainWorldContext()640 v8::Local<v8::Context> PepperPluginInstanceImpl::GetMainWorldContext() {
641 if (!container_)
642 return v8::Local<v8::Context>();
643
644 WebLocalFrame* frame = container_->GetDocument().GetFrame();
645
646 if (!frame)
647 return v8::Local<v8::Context>();
648
649 v8::Local<v8::Context> context = frame->MainWorldScriptContext();
650 DCHECK(context->GetIsolate() == isolate_);
651 return context;
652 }
653
Delete()654 void PepperPluginInstanceImpl::Delete() {
655 is_deleted_ = true;
656
657 // Keep a reference on the stack. See NOTE above.
658 scoped_refptr<PepperPluginInstanceImpl> ref(this);
659
660 // It is important to destroy the throttler before anything else.
661 // The plugin instance may flush its graphics pipeline during its postmortem
662 // spasm, causing the throttler to engage and obtain new dangling reference
663 // to the plugin container being destroyed.
664 throttler_.reset();
665
666 // Force the MessageChannel to release its "passthrough object" which should
667 // release our last reference to the "InstanceObject" and will probably
668 // destroy it. We want to do this prior to calling DidDestroy in case the
669 // destructor of the instance object tries to use the instance.
670 if (message_channel_)
671 message_channel_->SetPassthroughObject(v8::Local<v8::Object>());
672 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
673 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
674 // since there is little that it can do at this point.
675 if (original_instance_interface_) {
676 base::TimeTicks start = base::TimeTicks::Now();
677 original_instance_interface_->DidDestroy(pp_instance());
678 UMA_HISTOGRAM_CUSTOM_TIMES("NaCl.Perf.ShutdownTime.Total",
679 base::TimeTicks::Now() - start,
680 base::TimeDelta::FromMilliseconds(1),
681 base::TimeDelta::FromSeconds(20),
682 100);
683 } else {
684 instance_interface_->DidDestroy(pp_instance());
685 }
686 // Ensure we don't attempt to call functions on the destroyed instance.
687 original_instance_interface_.reset();
688 instance_interface_.reset();
689
690 if (fullscreen_container_) {
691 fullscreen_container_->Destroy();
692 fullscreen_container_ = nullptr;
693 }
694
695 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
696 // leaks the graphics 2D, it may actually get cleaned up after our
697 // destruction, so we need its pointers to be up to date.
698 BindGraphics(pp_instance(), 0);
699 container_ = nullptr;
700 }
701
is_deleted() const702 bool PepperPluginInstanceImpl::is_deleted() const { return is_deleted_; }
703
Paint(cc::PaintCanvas * canvas,const gfx::Rect & plugin_rect,const gfx::Rect & paint_rect)704 void PepperPluginInstanceImpl::Paint(cc::PaintCanvas* canvas,
705 const gfx::Rect& plugin_rect,
706 const gfx::Rect& paint_rect) {
707 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
708 if (module()->is_crashed()) {
709 // Crashed plugin painting.
710 if (!sad_plugin_image_) { // Lazily initialize bitmap.
711 if (SkBitmap* bitmap =
712 GetContentClient()->renderer()->GetSadPluginBitmap()) {
713 DCHECK(bitmap->isImmutable());
714 sad_plugin_image_ = cc::PaintImage::CreateFromBitmap(*bitmap);
715 }
716 }
717 if (sad_plugin_image_)
718 PaintSadPlugin(canvas, plugin_rect, sad_plugin_image_);
719 return;
720 }
721
722 if (bound_graphics_2d_platform_)
723 bound_graphics_2d_platform_->Paint(canvas, plugin_rect, paint_rect);
724 }
725
InvalidateRect(const gfx::Rect & rect)726 void PepperPluginInstanceImpl::InvalidateRect(const gfx::Rect& rect) {
727 if (fullscreen_container_) {
728 // The fullscreen container uses a composited layer, which we invalidate
729 // directly below via SetNeedsDisplay().
730 } else {
731 if (!container_ || view_data_.rect.size.width == 0 ||
732 view_data_.rect.size.height == 0)
733 return; // Nothing to do.
734 if (rect.IsEmpty())
735 container_->Invalidate();
736 else
737 container_->InvalidateRect(rect);
738 }
739
740 if (texture_layer_) {
741 if (rect.IsEmpty()) {
742 texture_layer_->SetNeedsDisplay();
743 } else {
744 texture_layer_->SetNeedsDisplayRect(rect);
745 }
746 }
747 }
748
CommitTransferableResource(const viz::TransferableResource & resource)749 void PepperPluginInstanceImpl::CommitTransferableResource(
750 const viz::TransferableResource& resource) {
751 if (!committed_texture_.mailbox_holder.mailbox.IsZero() &&
752 !IsTextureInUse(committed_texture_)) {
753 committed_texture_graphics_3d_->ReturnFrontBuffer(
754 committed_texture_.mailbox_holder.mailbox,
755 committed_texture_consumed_sync_token_, false);
756 }
757
758 committed_texture_ = resource;
759 committed_texture_graphics_3d_ = bound_graphics_3d_;
760 committed_texture_consumed_sync_token_ = gpu::SyncToken();
761
762 if (!texture_layer_) {
763 UpdateLayer(true);
764 return;
765 }
766
767 PassCommittedTextureToTextureLayer();
768 texture_layer_->SetNeedsDisplay();
769 }
770
PassCommittedTextureToTextureLayer()771 void PepperPluginInstanceImpl::PassCommittedTextureToTextureLayer() {
772 DCHECK(bound_graphics_3d_);
773
774 if (committed_texture_.mailbox_holder.mailbox.IsZero())
775 return;
776
777 std::unique_ptr<viz::SingleReleaseCallback> callback(
778 viz::SingleReleaseCallback::Create(base::BindOnce(
779 &PepperPluginInstanceImpl::FinishedConsumingCommittedTexture,
780 weak_factory_.GetWeakPtr(), committed_texture_,
781 committed_texture_graphics_3d_)));
782
783 IncrementTextureReferenceCount(committed_texture_);
784 texture_layer_->SetTransferableResource(committed_texture_,
785 std::move(callback));
786 }
787
FinishedConsumingCommittedTexture(const viz::TransferableResource & resource,scoped_refptr<PPB_Graphics3D_Impl> graphics_3d,const gpu::SyncToken & sync_token,bool is_lost)788 void PepperPluginInstanceImpl::FinishedConsumingCommittedTexture(
789 const viz::TransferableResource& resource,
790 scoped_refptr<PPB_Graphics3D_Impl> graphics_3d,
791 const gpu::SyncToken& sync_token,
792 bool is_lost) {
793 bool removed = DecrementTextureReferenceCount(resource);
794 bool is_committed_texture = committed_texture_.mailbox_holder.mailbox ==
795 resource.mailbox_holder.mailbox;
796
797 if (is_committed_texture && !is_lost) {
798 committed_texture_consumed_sync_token_ = sync_token;
799 return;
800 }
801
802 if (removed && !is_committed_texture) {
803 graphics_3d->ReturnFrontBuffer(resource.mailbox_holder.mailbox, sync_token,
804 is_lost);
805 }
806 }
807
InstanceCrashed()808 void PepperPluginInstanceImpl::InstanceCrashed() {
809 // Force free all resources and vars.
810 HostGlobals::Get()->InstanceCrashed(pp_instance());
811
812 // Free any associated graphics.
813 SetFullscreen(false);
814 FlashSetFullscreen(false, false);
815 // Unbind current 2D or 3D graphics context.
816 BindGraphics(pp_instance(), 0);
817 InvalidateRect(gfx::Rect());
818
819 if (render_frame_)
820 render_frame_->PluginCrashed(module_->path(), module_->GetPeerProcessId());
821 UnSetAndDeleteLockTargetAdapter();
822 }
823
Initialize(const std::vector<std::string> & arg_names,const std::vector<std::string> & arg_values,bool full_frame,std::unique_ptr<PluginInstanceThrottlerImpl> throttler)824 bool PepperPluginInstanceImpl::Initialize(
825 const std::vector<std::string>& arg_names,
826 const std::vector<std::string>& arg_values,
827 bool full_frame,
828 std::unique_ptr<PluginInstanceThrottlerImpl> throttler) {
829 DCHECK(!throttler_);
830
831 if (!render_frame_)
832 return false;
833
834 if (throttler) {
835 throttler_ = std::move(throttler);
836 throttler_->AddObserver(this);
837 }
838
839 message_channel_ = MessageChannel::Create(this, &message_channel_object_);
840 DCHECK(message_channel_);
841
842 full_frame_ = full_frame;
843
844 UpdateTouchEventRequest();
845 UpdateWheelEventRequest();
846
847 argn_ = arg_names;
848 argv_ = arg_values;
849 std::unique_ptr<const char* []> argn_array(StringVectorToArgArray(argn_));
850 std::unique_ptr<const char* []> argv_array(StringVectorToArgArray(argv_));
851 auto weak_this = weak_factory_.GetWeakPtr();
852 bool success = PP_ToBool(instance_interface_->DidCreate(
853 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()));
854 if (!weak_this) {
855 // The plugin may do synchronous scripting during "DidCreate", so |this|
856 // may be deleted. In that case, return failure and don't touch any
857 // member variables.
858 return false;
859 }
860 // If this is a plugin that hosts external plugins, we should delay messages
861 // so that the child plugin that's created later will receive all the
862 // messages. (E.g., NaCl trusted plugin starting a child NaCl app.)
863 //
864 // A host for external plugins will call ResetAsProxied later, at which point
865 // we can Start() the MessageChannel.
866 if (success && !module_->renderer_ppapi_host()->IsExternalPluginHost())
867 message_channel_->Start();
868
869 if (success)
870 HandleAccessibilityChange();
871
872 initialized_ = success;
873 return success;
874 }
875
HandleDocumentLoad(const blink::WebURLResponse & response)876 bool PepperPluginInstanceImpl::HandleDocumentLoad(
877 const blink::WebURLResponse& response) {
878 DCHECK(!document_loader_);
879 if (external_document_load_) {
880 // The external proxy isn't available, so save the response and record
881 // document load notifications for later replay.
882 external_document_response_ = response;
883 external_document_loader_ = std::make_unique<ExternalDocumentLoader>();
884 document_loader_ = external_document_loader_.get();
885 return true;
886 }
887
888 if (module()->is_crashed() || !render_frame_) {
889 // Don't create a resource for a crashed plugin.
890 container()->GetDocument().GetFrame()->StopLoading();
891 return false;
892 }
893
894 DCHECK(!document_loader_);
895
896 // Create a loader resource host for this load. Note that we have to set
897 // the document_loader before issuing the in-process
898 // PPP_Instance.HandleDocumentLoad call below, since this may reentrantly
899 // call into the instance and expect it to be valid.
900 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
901 auto loader_host =
902 std::make_unique<PepperURLLoaderHost>(host_impl, true, pp_instance(), 0);
903 // TODO(teravest): Remove set_document_loader() from instance and clean up
904 // this relationship.
905 set_document_loader(loader_host.get());
906 loader_host->DidReceiveResponse(response);
907
908 // This host will be pending until the resource object attaches to it.
909 int pending_host_id = host_impl->GetPpapiHost()->AddPendingResourceHost(
910 std::unique_ptr<ppapi::host::ResourceHost>(std::move(loader_host)));
911 DCHECK(pending_host_id);
912
913 render_frame()
914 ->GetTaskRunner(blink::TaskType::kInternalLoading)
915 ->PostTask(
916 FROM_HERE,
917 base::BindOnce(&PepperPluginInstanceImpl::DidDataFromWebURLResponse,
918 weak_factory_.GetWeakPtr(), response, pending_host_id,
919 DataFromWebURLResponse(response)));
920
921 // If the load was not abandoned, document_loader_ will now be set. It's
922 // possible that the load was canceled by now and document_loader_ was
923 // already nulled out.
924 return true;
925 }
926
SendCompositionEventToPlugin(PP_InputEvent_Type type,const base::string16 & text)927 bool PepperPluginInstanceImpl::SendCompositionEventToPlugin(
928 PP_InputEvent_Type type,
929 const base::string16& text) {
930 std::vector<blink::WebImeTextSpan> empty;
931 return SendCompositionEventWithImeTextSpanInformationToPlugin(
932 type, text, empty, static_cast<int>(text.size()),
933 static_cast<int>(text.size()));
934 }
935
936 bool PepperPluginInstanceImpl::
SendCompositionEventWithImeTextSpanInformationToPlugin(PP_InputEvent_Type type,const base::string16 & text,const std::vector<blink::WebImeTextSpan> & ime_text_spans,int selection_start,int selection_end)937 SendCompositionEventWithImeTextSpanInformationToPlugin(
938 PP_InputEvent_Type type,
939 const base::string16& text,
940 const std::vector<blink::WebImeTextSpan>& ime_text_spans,
941 int selection_start,
942 int selection_end) {
943 // Keep a reference on the stack. See NOTE above.
944 scoped_refptr<PepperPluginInstanceImpl> ref(this);
945
946 if (!LoadInputEventInterface())
947 return false;
948
949 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
950 if (!(filtered_input_event_mask_ & event_class) &&
951 !(input_event_mask_ & event_class))
952 return false;
953
954 ppapi::InputEventData event;
955 event.event_type = type;
956 event.event_time_stamp =
957 ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
958
959 // Convert UTF16 text to UTF8 with offset conversion.
960 std::vector<size_t> utf16_offsets;
961 utf16_offsets.push_back(selection_start);
962 utf16_offsets.push_back(selection_end);
963 for (size_t i = 0; i < ime_text_spans.size(); ++i) {
964 utf16_offsets.push_back(ime_text_spans[i].start_offset);
965 utf16_offsets.push_back(ime_text_spans[i].end_offset);
966 }
967 std::vector<size_t> utf8_offsets(utf16_offsets);
968 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
969
970 // Set the converted selection range.
971 event.composition_selection_start =
972 (utf8_offsets[0] == std::string::npos ? event.character_text.size()
973 : utf8_offsets[0]);
974 event.composition_selection_end =
975 (utf8_offsets[1] == std::string::npos ? event.character_text.size()
976 : utf8_offsets[1]);
977
978 // Set the converted segmentation points.
979 // Be sure to add 0 and size(), and remove duplication or errors.
980 std::set<size_t> offset_set(utf8_offsets.begin() + 2, utf8_offsets.end());
981 offset_set.insert(0);
982 offset_set.insert(event.character_text.size());
983 offset_set.erase(std::string::npos);
984 event.composition_segment_offsets.assign(offset_set.begin(),
985 offset_set.end());
986
987 // Set the composition target.
988 for (size_t i = 0; i < ime_text_spans.size(); ++i) {
989 if (ime_text_spans[i].thickness ==
990 ui::mojom::ImeTextSpanThickness::kThick) {
991 auto it = std::find(event.composition_segment_offsets.begin(),
992 event.composition_segment_offsets.end(),
993 utf8_offsets[2 * i + 2]);
994 if (it != event.composition_segment_offsets.end()) {
995 event.composition_target_segment =
996 it - event.composition_segment_offsets.begin();
997 break;
998 }
999 }
1000 }
1001
1002 // Send the event.
1003 bool handled = false;
1004 if (filtered_input_event_mask_ & event_class)
1005 event.is_filtered = true;
1006 else
1007 handled = true; // Unfiltered events are assumed to be handled.
1008 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1009 new PPB_InputEvent_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), event));
1010 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1011 pp_instance(), event_resource->pp_resource()));
1012 return handled;
1013 }
1014
RequestInputEventsHelper(uint32_t event_classes)1015 void PepperPluginInstanceImpl::RequestInputEventsHelper(
1016 uint32_t event_classes) {
1017 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
1018 UpdateTouchEventRequest();
1019 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
1020 UpdateWheelEventRequest();
1021 }
1022
HandleCompositionStart(const base::string16 & text)1023 bool PepperPluginInstanceImpl::HandleCompositionStart(
1024 const base::string16& text) {
1025 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
1026 text);
1027 }
1028
HandleCompositionUpdate(const base::string16 & text,const std::vector<blink::WebImeTextSpan> & ime_text_spans,int selection_start,int selection_end)1029 bool PepperPluginInstanceImpl::HandleCompositionUpdate(
1030 const base::string16& text,
1031 const std::vector<blink::WebImeTextSpan>& ime_text_spans,
1032 int selection_start,
1033 int selection_end) {
1034 return SendCompositionEventWithImeTextSpanInformationToPlugin(
1035 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE, text, ime_text_spans,
1036 selection_start, selection_end);
1037 }
1038
HandleCompositionEnd(const base::string16 & text)1039 bool PepperPluginInstanceImpl::HandleCompositionEnd(
1040 const base::string16& text) {
1041 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
1042 text);
1043 }
1044
HandleTextInput(const base::string16 & text)1045 bool PepperPluginInstanceImpl::HandleTextInput(const base::string16& text) {
1046 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT, text);
1047 }
1048
GetSurroundingText(base::string16 * text,gfx::Range * range) const1049 void PepperPluginInstanceImpl::GetSurroundingText(base::string16* text,
1050 gfx::Range* range) const {
1051 std::vector<size_t> offsets;
1052 offsets.push_back(selection_anchor_);
1053 offsets.push_back(selection_caret_);
1054 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
1055 range->set_start(offsets[0] == base::string16::npos ? text->size()
1056 : offsets[0]);
1057 range->set_end(offsets[1] == base::string16::npos ? text->size()
1058 : offsets[1]);
1059 }
1060
IsPluginAcceptingCompositionEvents() const1061 bool PepperPluginInstanceImpl::IsPluginAcceptingCompositionEvents() const {
1062 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
1063 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
1064 }
1065
GetCaretBounds() const1066 gfx::Rect PepperPluginInstanceImpl::GetCaretBounds() const {
1067 if (!text_input_caret_info_) {
1068 // If it is never set by the plugin, use the bottom left corner.
1069 gfx::Rect rect(view_data_.rect.point.x,
1070 view_data_.rect.point.y + view_data_.rect.size.height,
1071 0, 0);
1072 ConvertDIPToViewport(&rect);
1073 return rect;
1074 }
1075
1076 // TODO(kinaba) Take CSS transformation into account.
1077 // TODO(kinaba) Take |text_input_caret_info_->caret_bounds| into account. On
1078 // some platforms, an "exclude rectangle" where candidate window must avoid
1079 // the region can be passed to IME. Currently, we pass only the caret
1080 // rectangle because it is the only information supported uniformly in
1081 // Chromium.
1082 gfx::Rect caret = text_input_caret_info_->caret;
1083 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
1084 ConvertDIPToViewport(&caret);
1085 return caret;
1086 }
1087
HandleCoalescedInputEvent(const blink::WebCoalescedInputEvent & event,ui::Cursor * cursor)1088 bool PepperPluginInstanceImpl::HandleCoalescedInputEvent(
1089 const blink::WebCoalescedInputEvent& event,
1090 ui::Cursor* cursor) {
1091 if (blink::WebInputEvent::IsTouchEventType(event.Event().GetType()) &&
1092 ((filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_COALESCED_TOUCH) ||
1093 (input_event_mask_ & PP_INPUTEVENT_CLASS_COALESCED_TOUCH))) {
1094 bool result = false;
1095 for (size_t i = 0; i < event.CoalescedEventSize(); ++i) {
1096 result |= HandleInputEvent(event.CoalescedEvent(i), cursor);
1097 }
1098 return result;
1099 }
1100 return HandleInputEvent(event.Event(), cursor);
1101 }
1102
HandleInputEvent(const blink::WebInputEvent & event,ui::Cursor * cursor)1103 bool PepperPluginInstanceImpl::HandleInputEvent(
1104 const blink::WebInputEvent& event,
1105 ui::Cursor* cursor) {
1106 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleInputEvent");
1107
1108 if (!render_frame_)
1109 return false;
1110
1111 if (!has_been_clicked_ && is_flash_plugin_ &&
1112 event.GetType() == blink::WebInputEvent::kMouseDown &&
1113 (event.GetModifiers() & blink::WebInputEvent::kLeftButtonDown)) {
1114 has_been_clicked_ = true;
1115 }
1116
1117 if (throttler_ && throttler_->ConsumeInputEvent(event))
1118 return true;
1119
1120 if (WebInputEvent::IsMouseEventType(event.GetType())) {
1121 render_frame_->PepperDidReceiveMouseEvent(this);
1122 }
1123
1124 // Don't dispatch input events to crashed plugins.
1125 if (module()->is_crashed())
1126 return false;
1127
1128 // Don't send reserved system key events to plugins.
1129 if (IsReservedSystemInputEvent(event))
1130 return false;
1131
1132 // Keep a reference on the stack. See NOTE above.
1133 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1134
1135 bool rv = false;
1136 if (LoadInputEventInterface()) {
1137 PP_InputEvent_Class event_class = ClassifyInputEvent(event);
1138 if (!event_class)
1139 return false;
1140
1141 if ((filtered_input_event_mask_ & event_class) ||
1142 (input_event_mask_ & event_class)) {
1143 // Actually send the event.
1144 std::vector<ppapi::InputEventData> events;
1145 std::unique_ptr<const WebInputEvent> event_in_dip(
1146 ui::ScaleWebInputEvent(event, viewport_to_dip_scale_));
1147 if (event_in_dip)
1148 CreateInputEventData(*event_in_dip.get(), &last_mouse_position_,
1149 &events);
1150 else
1151 CreateInputEventData(event, &last_mouse_position_, &events);
1152
1153 // Each input event may generate more than one PP_InputEvent.
1154 for (size_t i = 0; i < events.size(); i++) {
1155 if (filtered_input_event_mask_ & event_class)
1156 events[i].is_filtered = true;
1157 else
1158 rv = true; // Unfiltered events are assumed to be handled.
1159 scoped_refptr<PPB_InputEvent_Shared> event_resource(
1160 new PPB_InputEvent_Shared(
1161 ppapi::OBJECT_IS_IMPL, pp_instance(), events[i]));
1162
1163 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
1164 pp_instance(), event_resource->pp_resource()));
1165 }
1166 }
1167 }
1168
1169 if (cursor_)
1170 *cursor = *cursor_;
1171 return rv;
1172 }
1173
HandleMessage(ScopedPPVar message)1174 void PepperPluginInstanceImpl::HandleMessage(ScopedPPVar message) {
1175 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleMessage");
1176 if (is_deleted_)
1177 return;
1178 ppapi::proxy::HostDispatcher* dispatcher =
1179 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
1180 if (!dispatcher || (message.get().type == PP_VARTYPE_OBJECT)) {
1181 // The dispatcher should always be valid, and MessageChannel should never
1182 // send an 'object' var over PPP_Messaging.
1183 NOTREACHED();
1184 return;
1185 }
1186 dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage(
1187 ppapi::API_ID_PPP_MESSAGING,
1188 pp_instance(),
1189 ppapi::proxy::SerializedVarSendInputShmem(dispatcher, message.get(),
1190 pp_instance())));
1191 }
1192
HandleBlockingMessage(ScopedPPVar message,ScopedPPVar * result)1193 bool PepperPluginInstanceImpl::HandleBlockingMessage(ScopedPPVar message,
1194 ScopedPPVar* result) {
1195 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::HandleBlockingMessage");
1196 if (is_deleted_)
1197 return false;
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;
1205 }
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;
1219 }
1220
GetInstanceObject(v8::Isolate * isolate)1221 PP_Var PepperPluginInstanceImpl::GetInstanceObject(v8::Isolate* isolate) {
1222 // Keep a reference on the stack. See NOTE above.
1223 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1224
1225 DCHECK_EQ(isolate, isolate_);
1226
1227 // If the plugin supports the private instance interface, try to retrieve its
1228 // instance object.
1229 if (LoadPrivateInterface())
1230 return plugin_private_interface_->GetInstanceObject(pp_instance());
1231 return PP_MakeUndefined();
1232 }
1233
ViewChanged(const gfx::Rect & window,const gfx::Rect & clip,const gfx::Rect & unobscured)1234 void PepperPluginInstanceImpl::ViewChanged(
1235 const gfx::Rect& window,
1236 const gfx::Rect& clip,
1237 const gfx::Rect& unobscured) {
1238 if (!render_frame_)
1239 return;
1240
1241 // WebKit can give weird (x,y) positions for empty clip rects (since the
1242 // position technically doesn't matter). But we want to make these
1243 // consistent since this is given to the plugin, so force everything to 0
1244 // in the "everything is clipped" case.
1245 gfx::Rect new_clip;
1246 if (!clip.IsEmpty())
1247 new_clip = clip;
1248
1249 unobscured_rect_ = unobscured;
1250
1251 view_data_.rect = PP_FromGfxRect(window);
1252 view_data_.clip_rect = PP_FromGfxRect(new_clip);
1253 view_data_.device_scale = container_->DeviceScaleFactor();
1254 view_data_.css_scale =
1255 container_->PageZoomFactor() * container_->PageScaleFactor();
1256 blink::WebFloatRect windowToViewportScale(0, 0, 1.0f, 0);
1257 render_frame()->GetLocalRootRenderWidget()->ConvertWindowToViewport(
1258 &windowToViewportScale);
1259 viewport_to_dip_scale_ = 1.0f / windowToViewportScale.width;
1260 ConvertRectToDIP(&view_data_.rect);
1261 ConvertRectToDIP(&view_data_.clip_rect);
1262 view_data_.css_scale *= viewport_to_dip_scale_;
1263 view_data_.device_scale /= viewport_to_dip_scale_;
1264
1265 gfx::Size scroll_offset = gfx::ScaleToRoundedSize(
1266 container_->GetDocument().GetFrame()->GetScrollOffset(),
1267 viewport_to_dip_scale_);
1268
1269 view_data_.scroll_offset = PP_MakePoint(scroll_offset.width(),
1270 scroll_offset.height());
1271
1272 // The view size may have changed and we might need to update
1273 // our registration of event listeners.
1274 UpdateTouchEventRequest();
1275 UpdateWheelEventRequest();
1276
1277 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
1278 bool is_fullscreen_element = container_->IsFullscreenElement();
1279 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
1280 render_frame()->GetLocalRootRenderWidget()->is_fullscreen_granted() &&
1281 is_fullscreen_element) {
1282 // Entered fullscreen. Only possible via SetFullscreen().
1283 view_data_.is_fullscreen = true;
1284 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
1285 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
1286 // so desired_fullscreen_state might be out-of-date.
1287 desired_fullscreen_state_ = false;
1288 view_data_.is_fullscreen = false;
1289
1290 // This operation will cause the plugin to re-layout which will send more
1291 // DidChangeView updates. Schedule an asynchronous update and suppress
1292 // notifications until that completes to avoid sending intermediate sizes
1293 // to the plugins.
1294 ScheduleAsyncDidChangeView();
1295
1296 // Reset the size attributes that we hacked to fill in the screen and
1297 // retrigger ViewChanged. Make sure we don't forward duplicates of
1298 // this view to the plugin.
1299 ResetSizeAttributesAfterFullscreen();
1300 return;
1301 }
1302 }
1303
1304 UpdateFlashFullscreenState(fullscreen_container_ != nullptr);
1305
1306 // During plugin initialization, there are often re-layouts. Avoid sending
1307 // intermediate sizes the plugin and throttler.
1308 if (sent_initial_did_change_view_)
1309 SendDidChangeView();
1310 else
1311 ScheduleAsyncDidChangeView();
1312 }
1313
SetWebKitFocus(bool has_focus)1314 void PepperPluginInstanceImpl::SetWebKitFocus(bool has_focus) {
1315 if (has_webkit_focus_ == has_focus)
1316 return;
1317
1318 bool old_plugin_focus = PluginHasFocus();
1319 has_webkit_focus_ = has_focus;
1320 if (PluginHasFocus() != old_plugin_focus)
1321 SendFocusChangeNotification();
1322 }
1323
SetContentAreaFocus(bool has_focus)1324 void PepperPluginInstanceImpl::SetContentAreaFocus(bool has_focus) {
1325 if (has_content_area_focus_ == has_focus)
1326 return;
1327
1328 bool old_plugin_focus = PluginHasFocus();
1329 has_content_area_focus_ = has_focus;
1330 if (PluginHasFocus() != old_plugin_focus)
1331 SendFocusChangeNotification();
1332 }
1333
PageVisibilityChanged(bool is_visible)1334 void PepperPluginInstanceImpl::PageVisibilityChanged(bool is_visible) {
1335 if (is_visible == view_data_.is_page_visible)
1336 return; // Nothing to do.
1337 view_data_.is_page_visible = is_visible;
1338
1339 // If the initial DidChangeView notification hasn't been sent to the plugin,
1340 // let it pass the visibility state for us, instead of sending a notification
1341 // immediately. It is possible that PepperPluginInstanceImpl::ViewChanged()
1342 // hasn't been called for the first time. In that case, most of the fields in
1343 // |view_data_| haven't been properly initialized.
1344 if (sent_initial_did_change_view_)
1345 SendDidChangeView();
1346 }
1347
ViewInitiatedPaint()1348 void PepperPluginInstanceImpl::ViewInitiatedPaint() {
1349 if (bound_graphics_2d_platform_)
1350 bound_graphics_2d_platform_->ViewInitiatedPaint();
1351 else if (bound_graphics_3d_.get())
1352 bound_graphics_3d_->ViewInitiatedPaint();
1353 }
1354
SetSelectedText(const base::string16 & selected_text)1355 void PepperPluginInstanceImpl::SetSelectedText(
1356 const base::string16& selected_text) {
1357 if (!render_frame_)
1358 return;
1359
1360 selected_text_ = selected_text;
1361 gfx::Range range(0, selected_text.length());
1362 render_frame_->SetSelectedText(selected_text, 0, range, true);
1363 }
1364
SetLinkUnderCursor(const std::string & url)1365 void PepperPluginInstanceImpl::SetLinkUnderCursor(const std::string& url) {
1366 link_under_cursor_ = base::UTF8ToUTF16(url);
1367 }
1368
SetTextInputType(ui::TextInputType type)1369 void PepperPluginInstanceImpl::SetTextInputType(ui::TextInputType type) {
1370 if (!render_frame_)
1371 return;
1372
1373 text_input_type_ = type;
1374 render_frame_->PepperTextInputTypeChanged(this);
1375 }
1376
PostMessageToJavaScript(PP_Var message)1377 void PepperPluginInstanceImpl::PostMessageToJavaScript(PP_Var message) {
1378 if (message_channel_)
1379 message_channel_->PostMessageToJavaScript(message);
1380 }
1381
RegisterMessageHandler(PP_Instance instance,void * user_data,const PPP_MessageHandler_0_2 * handler,PP_Resource message_loop)1382 int32_t PepperPluginInstanceImpl::RegisterMessageHandler(
1383 PP_Instance instance,
1384 void* user_data,
1385 const PPP_MessageHandler_0_2* handler,
1386 PP_Resource message_loop) {
1387 // Not supported in-process.
1388 NOTIMPLEMENTED();
1389 return PP_ERROR_FAILED;
1390 }
1391
UnregisterMessageHandler(PP_Instance instance)1392 void PepperPluginInstanceImpl::UnregisterMessageHandler(PP_Instance instance) {
1393 // Not supported in-process.
1394 NOTIMPLEMENTED();
1395 }
1396
GetSelectedText(bool html)1397 base::string16 PepperPluginInstanceImpl::GetSelectedText(bool html) {
1398 return selected_text_;
1399 }
1400
GetLinkAtPosition(const gfx::Point & point)1401 base::string16 PepperPluginInstanceImpl::GetLinkAtPosition(
1402 const gfx::Point& point) {
1403 // Keep a reference on the stack. See NOTE above.
1404 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1405 if (!LoadPdfInterface()) {
1406 // TODO(koz): Change the containing function to GetLinkUnderCursor(). We can
1407 // return |link_under_cursor_| here because this is only ever called with
1408 // the current mouse coordinates.
1409 return link_under_cursor_;
1410 }
1411
1412 PP_Point p;
1413 p.x = point.x();
1414 p.y = point.y();
1415 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1416 // If the plugin returns undefined for this function it has switched to
1417 // providing us with the link under the cursor eagerly.
1418 if (rv.type == PP_VARTYPE_UNDEFINED)
1419 return link_under_cursor_;
1420 StringVar* string = StringVar::FromPPVar(rv);
1421 base::string16 link;
1422 if (string)
1423 link = base::UTF8ToUTF16(string->value());
1424 // Release the ref the plugin transfered to us.
1425 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1426 return link;
1427 }
1428
SetCaretPosition(const gfx::PointF & position)1429 void PepperPluginInstanceImpl::SetCaretPosition(const gfx::PointF& position) {
1430 if (!LoadPdfInterface())
1431 return;
1432
1433 PP_FloatPoint p;
1434 p.x = position.x();
1435 p.y = position.y();
1436 plugin_pdf_interface_->SetCaretPosition(pp_instance(), &p);
1437 }
1438
MoveRangeSelectionExtent(const gfx::PointF & extent)1439 void PepperPluginInstanceImpl::MoveRangeSelectionExtent(
1440 const gfx::PointF& extent) {
1441 if (!LoadPdfInterface())
1442 return;
1443
1444 PP_FloatPoint p;
1445 p.x = extent.x();
1446 p.y = extent.y();
1447 plugin_pdf_interface_->MoveRangeSelectionExtent(pp_instance(), &p);
1448 }
1449
SetSelectionBounds(const gfx::PointF & base,const gfx::PointF & extent)1450 void PepperPluginInstanceImpl::SetSelectionBounds(const gfx::PointF& base,
1451 const gfx::PointF& extent) {
1452 if (!LoadPdfInterface())
1453 return;
1454
1455 PP_FloatPoint p_base;
1456 p_base.x = base.x();
1457 p_base.y = base.y();
1458
1459 PP_FloatPoint p_extent;
1460 p_extent.x = extent.x();
1461 p_extent.y = extent.y();
1462 plugin_pdf_interface_->SetSelectionBounds(pp_instance(), &p_base, &p_extent);
1463 }
1464
CanEditText()1465 bool PepperPluginInstanceImpl::CanEditText() {
1466 if (!LoadPdfInterface())
1467 return false;
1468 // No reference to |this| on the stack. Do not do any more work after this.
1469 // See NOTE above.
1470 return PP_ToBool(plugin_pdf_interface_->CanEditText(pp_instance()));
1471 }
1472
HasEditableText()1473 bool PepperPluginInstanceImpl::HasEditableText() {
1474 if (!LoadPdfInterface())
1475 return false;
1476
1477 // No reference to |this| on the stack. Do not do any more work after this.
1478 // See NOTE above.
1479 return PP_ToBool(plugin_pdf_interface_->HasEditableText(pp_instance()));
1480 }
1481
ReplaceSelection(const std::string & text)1482 void PepperPluginInstanceImpl::ReplaceSelection(const std::string& text) {
1483 if (!LoadPdfInterface())
1484 return;
1485
1486 // No reference to |this| on the stack. Do not do any more work after this.
1487 // See NOTE above.
1488 plugin_pdf_interface_->ReplaceSelection(pp_instance(), text.c_str());
1489 }
1490
SelectAll()1491 void PepperPluginInstanceImpl::SelectAll() {
1492 if (!LoadPdfInterface())
1493 return;
1494
1495 // Keep a reference on the stack. See NOTE above.
1496 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1497
1498 // TODO(https://crbug.com/836074) |kPlatformModifier| should be
1499 // |ui::EF_PLATFORM_ACCELERATOR| (|ui::EF_COMMAND_DOWN| on Mac).
1500 static const ui::EventFlags kPlatformModifier = ui::EF_CONTROL_DOWN;
1501 // Synthesize a ctrl + a key event to send to the plugin and let it sort out
1502 // the event. See also https://crbug.com/739529.
1503 ui::KeyEvent char_event(L'A', ui::VKEY_A, ui::DomCode::NONE,
1504 kPlatformModifier);
1505
1506 // Also synthesize a key up event to look more like a real key press.
1507 // Otherwise the plugin will not do all the required work to keep the renderer
1508 // in sync.
1509 ui::KeyEvent keyup_event(ui::ET_KEY_RELEASED, ui::VKEY_A, kPlatformModifier);
1510
1511 ui::Cursor dummy_cursor_info;
1512 HandleInputEvent(MakeWebKeyboardEvent(char_event), &dummy_cursor_info);
1513 HandleInputEvent(MakeWebKeyboardEvent(keyup_event), &dummy_cursor_info);
1514 }
1515
CanUndo()1516 bool PepperPluginInstanceImpl::CanUndo() {
1517 if (!LoadPdfInterface())
1518 return false;
1519
1520 // No reference to |this| on the stack. Do not do any more work after this.
1521 // See NOTE above.
1522 return PP_ToBool(plugin_pdf_interface_->CanUndo(pp_instance()));
1523 }
1524
CanRedo()1525 bool PepperPluginInstanceImpl::CanRedo() {
1526 if (!LoadPdfInterface())
1527 return false;
1528
1529 // No reference to |this| on the stack. Do not do any more work after this.
1530 // See NOTE above.
1531 return PP_ToBool(plugin_pdf_interface_->CanRedo(pp_instance()));
1532 }
1533
Undo()1534 void PepperPluginInstanceImpl::Undo() {
1535 if (!LoadPdfInterface())
1536 return;
1537
1538 // No reference to |this| on the stack. Do not do any more work after this.
1539 // See NOTE above.
1540 plugin_pdf_interface_->Undo(pp_instance());
1541 }
1542
Redo()1543 void PepperPluginInstanceImpl::Redo() {
1544 if (!LoadPdfInterface())
1545 return;
1546
1547 plugin_pdf_interface_->Redo(pp_instance());
1548 }
1549
HandleAccessibilityAction(const PP_PdfAccessibilityActionData & action_data)1550 void PepperPluginInstanceImpl::HandleAccessibilityAction(
1551 const PP_PdfAccessibilityActionData& action_data) {
1552 if (!LoadPdfInterface())
1553 return;
1554
1555 plugin_pdf_interface_->HandleAccessibilityAction(pp_instance(), action_data);
1556 }
1557
RequestSurroundingText(size_t desired_number_of_characters)1558 void PepperPluginInstanceImpl::RequestSurroundingText(
1559 size_t desired_number_of_characters) {
1560 // Keep a reference on the stack. See NOTE above.
1561 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1562 if (!LoadTextInputInterface())
1563 return;
1564 plugin_textinput_interface_->RequestSurroundingText(
1565 pp_instance(), desired_number_of_characters);
1566 }
1567
StartFind(const std::string & search_text,bool case_sensitive,int identifier)1568 bool PepperPluginInstanceImpl::StartFind(const std::string& search_text,
1569 bool case_sensitive,
1570 int identifier) {
1571 // Keep a reference on the stack. See NOTE above.
1572 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1573 if (!LoadFindInterface())
1574 return false;
1575 find_identifier_ = identifier;
1576 return PP_ToBool(plugin_find_interface_->StartFind(
1577 pp_instance(), search_text.c_str(), PP_FromBool(case_sensitive)));
1578 }
1579
SelectFindResult(bool forward,int identifier)1580 void PepperPluginInstanceImpl::SelectFindResult(bool forward, int identifier) {
1581 // Keep a reference on the stack. See NOTE above.
1582 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1583 if (!LoadFindInterface())
1584 return;
1585 find_identifier_ = identifier;
1586 plugin_find_interface_->SelectFindResult(pp_instance(), PP_FromBool(forward));
1587 }
1588
StopFind()1589 void PepperPluginInstanceImpl::StopFind() {
1590 // Keep a reference on the stack. See NOTE above.
1591 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1592 if (!LoadFindInterface())
1593 return;
1594 find_identifier_ = -1;
1595 plugin_find_interface_->StopFind(pp_instance());
1596 }
1597
LoadFindInterface()1598 bool PepperPluginInstanceImpl::LoadFindInterface() {
1599 if (!module_->permissions().HasPermission(ppapi::PERMISSION_PDF))
1600 return false;
1601 if (!plugin_find_interface_) {
1602 plugin_find_interface_ = static_cast<const PPP_Find_Private*>(
1603 module_->GetPluginInterface(PPP_FIND_PRIVATE_INTERFACE));
1604 }
1605
1606 return !!plugin_find_interface_;
1607 }
1608
LoadInputEventInterface()1609 bool PepperPluginInstanceImpl::LoadInputEventInterface() {
1610 if (!checked_for_plugin_input_event_interface_) {
1611 checked_for_plugin_input_event_interface_ = true;
1612 plugin_input_event_interface_ = static_cast<const PPP_InputEvent*>(
1613 module_->GetPluginInterface(PPP_INPUT_EVENT_INTERFACE));
1614 }
1615 return !!plugin_input_event_interface_;
1616 }
1617
LoadMouseLockInterface()1618 bool PepperPluginInstanceImpl::LoadMouseLockInterface() {
1619 if (!plugin_mouse_lock_interface_) {
1620 plugin_mouse_lock_interface_ = static_cast<const PPP_MouseLock*>(
1621 module_->GetPluginInterface(PPP_MOUSELOCK_INTERFACE));
1622 }
1623
1624 return !!plugin_mouse_lock_interface_;
1625 }
1626
LoadPdfInterface()1627 bool PepperPluginInstanceImpl::LoadPdfInterface() {
1628 if (!checked_for_plugin_pdf_interface_) {
1629 checked_for_plugin_pdf_interface_ = true;
1630 plugin_pdf_interface_ = static_cast<const PPP_Pdf*>(
1631 module_->GetPluginInterface(PPP_PDF_INTERFACE_1));
1632 }
1633
1634 return !!plugin_pdf_interface_;
1635 }
1636
LoadPrintInterface()1637 bool PepperPluginInstanceImpl::LoadPrintInterface() {
1638 // Only check for the interface if the plugin has dev permission.
1639 if (!module_->permissions().HasPermission(ppapi::PERMISSION_DEV))
1640 return false;
1641 if (!plugin_print_interface_) {
1642 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1643 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1644 }
1645 return !!plugin_print_interface_;
1646 }
1647
LoadPrivateInterface()1648 bool PepperPluginInstanceImpl::LoadPrivateInterface() {
1649 // If this is a NaCl app, we want to talk to the trusted NaCl plugin to
1650 // call GetInstanceObject. This is necessary to ensure that the properties
1651 // the trusted plugin exposes (readyState and lastError) work properly. Note
1652 // that untrusted NaCl apps are not allowed to provide PPP_InstancePrivate,
1653 // so it's correct to never look up PPP_InstancePrivate for them.
1654 //
1655 // If this is *not* a NaCl plugin, original_module_ will never be set; we talk
1656 // to the "real" module.
1657 scoped_refptr<PluginModule> module =
1658 original_module_.get() ? original_module_ : module_;
1659 // Only check for the interface if the plugin has private permission.
1660 if (!module->permissions().HasPermission(ppapi::PERMISSION_PRIVATE))
1661 return false;
1662 if (!plugin_private_interface_) {
1663 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1664 module->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1665 }
1666
1667 return !!plugin_private_interface_;
1668 }
1669
LoadTextInputInterface()1670 bool PepperPluginInstanceImpl::LoadTextInputInterface() {
1671 if (!plugin_textinput_interface_) {
1672 plugin_textinput_interface_ = static_cast<const PPP_TextInput_Dev*>(
1673 module_->GetPluginInterface(PPP_TEXTINPUT_DEV_INTERFACE));
1674 }
1675
1676 return !!plugin_textinput_interface_;
1677 }
1678
SetGraphics2DTransform(const float & scale,const gfx::PointF & translation)1679 void PepperPluginInstanceImpl::SetGraphics2DTransform(
1680 const float& scale,
1681 const gfx::PointF& translation) {
1682 graphics2d_scale_ = scale;
1683 graphics2d_translation_ = translation;
1684
1685 UpdateLayerTransform();
1686 }
1687
UpdateLayerTransform()1688 void PepperPluginInstanceImpl::UpdateLayerTransform() {
1689 if (!bound_graphics_2d_platform_ || !texture_layer_) {
1690 // Currently the transform is only applied for Graphics2D.
1691 return;
1692 }
1693 // Set the UV coordinates of the texture based on the size of the Graphics2D
1694 // context. By default a texture gets scaled to the size of the layer. But
1695 // if the size of the Graphics2D context doesn't match the size of the plugin
1696 // then it will be incorrectly stretched. This also affects how the plugin
1697 // is painted when it is being resized. If the Graphics2D contents are
1698 // stretched when a plugin is resized while waiting for a new frame from the
1699 // plugin to be rendered, then flickering behavior occurs as in
1700 // crbug.com/353453.
1701 gfx::SizeF graphics_2d_size_in_dip =
1702 gfx::ScaleSize(gfx::SizeF(bound_graphics_2d_platform_->Size()),
1703 bound_graphics_2d_platform_->GetScale());
1704 gfx::Size plugin_size_in_dip(view_data_.rect.size.width,
1705 view_data_.rect.size.height);
1706
1707 // Adding the SetLayerTransform from Graphics2D to the UV.
1708 // If graphics2d_scale_ is 1.f and graphics2d_translation_ is 0 then UV will
1709 // be top_left (0,0) and lower_right (plugin_size_in_dip.width() /
1710 // graphics_2d_size_in_dip.width(), plugin_size_in_dip.height() /
1711 // graphics_2d_size_in_dip.height())
1712 gfx::PointF top_left =
1713 gfx::PointF(-graphics2d_translation_.x() / graphics2d_scale_,
1714 -graphics2d_translation_.y() / graphics2d_scale_);
1715 gfx::PointF lower_right =
1716 gfx::PointF((1 / graphics2d_scale_) * plugin_size_in_dip.width() -
1717 graphics2d_translation_.x() / graphics2d_scale_,
1718 (1 / graphics2d_scale_) * plugin_size_in_dip.height() -
1719 graphics2d_translation_.y() / graphics2d_scale_);
1720 texture_layer_->SetUV(
1721 gfx::PointF(top_left.x() / graphics_2d_size_in_dip.width(),
1722 top_left.y() / graphics_2d_size_in_dip.height()),
1723 gfx::PointF(lower_right.x() / graphics_2d_size_in_dip.width(),
1724 lower_right.y() / graphics_2d_size_in_dip.height()));
1725 }
1726
PluginHasFocus() const1727 bool PepperPluginInstanceImpl::PluginHasFocus() const {
1728 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1729 }
1730
SendFocusChangeNotification()1731 void PepperPluginInstanceImpl::SendFocusChangeNotification() {
1732 // Keep a reference on the stack. RenderFrameImpl::PepperFocusChanged may
1733 // remove the <embed> from the DOM, which will make the PepperWebPluginImpl
1734 // drop its reference, usually the last one. This is similar to possible
1735 // plugin behavior described at the NOTE above Delete().
1736 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1737
1738 if (!render_frame_)
1739 return;
1740
1741 bool has_focus = PluginHasFocus();
1742 render_frame_->PepperFocusChanged(this, has_focus);
1743
1744 // instance_interface_ may have been cleared in Delete() if the
1745 // PepperWebPluginImpl is destroyed.
1746 if (instance_interface_)
1747 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1748 }
1749
UpdateTouchEventRequest()1750 void PepperPluginInstanceImpl::UpdateTouchEventRequest() {
1751 // If the view has 0 area don't request touch events.
1752 if (view_data_.rect.size.width == 0 || view_data_.rect.size.height == 0) {
1753 container_->RequestTouchEventType(
1754 blink::WebPluginContainer::kTouchEventRequestTypeNone);
1755 return;
1756 }
1757 blink::WebPluginContainer::TouchEventRequestType request_type =
1758 blink::WebPluginContainer::kTouchEventRequestTypeSynthesizedMouse;
1759 if ((filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_COALESCED_TOUCH) ||
1760 (input_event_mask_ & PP_INPUTEVENT_CLASS_COALESCED_TOUCH)) {
1761 request_type =
1762 blink::WebPluginContainer::kTouchEventRequestTypeRawLowLatency;
1763 } else if ((filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1764 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH)) {
1765 request_type = blink::WebPluginContainer::kTouchEventRequestTypeRaw;
1766 }
1767
1768 container_->RequestTouchEventType(request_type);
1769 }
1770
UpdateWheelEventRequest()1771 void PepperPluginInstanceImpl::UpdateWheelEventRequest() {
1772 // If the view has 0 area don't request wheel events.
1773 if (view_data_.rect.size.width == 0 || view_data_.rect.size.height == 0) {
1774 container_->SetWantsWheelEvents(false);
1775 return;
1776 }
1777
1778 bool hasWheelMask =
1779 (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1780 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1781 container_->SetWantsWheelEvents(hasWheelMask);
1782 }
1783
ScheduleAsyncDidChangeView()1784 void PepperPluginInstanceImpl::ScheduleAsyncDidChangeView() {
1785 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1786 return; // Already scheduled.
1787 base::ThreadTaskRunnerHandle::Get()->PostTask(
1788 FROM_HERE,
1789 base::BindOnce(&PepperPluginInstanceImpl::SendAsyncDidChangeView,
1790 view_change_weak_ptr_factory_.GetWeakPtr()));
1791 }
1792
SendAsyncDidChangeView()1793 void PepperPluginInstanceImpl::SendAsyncDidChangeView() {
1794 // The bound callback that owns the weak pointer is still valid until after
1795 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1796 // invalidate them here.
1797 // NOTE: If we ever want to have more than one pending callback, it should
1798 // use a different factory, or we should have a different strategy here.
1799 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1800 SendDidChangeView();
1801 }
1802
SendDidChangeView()1803 void PepperPluginInstanceImpl::SendDidChangeView() {
1804 if (!render_frame_)
1805 return;
1806
1807 // An asynchronous view update is scheduled. Skip sending this update.
1808 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1809 return;
1810
1811 // Don't send DidChangeView to crashed plugins.
1812 if (module()->is_crashed())
1813 return;
1814
1815 if (bound_graphics_2d_platform_)
1816 bound_graphics_2d_platform_->set_viewport_to_dip_scale(
1817 viewport_to_dip_scale_);
1818
1819 module_->renderer_ppapi_host()->set_viewport_to_dip_scale(
1820 viewport_to_dip_scale_);
1821
1822 // During the first view update, initialize the throttler.
1823 if (!sent_initial_did_change_view_ && throttler_) {
1824 throttler_->Initialize(render_frame_, url::Origin::Create(plugin_url_),
1825 module()->name(), unobscured_rect_.size());
1826 }
1827
1828 ppapi::ViewData view_data = view_data_;
1829
1830 // When plugin content is throttled, fake the page being offscreen. We cannot
1831 // send empty view data here, as some plugins rely on accurate view data.
1832 if (throttler_ && throttler_->IsThrottled()) {
1833 view_data.is_page_visible = false;
1834 view_data.clip_rect.point.x = 0;
1835 view_data.clip_rect.point.y = 0;
1836 view_data.clip_rect.size.width = 0;
1837 view_data.clip_rect.size.height = 0;
1838 }
1839
1840 if (sent_initial_did_change_view_ && last_sent_view_data_.Equals(view_data))
1841 return; // Nothing to update.
1842
1843 sent_initial_did_change_view_ = true;
1844 last_sent_view_data_ = view_data;
1845 ScopedPPResource resource(
1846 ScopedPPResource::PassRef(),
1847 (new PPB_View_Shared(ppapi::OBJECT_IS_IMPL, pp_instance(), view_data))
1848 ->GetReference());
1849
1850 UpdateLayerTransform();
1851
1852 if (bound_graphics_2d_platform_ &&
1853 (!view_data.is_page_visible ||
1854 PP_ToGfxRect(view_data.clip_rect).IsEmpty())) {
1855 bound_graphics_2d_platform_->ClearCache();
1856 }
1857
1858 // It's possible that Delete() has been called but the renderer hasn't
1859 // released its reference to this object yet.
1860 if (instance_interface_) {
1861 instance_interface_->DidChangeView(
1862 pp_instance(), resource, &view_data.rect, &view_data.clip_rect);
1863 }
1864 }
1865
ReportGeometry()1866 void PepperPluginInstanceImpl::ReportGeometry() {
1867 // If this call was delayed, we may have transitioned back to fullscreen in
1868 // the mean time, so only report the geometry if we are actually in normal
1869 // mode.
1870 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1871 container_->ReportGeometry();
1872 }
1873
GetPreferredPrintOutputFormat(PP_PrintOutputFormat_Dev * format,const WebPrintParams & print_params)1874 bool PepperPluginInstanceImpl::GetPreferredPrintOutputFormat(
1875 PP_PrintOutputFormat_Dev* format,
1876 const WebPrintParams& print_params) {
1877 // Keep a reference on the stack. See NOTE above.
1878 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1879 if (!LoadPrintInterface())
1880 return false;
1881 uint32_t supported_formats =
1882 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1883 if ((supported_formats & PP_PRINTOUTPUTFORMAT_PDF) &&
1884 !print_params.rasterize_pdf) {
1885 *format = PP_PRINTOUTPUTFORMAT_PDF;
1886 return true;
1887 }
1888 if (supported_formats & PP_PRINTOUTPUTFORMAT_RASTER) {
1889 *format = PP_PRINTOUTPUTFORMAT_RASTER;
1890 return true;
1891 }
1892 return false;
1893 }
1894
SupportsPrintInterface()1895 bool PepperPluginInstanceImpl::SupportsPrintInterface() {
1896 PP_PrintOutputFormat_Dev format;
1897 WebPrintParams params;
1898 params.rasterize_pdf = false;
1899 return GetPreferredPrintOutputFormat(&format, params);
1900 }
1901
PrintBegin(const WebPrintParams & print_params)1902 int PepperPluginInstanceImpl::PrintBegin(const WebPrintParams& print_params) {
1903 // Keep a reference on the stack. See NOTE above.
1904 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1905 PP_PrintOutputFormat_Dev format;
1906 if (!GetPreferredPrintOutputFormat(&format, print_params)) {
1907 // PrintBegin should not have been called since SupportsPrintInterface
1908 // would have returned false;
1909 NOTREACHED();
1910 return 0;
1911 }
1912
1913 int num_pages;
1914 PP_PrintSettings_Dev print_settings;
1915 print_settings.printable_area = PP_FromGfxRect(print_params.printable_area);
1916 print_settings.content_area = PP_FromGfxRect(print_params.print_content_area);
1917 print_settings.paper_size = PP_FromGfxSize(print_params.paper_size);
1918 print_settings.dpi = print_params.printer_dpi;
1919 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1920 print_settings.grayscale = PP_FALSE;
1921 print_settings.print_scaling_option =
1922 static_cast<PP_PrintScalingOption_Dev>(print_params.print_scaling_option);
1923 print_settings.format = format;
1924
1925 if (LoadPdfInterface()) {
1926 PP_PdfPrintSettings_Dev pdf_print_settings;
1927 pdf_print_settings.pages_per_sheet = print_params.pages_per_sheet;
1928 pdf_print_settings.scale_factor = print_params.scale_factor;
1929
1930 num_pages = plugin_pdf_interface_->PrintBegin(
1931 pp_instance(), &print_settings, &pdf_print_settings);
1932 } else {
1933 // If the content is not from the PDF plugin, "fit to paper" should have
1934 // never been a scaling option for the user to begin with.
1935 DCHECK_NE(print_settings.print_scaling_option,
1936 PP_PRINTSCALINGOPTION_FIT_TO_PAPER);
1937
1938 num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
1939 }
1940 if (!num_pages)
1941 return 0;
1942
1943 current_print_settings_ = print_settings;
1944 metafile_ = nullptr;
1945 ranges_.clear();
1946 ranges_.reserve(num_pages);
1947 return num_pages;
1948 }
1949
PrintPage(int page_number,cc::PaintCanvas * canvas)1950 void PepperPluginInstanceImpl::PrintPage(int page_number,
1951 cc::PaintCanvas* canvas) {
1952 #if BUILDFLAG(ENABLE_PRINTING)
1953 DCHECK(plugin_print_interface_);
1954
1955 // |canvas| should always have an associated metafile.
1956 auto* metafile = canvas->GetPrintingMetafile();
1957 DCHECK(metafile);
1958
1959 // |ranges_| should be empty IFF |metafile_| is not set.
1960 DCHECK_EQ(ranges_.empty(), !metafile_);
1961 if (metafile_) {
1962 // The metafile should be the same across all calls for a given print job.
1963 DCHECK_EQ(metafile_, metafile);
1964 } else {
1965 // Store |metafile| on the first call.
1966 metafile_ = metafile;
1967 }
1968
1969 PP_PrintPageNumberRange_Dev page_range = {uint32_t(page_number), uint32_t(page_number)};
1970 ranges_.push_back(page_range);
1971 #endif
1972 }
1973
PrintEnd()1974 void PepperPluginInstanceImpl::PrintEnd() {
1975 // Keep a reference on the stack. See NOTE above.
1976 scoped_refptr<PepperPluginInstanceImpl> ref(this);
1977 DCHECK(plugin_print_interface_);
1978
1979 if (!ranges_.empty()) {
1980 PP_Resource print_output = plugin_print_interface_->PrintPages(
1981 pp_instance(), ranges_.data(), ranges_.size());
1982 if (print_output) {
1983 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF ||
1984 current_print_settings_.format == PP_PRINTOUTPUTFORMAT_RASTER) {
1985 PrintPDFOutput(print_output, metafile_);
1986 }
1987
1988 // Now release the print output resource.
1989 PluginModule::GetCore()->ReleaseResource(print_output);
1990 }
1991
1992 ranges_.clear();
1993 metafile_ = nullptr;
1994 }
1995
1996 plugin_print_interface_->End(pp_instance());
1997 memset(¤t_print_settings_, 0, sizeof(current_print_settings_));
1998 }
1999
GetPrintPresetOptionsFromDocument(blink::WebPrintPresetOptions * preset_options)2000 bool PepperPluginInstanceImpl::GetPrintPresetOptionsFromDocument(
2001 blink::WebPrintPresetOptions* preset_options) {
2002 // Keep a reference on the stack. See NOTE above.
2003 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2004 if (!LoadPdfInterface())
2005 return false;
2006
2007 PP_PdfPrintPresetOptions_Dev options;
2008 if (!plugin_pdf_interface_->GetPrintPresetOptionsFromDocument(pp_instance(),
2009 &options)) {
2010 return false;
2011 }
2012
2013 preset_options->is_scaling_disabled = PP_ToBool(options.is_scaling_disabled);
2014 switch (options.duplex) {
2015 case PP_PRIVATEDUPLEXMODE_SIMPLEX:
2016 preset_options->duplex_mode = blink::kWebSimplex;
2017 break;
2018 case PP_PRIVATEDUPLEXMODE_SHORT_EDGE:
2019 preset_options->duplex_mode = blink::kWebShortEdge;
2020 break;
2021 case PP_PRIVATEDUPLEXMODE_LONG_EDGE:
2022 preset_options->duplex_mode = blink::kWebLongEdge;
2023 break;
2024 default:
2025 preset_options->duplex_mode = blink::kWebUnknownDuplexMode;
2026 break;
2027 }
2028 preset_options->copies = options.copies;
2029 preset_options->is_page_size_uniform =
2030 PP_ToBool(options.is_page_size_uniform);
2031 preset_options->uniform_page_size = blink::WebSize(
2032 options.uniform_page_size.width, options.uniform_page_size.height);
2033
2034 return true;
2035 }
2036
IsPdfPlugin()2037 bool PepperPluginInstanceImpl::IsPdfPlugin() {
2038 return LoadPdfInterface();
2039 }
2040
CanRotateView()2041 bool PepperPluginInstanceImpl::CanRotateView() {
2042 if (!LoadPdfInterface() || module()->is_crashed())
2043 return false;
2044
2045 return true;
2046 }
2047
RotateView(WebPlugin::RotationType type)2048 void PepperPluginInstanceImpl::RotateView(WebPlugin::RotationType type) {
2049 if (!LoadPdfInterface())
2050 return;
2051 PP_PrivatePageTransformType transform_type =
2052 type == WebPlugin::kRotationType90Clockwise
2053 ? PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
2054 : PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
2055 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
2056 // NOTE: plugin instance may have been deleted.
2057 }
2058
FlashIsFullscreenOrPending()2059 bool PepperPluginInstanceImpl::FlashIsFullscreenOrPending() {
2060 return fullscreen_container_ != nullptr;
2061 }
2062
IsFullscreenOrPending()2063 bool PepperPluginInstanceImpl::IsFullscreenOrPending() {
2064 return desired_fullscreen_state_;
2065 }
2066
SetFullscreen(bool fullscreen)2067 bool PepperPluginInstanceImpl::SetFullscreen(bool fullscreen) {
2068 // Keep a reference on the stack. See NOTE above.
2069 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2070
2071 // Check whether we are trying to switch to the state we're already going
2072 // to (i.e. if we're already switching to fullscreen but the fullscreen
2073 // container isn't ready yet, don't do anything more).
2074 if (fullscreen == IsFullscreenOrPending())
2075 return false;
2076
2077 if (!SetFullscreenCommon(fullscreen))
2078 return false;
2079
2080 // Check whether we are trying to switch while the state is in transition.
2081 // The 2nd request gets dropped while messing up the internal state, so
2082 // disallow this.
2083 if (view_data_.is_fullscreen != desired_fullscreen_state_)
2084 return false;
2085
2086 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
2087 desired_fullscreen_state_ = fullscreen;
2088
2089 if (fullscreen) {
2090 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
2091 // so we will tweak plugin's attributes to support the expected behavior.
2092 KeepSizeAttributesBeforeFullscreen();
2093 SetSizeAttributesForFullscreen();
2094 container_->RequestFullscreen();
2095 } else {
2096 container_->CancelFullscreen();
2097 }
2098 return true;
2099 }
2100
UpdateFlashFullscreenState(bool flash_fullscreen)2101 void PepperPluginInstanceImpl::UpdateFlashFullscreenState(
2102 bool flash_fullscreen) {
2103 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
2104
2105 if (flash_fullscreen == flash_fullscreen_) {
2106 // Manually clear callback when fullscreen fails with mouselock pending.
2107 if (!flash_fullscreen && is_mouselock_pending)
2108 lock_mouse_callback_->Run(PP_ERROR_FAILED);
2109 return;
2110 }
2111
2112 UpdateLayer(false);
2113
2114 bool old_plugin_focus = PluginHasFocus();
2115 flash_fullscreen_ = flash_fullscreen;
2116 if (is_mouselock_pending && !IsMouseLocked()) {
2117 if (!HasTransientUserActivation() &&
2118 !module_->permissions().HasPermission(
2119 ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
2120 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
2121 } else {
2122 if (!LockMouse(/*request_unadjusted_movement=*/false))
2123 lock_mouse_callback_->Run(PP_ERROR_FAILED);
2124 }
2125 }
2126
2127 if (PluginHasFocus() != old_plugin_focus)
2128 SendFocusChangeNotification();
2129 }
2130
UpdateLayer(bool force_creation)2131 void PepperPluginInstanceImpl::UpdateLayer(bool force_creation) {
2132 if (!container_)
2133 return;
2134
2135 bool want_3d_layer = !!bound_graphics_3d_.get();
2136 bool want_2d_layer = !!bound_graphics_2d_platform_;
2137 bool want_texture_layer = want_3d_layer || want_2d_layer;
2138
2139 if (throttler_ && throttler_->IsHiddenForPlaceholder()) {
2140 want_3d_layer = false;
2141 want_2d_layer = false;
2142 want_texture_layer = false;
2143 }
2144
2145 if (!force_creation && (want_texture_layer == !!texture_layer_) &&
2146 (want_3d_layer == layer_is_hardware_) &&
2147 layer_bound_to_fullscreen_ == !!fullscreen_container_) {
2148 UpdateLayerTransform();
2149 return;
2150 }
2151
2152 if (texture_layer_) {
2153 if (!layer_bound_to_fullscreen_)
2154 container_->SetCcLayer(nullptr, false);
2155 else if (fullscreen_container_)
2156 fullscreen_container_->SetLayer(nullptr);
2157 texture_layer_->ClearClient();
2158 texture_layer_ = nullptr;
2159 }
2160
2161 if (want_texture_layer) {
2162 bool opaque = false;
2163 if (want_3d_layer) {
2164 DCHECK(bound_graphics_3d_.get());
2165 texture_layer_ = cc::TextureLayer::CreateForMailbox(nullptr);
2166 opaque = bound_graphics_3d_->IsOpaque();
2167
2168 PassCommittedTextureToTextureLayer();
2169 } else {
2170 DCHECK(bound_graphics_2d_platform_);
2171 texture_layer_ = cc::TextureLayer::CreateForMailbox(this);
2172 bound_graphics_2d_platform_->AttachedToNewLayer();
2173 opaque = bound_graphics_2d_platform_->IsAlwaysOpaque();
2174 texture_layer_->SetFlipped(false);
2175 }
2176
2177 // Ignore transparency in fullscreen, since that's what Flash always
2178 // wants to do, and that lets it not recreate a context if
2179 // wmode=transparent was specified.
2180 opaque = opaque || fullscreen_container_;
2181 texture_layer_->SetContentsOpaque(opaque);
2182 }
2183
2184 if (texture_layer_) {
2185 if (fullscreen_container_)
2186 fullscreen_container_->SetLayer(texture_layer_);
2187 else
2188 container_->SetCcLayer(texture_layer_.get(), true);
2189 if (is_flash_plugin_)
2190 texture_layer_->SetMayContainVideo(true);
2191 }
2192
2193 layer_bound_to_fullscreen_ = !!fullscreen_container_;
2194 layer_is_hardware_ = want_3d_layer;
2195 UpdateLayerTransform();
2196 }
2197
PrepareTransferableResource(cc::SharedBitmapIdRegistrar * bitmap_registrar,viz::TransferableResource * transferable_resource,std::unique_ptr<viz::SingleReleaseCallback> * release_callback)2198 bool PepperPluginInstanceImpl::PrepareTransferableResource(
2199 cc::SharedBitmapIdRegistrar* bitmap_registrar,
2200 viz::TransferableResource* transferable_resource,
2201 std::unique_ptr<viz::SingleReleaseCallback>* release_callback) {
2202 if (!bound_graphics_2d_platform_)
2203 return false;
2204 return bound_graphics_2d_platform_->PrepareTransferableResource(
2205 bitmap_registrar, transferable_resource, release_callback);
2206 }
2207
AccessibilityModeChanged(const ui::AXMode & mode)2208 void PepperPluginInstanceImpl::AccessibilityModeChanged(
2209 const ui::AXMode& mode) {
2210 HandleAccessibilityChange();
2211 }
2212
OnDestruct()2213 void PepperPluginInstanceImpl::OnDestruct() {
2214 render_frame_ = nullptr;
2215 }
2216
OnThrottleStateChange()2217 void PepperPluginInstanceImpl::OnThrottleStateChange() {
2218 if (!render_frame_)
2219 return;
2220
2221 SendDidChangeView();
2222
2223 bool is_throttled = throttler_->IsThrottled();
2224 render_frame()->Send(new FrameHostMsg_PluginInstanceThrottleStateChange(
2225 module_->GetPluginChildId(), pp_instance_, is_throttled));
2226 }
2227
OnHiddenForPlaceholder(bool hidden)2228 void PepperPluginInstanceImpl::OnHiddenForPlaceholder(bool hidden) {
2229 UpdateLayer(false /* device_changed */);
2230 }
2231
AddPluginObject(PluginObject * plugin_object)2232 void PepperPluginInstanceImpl::AddPluginObject(PluginObject* plugin_object) {
2233 DCHECK(live_plugin_objects_.find(plugin_object) ==
2234 live_plugin_objects_.end());
2235 live_plugin_objects_.insert(plugin_object);
2236 }
2237
RemovePluginObject(PluginObject * plugin_object)2238 void PepperPluginInstanceImpl::RemovePluginObject(PluginObject* plugin_object) {
2239 // Don't actually verify that the object is in the set since during module
2240 // deletion we'll be in the process of freeing them.
2241 live_plugin_objects_.erase(plugin_object);
2242 }
2243
HasTransientUserActivation() const2244 bool PepperPluginInstanceImpl::HasTransientUserActivation() const {
2245 return render_frame_->GetWebFrame()->HasTransientUserActivation();
2246 }
2247
OnLockMouseACK(bool succeeded)2248 void PepperPluginInstanceImpl::OnLockMouseACK(bool succeeded) {
2249 if (TrackedCallback::IsPending(lock_mouse_callback_))
2250 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
2251 }
2252
OnMouseLockLost()2253 void PepperPluginInstanceImpl::OnMouseLockLost() {
2254 if (LoadMouseLockInterface())
2255 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
2256 }
2257
HandleMouseLockedInputEvent(const blink::WebMouseEvent & event)2258 void PepperPluginInstanceImpl::HandleMouseLockedInputEvent(
2259 const blink::WebMouseEvent& event) {
2260 // |cursor| is ignored since it is hidden when the mouse is locked.
2261 ui::Cursor cursor;
2262 HandleInputEvent(event, &cursor);
2263 }
2264
SimulateInputEvent(const InputEventData & input_event)2265 void PepperPluginInstanceImpl::SimulateInputEvent(
2266 const InputEventData& input_event) {
2267 WebWidget* widget =
2268 container()->GetDocument().GetFrame()->LocalRoot()->FrameWidget();
2269 if (!widget) {
2270 NOTREACHED();
2271 return;
2272 }
2273
2274 bool handled = SimulateIMEEvent(input_event);
2275 if (handled)
2276 return;
2277
2278 std::vector<std::unique_ptr<WebInputEvent>> events =
2279 CreateSimulatedWebInputEvents(
2280 input_event, view_data_.rect.point.x + view_data_.rect.size.width / 2,
2281 view_data_.rect.point.y + view_data_.rect.size.height / 2);
2282 for (auto it = events.begin(); it != events.end(); ++it) {
2283 widget->HandleInputEvent(blink::WebCoalescedInputEvent(*it->get()));
2284 }
2285 if (input_event.event_type == PP_INPUTEVENT_TYPE_TOUCHSTART ||
2286 input_event.event_type == PP_INPUTEVENT_TYPE_TOUCHMOVE ||
2287 input_event.event_type == PP_INPUTEVENT_TYPE_TOUCHEND ||
2288 input_event.event_type == PP_INPUTEVENT_TYPE_TOUCHCANCEL)
2289 widget->DispatchBufferedTouchEvents();
2290 }
2291
SimulateIMEEvent(const InputEventData & input_event)2292 bool PepperPluginInstanceImpl::SimulateIMEEvent(
2293 const InputEventData& input_event) {
2294 switch (input_event.event_type) {
2295 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
2296 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
2297 SimulateImeSetCompositionEvent(input_event);
2298 break;
2299 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
2300 DCHECK(input_event.character_text.empty());
2301 SimulateImeSetCompositionEvent(input_event);
2302 break;
2303 case PP_INPUTEVENT_TYPE_IME_TEXT:
2304 if (!render_frame_)
2305 return false;
2306 render_frame_->SimulateImeCommitText(
2307 base::UTF8ToUTF16(input_event.character_text),
2308 std::vector<blink::WebImeTextSpan>(), gfx::Range());
2309 break;
2310 default:
2311 return false;
2312 }
2313 return true;
2314 }
2315
SimulateImeSetCompositionEvent(const InputEventData & input_event)2316 void PepperPluginInstanceImpl::SimulateImeSetCompositionEvent(
2317 const InputEventData& input_event) {
2318 if (!render_frame_)
2319 return;
2320
2321 std::vector<size_t> offsets;
2322 offsets.push_back(input_event.composition_selection_start);
2323 offsets.push_back(input_event.composition_selection_end);
2324 offsets.insert(offsets.end(),
2325 input_event.composition_segment_offsets.begin(),
2326 input_event.composition_segment_offsets.end());
2327
2328 base::string16 utf16_text =
2329 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
2330
2331 std::vector<blink::WebImeTextSpan> ime_text_spans;
2332 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
2333 blink::WebImeTextSpan ime_text_span;
2334 ime_text_span.start_offset = offsets[i];
2335 ime_text_span.end_offset = offsets[i + 1];
2336 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
2337 ime_text_span.thickness = ui::mojom::ImeTextSpanThickness::kThick;
2338 ime_text_spans.push_back(ime_text_span);
2339 }
2340
2341 render_frame_->SimulateImeSetComposition(utf16_text, ime_text_spans,
2342 offsets[0], offsets[1]);
2343 }
2344
BindGraphics(PP_Instance instance,PP_Resource device)2345 PP_Bool PepperPluginInstanceImpl::BindGraphics(PP_Instance instance,
2346 PP_Resource device) {
2347 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::BindGraphics");
2348 // The Graphics3D instance can't be destroyed until we call
2349 // UpdateLayer().
2350 scoped_refptr<ppapi::Resource> old_graphics = bound_graphics_3d_.get();
2351 if (bound_graphics_3d_.get()) {
2352 bound_graphics_3d_->BindToInstance(false);
2353 bound_graphics_3d_ = nullptr;
2354 }
2355 if (bound_graphics_2d_platform_) {
2356 bound_graphics_2d_platform_->BindToInstance(nullptr);
2357 bound_graphics_2d_platform_ = nullptr;
2358 }
2359
2360 // Special-case clearing the current device.
2361 if (!device) {
2362 UpdateLayer(true);
2363 InvalidateRect(gfx::Rect());
2364 return PP_TRUE;
2365 }
2366
2367 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
2368 // to/from fullscreen with PPB_Fullscreen.
2369 if ((fullscreen_container_ && !flash_fullscreen_) ||
2370 desired_fullscreen_state_ != view_data_.is_fullscreen)
2371 return PP_FALSE;
2372
2373 const ppapi::host::PpapiHost* ppapi_host =
2374 RendererPpapiHost::GetForPPInstance(instance)->GetPpapiHost();
2375 ppapi::host::ResourceHost* host = ppapi_host->GetResourceHost(device);
2376 PepperGraphics2DHost* graphics_2d = nullptr;
2377 if (host) {
2378 if (host->IsGraphics2DHost()) {
2379 graphics_2d = static_cast<PepperGraphics2DHost*>(host);
2380 } else {
2381 DLOG(ERROR) <<
2382 "Resource is not PepperCompositorHost or PepperGraphics2DHost.";
2383 }
2384 }
2385
2386 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
2387 PPB_Graphics3D_Impl* graphics_3d =
2388 enter_3d.succeeded()
2389 ? static_cast<PPB_Graphics3D_Impl*>(enter_3d.object())
2390 : nullptr;
2391
2392 if (graphics_2d) {
2393 if (graphics_2d->BindToInstance(this)) {
2394 bound_graphics_2d_platform_ = graphics_2d;
2395 bound_graphics_2d_platform_->set_viewport_to_dip_scale(
2396 viewport_to_dip_scale_);
2397 UpdateLayer(true);
2398 return PP_TRUE;
2399 }
2400 } else if (graphics_3d) {
2401 // Make sure graphics can only be bound to the instance it is
2402 // associated with.
2403 if (graphics_3d->pp_instance() == pp_instance() &&
2404 graphics_3d->BindToInstance(true)) {
2405 bound_graphics_3d_ = graphics_3d;
2406 UpdateLayer(true);
2407 return PP_TRUE;
2408 }
2409 }
2410
2411 // The instance cannot be bound or the device is not a valid resource type.
2412 return PP_FALSE;
2413 }
2414
IsFullFrame(PP_Instance instance)2415 PP_Bool PepperPluginInstanceImpl::IsFullFrame(PP_Instance instance) {
2416 return PP_FromBool(full_frame());
2417 }
2418
GetViewData(PP_Instance instance)2419 const ViewData* PepperPluginInstanceImpl::GetViewData(PP_Instance instance) {
2420 return &view_data_;
2421 }
2422
FlashIsFullscreen(PP_Instance instance)2423 PP_Bool PepperPluginInstanceImpl::FlashIsFullscreen(PP_Instance instance) {
2424 return PP_FromBool(flash_fullscreen_);
2425 }
2426
GetWindowObject(PP_Instance instance)2427 PP_Var PepperPluginInstanceImpl::GetWindowObject(PP_Instance instance) {
2428 if (!container_)
2429 return PP_MakeUndefined();
2430 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2431 PepperTryCatchVar try_catch(this, &converter, nullptr);
2432 WebLocalFrame* frame = container_->GetDocument().GetFrame();
2433 if (!frame) {
2434 try_catch.SetException("No frame exists for window object.");
2435 return PP_MakeUndefined();
2436 }
2437
2438 ScopedPPVar result =
2439 try_catch.FromV8(frame->MainWorldScriptContext()->Global());
2440 DCHECK(!try_catch.HasException());
2441 return result.Release();
2442 }
2443
GetOwnerElementObject(PP_Instance instance)2444 PP_Var PepperPluginInstanceImpl::GetOwnerElementObject(PP_Instance instance) {
2445 if (!container_)
2446 return PP_MakeUndefined();
2447 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2448 PepperTryCatchVar try_catch(this, &converter, nullptr);
2449 ScopedPPVar result = try_catch.FromV8(container_->V8ObjectForElement());
2450 DCHECK(!try_catch.HasException());
2451 return result.Release();
2452 }
2453
ExecuteScript(PP_Instance instance,PP_Var script_var,PP_Var * exception)2454 PP_Var PepperPluginInstanceImpl::ExecuteScript(PP_Instance instance,
2455 PP_Var script_var,
2456 PP_Var* exception) {
2457 if (!container_)
2458 return PP_MakeUndefined();
2459 if (is_deleted_ && blink::WebPluginScriptForbiddenScope::IsForbidden())
2460 return PP_MakeUndefined();
2461
2462 // Executing the script may remove the plugin from the DOM, so we need to keep
2463 // a reference to ourselves so that we can still process the result after
2464 // running the script below.
2465 scoped_refptr<PepperPluginInstanceImpl> ref(this);
2466 V8VarConverter converter(pp_instance_, V8VarConverter::kAllowObjectVars);
2467 PepperTryCatchVar try_catch(this, &converter, exception);
2468
2469 // Check for an exception due to the context being destroyed.
2470 if (try_catch.HasException())
2471 return PP_MakeUndefined();
2472
2473 WebLocalFrame* frame = container_->GetDocument().GetFrame();
2474 if (!frame) {
2475 try_catch.SetException("No frame to execute script in.");
2476 return PP_MakeUndefined();
2477 }
2478
2479 StringVar* script_string_var = StringVar::FromPPVar(script_var);
2480 if (!script_string_var) {
2481 try_catch.SetException("Script param to ExecuteScript must be a string.");
2482 return PP_MakeUndefined();
2483 }
2484
2485 std::string script_string = script_string_var->value();
2486 blink::WebScriptSource script(
2487 blink::WebString::FromUTF8(script_string.c_str()));
2488 v8::Local<v8::Value> result;
2489 if (HasTransientUserActivation()) {
2490 result = frame->ExecuteScriptAndReturnValue(script);
2491 } else {
2492 result = frame->ExecuteScriptAndReturnValue(script);
2493 }
2494
2495 ScopedPPVar var_result = try_catch.FromV8(result);
2496 if (try_catch.HasException())
2497 return PP_MakeUndefined();
2498
2499 return var_result.Release();
2500 }
2501
GetAudioHardwareOutputSampleRate(PP_Instance instance)2502 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputSampleRate(
2503 PP_Instance instance) {
2504 return render_frame() ? AudioDeviceFactory::GetOutputDeviceInfo(
2505 render_frame()->GetRoutingID(),
2506 media::AudioSinkParameters())
2507 .output_params()
2508 .sample_rate()
2509 : 0;
2510 }
2511
GetAudioHardwareOutputBufferSize(PP_Instance instance)2512 uint32_t PepperPluginInstanceImpl::GetAudioHardwareOutputBufferSize(
2513 PP_Instance instance) {
2514 return render_frame() ? AudioDeviceFactory::GetOutputDeviceInfo(
2515 render_frame()->GetRoutingID(),
2516 media::AudioSinkParameters())
2517 .output_params()
2518 .frames_per_buffer()
2519 : 0;
2520 }
2521
GetDefaultCharSet(PP_Instance instance)2522 PP_Var PepperPluginInstanceImpl::GetDefaultCharSet(PP_Instance instance) {
2523 if (!render_frame_)
2524 return PP_MakeUndefined();
2525 return StringVar::StringToPPVar(
2526 render_frame_->render_view()->webkit_preferences().default_encoding);
2527 }
2528
SetPluginToHandleFindRequests(PP_Instance instance)2529 void PepperPluginInstanceImpl::SetPluginToHandleFindRequests(
2530 PP_Instance instance) {
2531 if (!LoadFindInterface())
2532 return;
2533 bool is_main_frame =
2534 render_frame_ &&
2535 render_frame_->GetRenderView()->GetMainRenderFrame() == render_frame_;
2536 if (!is_main_frame)
2537 return;
2538 container_->UsePluginAsFindHandler();
2539 }
2540
NumberOfFindResultsChanged(PP_Instance instance,int32_t total,PP_Bool final_result)2541 void PepperPluginInstanceImpl::NumberOfFindResultsChanged(
2542 PP_Instance instance,
2543 int32_t total,
2544 PP_Bool final_result) {
2545 // After stopping search and setting find_identifier_ to -1 there still may be
2546 // a NumberOfFindResultsChanged notification pending from plug-in. Just ignore
2547 // them.
2548 if (find_identifier_ == -1)
2549 return;
2550 if (!container_)
2551 return;
2552 container_->ReportFindInPageMatchCount(find_identifier_, total,
2553 PP_ToBool(final_result));
2554 }
2555
SelectedFindResultChanged(PP_Instance instance,int32_t index)2556 void PepperPluginInstanceImpl::SelectedFindResultChanged(PP_Instance instance,
2557 int32_t index) {
2558 if (find_identifier_ == -1)
2559 return;
2560 if (!container_)
2561 return;
2562 container_->ReportFindInPageSelection(find_identifier_, index + 1);
2563 }
2564
SetTickmarks(PP_Instance instance,const PP_Rect * tickmarks,uint32_t count)2565 void PepperPluginInstanceImpl::SetTickmarks(PP_Instance instance,
2566 const PP_Rect* tickmarks,
2567 uint32_t count) {
2568 if (!render_frame_ || !render_frame_->GetWebFrame())
2569 return;
2570
2571 blink::WebVector<blink::WebRect> tickmarks_converted(
2572 static_cast<size_t>(count));
2573 for (uint32_t i = 0; i < count; ++i) {
2574 gfx::RectF tickmark(tickmarks[i].point.x,
2575 tickmarks[i].point.y,
2576 tickmarks[i].size.width,
2577 tickmarks[i].size.height);
2578 tickmark.Scale(1 / viewport_to_dip_scale_);
2579 tickmarks_converted[i] = blink::WebRect(gfx::ToEnclosedRect(tickmark));
2580 }
2581 WebLocalFrame* frame = render_frame_->GetWebFrame();
2582 frame->SetTickmarks(tickmarks_converted);
2583 }
2584
IsFullscreen(PP_Instance instance)2585 PP_Bool PepperPluginInstanceImpl::IsFullscreen(PP_Instance instance) {
2586 return PP_FromBool(view_data_.is_fullscreen);
2587 }
2588
SetFullscreen(PP_Instance instance,PP_Bool fullscreen)2589 PP_Bool PepperPluginInstanceImpl::SetFullscreen(PP_Instance instance,
2590 PP_Bool fullscreen) {
2591 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2592 }
2593
GetScreenSize(PP_Instance instance,PP_Size * size)2594 PP_Bool PepperPluginInstanceImpl::GetScreenSize(PP_Instance instance,
2595 PP_Size* size) {
2596 if (flash_fullscreen_) {
2597 // Workaround for Flash rendering bug: Flash is assuming the fullscreen view
2598 // size will be equal to the physical screen size. However, the fullscreen
2599 // view is sized by the browser UI, and may not be the same size as the
2600 // screen or the desktop. Therefore, report the view size as the screen
2601 // size when in fullscreen mode. http://crbug.com/506016
2602 // TODO(miu): Remove this workaround once Flash has been fixed.
2603 *size = view_data_.rect.size;
2604 } else {
2605 // All other cases: Report the screen size.
2606 if (!render_frame_)
2607 return PP_FALSE;
2608 blink::WebScreenInfo info =
2609 render_frame_->GetLocalRootRenderWidget()->GetScreenInfo();
2610 *size = PP_MakeSize(info.rect.width, info.rect.height);
2611 }
2612 return PP_TRUE;
2613 }
2614
GetSingletonResource(PP_Instance instance,ppapi::SingletonResourceID id)2615 ppapi::Resource* PepperPluginInstanceImpl::GetSingletonResource(
2616 PP_Instance instance,
2617 ppapi::SingletonResourceID id) {
2618 // Flash APIs and some others aren't implemented in-process.
2619 switch (id) {
2620 case ppapi::BROKER_SINGLETON_ID:
2621 case ppapi::BROWSER_FONT_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 nullptr;
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);
2641 }
2642 }
2643 return uma_private_impl_.get();
2644 }
2645 }
2646
2647 NOTREACHED();
2648 return nullptr;
2649 }
2650
RequestInputEvents(PP_Instance instance,uint32_t event_classes)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);
2657 }
2658
RequestFilteringInputEvents(PP_Instance instance,uint32_t 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);
2666 }
2667
ClearInputEventRequest(PP_Instance instance,uint32_t 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);
2673 }
2674
PostMessage(PP_Instance instance,PP_Var message)2675 void PepperPluginInstanceImpl::PostMessage(PP_Instance instance,
2676 PP_Var message) {
2677 PostMessageToJavaScript(message);
2678 }
2679
SetCursor(PP_Instance instance,PP_MouseCursor_Type type,PP_Resource image,const PP_Point * hot_spot)2680 PP_Bool PepperPluginInstanceImpl::SetCursor(PP_Instance instance,
2681 PP_MouseCursor_Type type,
2682 PP_Resource image,
2683 const PP_Point* hot_spot) {
2684 if (!ValidateSetCursorParams(type, image, hot_spot))
2685 return PP_FALSE;
2686
2687 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2688 DoSetCursor(
2689 std::make_unique<ui::Cursor>(static_cast<ui::mojom::CursorType>(type)));
2690 return PP_TRUE;
2691 }
2692
2693 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2694 if (enter.failed())
2695 return PP_FALSE;
2696 PPB_ImageData_Impl* image_data =
2697 static_cast<PPB_ImageData_Impl*>(enter.object());
2698
2699 ImageDataAutoMapper auto_mapper(image_data);
2700 if (!auto_mapper.is_valid())
2701 return PP_FALSE;
2702
2703 auto custom_cursor =
2704 std::make_unique<ui::Cursor>(ui::mojom::CursorType::kCustom);
2705 custom_cursor->set_custom_hotspot(gfx::Point(hot_spot->x, hot_spot->y));
2706
2707 SkBitmap bitmap(image_data->GetMappedBitmap());
2708 // Make a deep copy, so that the cursor remains valid even after the original
2709 // image data gets freed.
2710 SkBitmap dst = GetCursorBitmap(*custom_cursor);
2711 if (!dst.tryAllocPixels(bitmap.info()) ||
2712 !bitmap.readPixels(dst.info(), dst.getPixels(), dst.rowBytes(), 0, 0)) {
2713 return PP_FALSE;
2714 }
2715 custom_cursor->set_custom_bitmap(dst);
2716
2717 DoSetCursor(std::move(custom_cursor));
2718 return PP_TRUE;
2719 }
2720
LockMouse(PP_Instance instance,scoped_refptr<TrackedCallback> callback)2721 int32_t PepperPluginInstanceImpl::LockMouse(
2722 PP_Instance instance,
2723 scoped_refptr<TrackedCallback> callback) {
2724 if (TrackedCallback::IsPending(lock_mouse_callback_))
2725 return PP_ERROR_INPROGRESS;
2726
2727 if (IsMouseLocked())
2728 return PP_OK;
2729
2730 if (!CanAccessMainFrame())
2731 return PP_ERROR_NOACCESS;
2732
2733 if (!HasTransientUserActivation())
2734 return PP_ERROR_NO_USER_GESTURE;
2735
2736 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2737 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2738 if (!FlashIsFullscreenOrPending() || flash_fullscreen_) {
2739 if (!LockMouse(false))
2740 return PP_ERROR_FAILED;
2741 }
2742
2743 // Either mouselock succeeded or a Flash fullscreen is pending.
2744 lock_mouse_callback_ = callback;
2745 return PP_OK_COMPLETIONPENDING;
2746 }
2747
UnlockMouse(PP_Instance instance)2748 void PepperPluginInstanceImpl::UnlockMouse(PP_Instance instance) {
2749 GetMouseLockDispatcher()->UnlockMouse(GetOrCreateLockTargetAdapter());
2750 }
2751
SetTextInputType(PP_Instance instance,PP_TextInput_Type type)2752 void PepperPluginInstanceImpl::SetTextInputType(PP_Instance instance,
2753 PP_TextInput_Type type) {
2754 if (!render_frame_)
2755 return;
2756 int itype = type;
2757 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2758 itype = ui::TEXT_INPUT_TYPE_NONE;
2759 SetTextInputType(static_cast<ui::TextInputType>(itype));
2760 }
2761
UpdateCaretPosition(PP_Instance instance,const PP_Rect & caret,const PP_Rect & bounding_box)2762 void PepperPluginInstanceImpl::UpdateCaretPosition(
2763 PP_Instance instance,
2764 const PP_Rect& caret,
2765 const PP_Rect& bounding_box) {
2766 if (!render_frame_)
2767 return;
2768 TextInputCaretInfo info = {PP_ToGfxRect(caret), PP_ToGfxRect(bounding_box)};
2769 text_input_caret_info_ = std::move(info);
2770 render_frame_->PepperCaretPositionChanged(this);
2771 }
2772
CancelCompositionText(PP_Instance instance)2773 void PepperPluginInstanceImpl::CancelCompositionText(PP_Instance instance) {
2774 if (render_frame_)
2775 render_frame_->PepperCancelComposition(this);
2776 }
2777
SelectionChanged(PP_Instance instance)2778 void PepperPluginInstanceImpl::SelectionChanged(PP_Instance instance) {
2779 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2780 // It can be optimized so that it won't call it back until the information
2781 // is really needed.
2782
2783 // Avoid calling in nested context or else this will reenter the plugin. This
2784 // uses a weak pointer rather than exploiting the fact that this class is
2785 // refcounted because we don't actually want this operation to affect the
2786 // lifetime of the instance.
2787 base::ThreadTaskRunnerHandle::Get()->PostTask(
2788 FROM_HERE,
2789 base::BindOnce(&PepperPluginInstanceImpl::RequestSurroundingText,
2790 weak_factory_.GetWeakPtr(),
2791 static_cast<size_t>(kExtraCharsForTextInput)));
2792 }
2793
UpdateSurroundingText(PP_Instance instance,const char * text,uint32_t caret,uint32_t anchor)2794 void PepperPluginInstanceImpl::UpdateSurroundingText(PP_Instance instance,
2795 const char* text,
2796 uint32_t caret,
2797 uint32_t anchor) {
2798 if (!render_frame_)
2799 return;
2800 surrounding_text_ = text;
2801 selection_caret_ = caret;
2802 selection_anchor_ = anchor;
2803 render_frame_->PepperSelectionChanged(this);
2804 }
2805
ResolveRelativeToDocument(PP_Instance instance,PP_Var relative,PP_URLComponents_Dev * components)2806 PP_Var PepperPluginInstanceImpl::ResolveRelativeToDocument(
2807 PP_Instance instance,
2808 PP_Var relative,
2809 PP_URLComponents_Dev* components) {
2810 StringVar* relative_string = StringVar::FromPPVar(relative);
2811 if (!relative_string)
2812 return PP_MakeNull();
2813
2814 GURL document_url = container()->GetDocument().BaseURL();
2815 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2816 document_url.Resolve(relative_string->value()), components);
2817 }
2818
DocumentCanRequest(PP_Instance instance,PP_Var url)2819 PP_Bool PepperPluginInstanceImpl::DocumentCanRequest(PP_Instance instance,
2820 PP_Var url) {
2821 StringVar* url_string = StringVar::FromPPVar(url);
2822 if (!url_string)
2823 return PP_FALSE;
2824
2825 blink::WebSecurityOrigin security_origin;
2826 if (!SecurityOriginForInstance(instance, &security_origin))
2827 return PP_FALSE;
2828
2829 GURL gurl(url_string->value());
2830 if (!gurl.is_valid())
2831 return PP_FALSE;
2832
2833 return PP_FromBool(security_origin.CanRequest(gurl));
2834 }
2835
DocumentCanAccessDocument(PP_Instance instance,PP_Instance target)2836 PP_Bool PepperPluginInstanceImpl::DocumentCanAccessDocument(
2837 PP_Instance instance,
2838 PP_Instance target) {
2839 blink::WebSecurityOrigin our_origin;
2840 if (!SecurityOriginForInstance(instance, &our_origin))
2841 return PP_FALSE;
2842
2843 blink::WebSecurityOrigin target_origin;
2844 if (!SecurityOriginForInstance(instance, &target_origin))
2845 return PP_FALSE;
2846
2847 return PP_FromBool(our_origin.CanAccess(target_origin));
2848 }
2849
GetDocumentURL(PP_Instance instance,PP_URLComponents_Dev * components)2850 PP_Var PepperPluginInstanceImpl::GetDocumentURL(
2851 PP_Instance instance,
2852 PP_URLComponents_Dev* components) {
2853 blink::WebDocument document = container()->GetDocument();
2854 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.Url(),
2855 components);
2856 }
2857
GetPluginInstanceURL(PP_Instance instance,PP_URLComponents_Dev * components)2858 PP_Var PepperPluginInstanceImpl::GetPluginInstanceURL(
2859 PP_Instance instance,
2860 PP_URLComponents_Dev* components) {
2861 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_, components);
2862 }
2863
GetPluginReferrerURL(PP_Instance instance,PP_URLComponents_Dev * components)2864 PP_Var PepperPluginInstanceImpl::GetPluginReferrerURL(
2865 PP_Instance instance,
2866 PP_URLComponents_Dev* components) {
2867 blink::WebDocument document = container()->GetDocument();
2868 if (!full_frame_)
2869 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.Url(),
2870 components);
2871 WebLocalFrame* frame = document.GetFrame();
2872 if (!frame)
2873 return PP_MakeUndefined();
2874 WebString referer = frame->GetDocumentLoader()->OriginalReferrer();
2875 if (referer.IsEmpty())
2876 return PP_MakeUndefined();
2877 return ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2878 blink::WebStringToGURL(referer), components);
2879 }
2880
ResetAsProxied(scoped_refptr<PluginModule> module)2881 PP_ExternalPluginResult PepperPluginInstanceImpl::ResetAsProxied(
2882 scoped_refptr<PluginModule> module) {
2883 // Save the original module and switch over to the new one now that this
2884 // plugin is using the IPC-based proxy.
2885 original_module_ = module_;
2886 module_ = module;
2887
2888 // For NaCl instances, remember the NaCl plugin instance interface, so we
2889 // can shut it down by calling its DidDestroy in our Delete() method.
2890 original_instance_interface_ = std::move(instance_interface_);
2891
2892 base::RepeatingCallback<const void*(const char*)> get_plugin_interface_func =
2893 base::BindRepeating(&PluginModule::GetPluginInterface, module_);
2894 PPP_Instance_Combined* ppp_instance_combined =
2895 PPP_Instance_Combined::Create(std::move(get_plugin_interface_func));
2896 if (!ppp_instance_combined) {
2897 // The proxy must support at least one usable PPP_Instance interface.
2898 // While this could be a failure to implement the interface in the NaCl
2899 // module, it is more likely that the NaCl process has crashed. Either
2900 // way, report that module initialization failed.
2901 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2902 }
2903
2904 instance_interface_.reset(ppp_instance_combined);
2905 // Clear all PPP interfaces we may have cached.
2906 plugin_find_interface_ = nullptr;
2907 plugin_input_event_interface_ = nullptr;
2908 checked_for_plugin_input_event_interface_ = false;
2909 plugin_mouse_lock_interface_ = nullptr;
2910 plugin_pdf_interface_ = nullptr;
2911 checked_for_plugin_pdf_interface_ = false;
2912 plugin_private_interface_ = nullptr;
2913 plugin_textinput_interface_ = nullptr;
2914
2915 // Re-send the DidCreate event via the proxy.
2916 std::unique_ptr<const char* []> argn_array(StringVectorToArgArray(argn_));
2917 std::unique_ptr<const char* []> argv_array(StringVectorToArgArray(argv_));
2918 if (!instance_interface_->DidCreate(
2919 pp_instance(), argn_.size(), argn_array.get(), argv_array.get()))
2920 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2921 if (message_channel_)
2922 message_channel_->Start();
2923
2924 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2925 // event. This way, SendDidChangeView will send the "current" view
2926 // immediately (before other events like HandleDocumentLoad).
2927 sent_initial_did_change_view_ = false;
2928 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2929 SendDidChangeView();
2930
2931 DCHECK(external_document_load_);
2932 external_document_load_ = false;
2933 if (!external_document_response_.IsNull()) {
2934 document_loader_ = nullptr;
2935 // Pass the response to the new proxy.
2936 HandleDocumentLoad(external_document_response_);
2937 external_document_response_ = blink::WebURLResponse();
2938 // Replay any document load events we've received to the real loader.
2939 external_document_loader_->ReplayReceivedData(document_loader_);
2940 external_document_loader_.reset();
2941 }
2942
2943 return PP_EXTERNAL_PLUGIN_OK;
2944 }
2945
IsValidInstanceOf(PluginModule * module)2946 bool PepperPluginInstanceImpl::IsValidInstanceOf(PluginModule* module) {
2947 DCHECK(module);
2948 return module == module_.get() || module == original_module_.get();
2949 }
2950
GetRenderFrame()2951 RenderFrame* PepperPluginInstanceImpl::GetRenderFrame() {
2952 return render_frame_;
2953 }
2954
GetContainer()2955 blink::WebPluginContainer* PepperPluginInstanceImpl::GetContainer() {
2956 return container_;
2957 }
2958
GetIsolate()2959 v8::Isolate* PepperPluginInstanceImpl::GetIsolate() {
2960 return isolate_;
2961 }
2962
GetVarTracker()2963 ppapi::VarTracker* PepperPluginInstanceImpl::GetVarTracker() {
2964 return HostGlobals::Get()->GetVarTracker();
2965 }
2966
GetPluginURL()2967 const GURL& PepperPluginInstanceImpl::GetPluginURL() { return plugin_url_; }
2968
GetModulePath()2969 base::FilePath PepperPluginInstanceImpl::GetModulePath() {
2970 return module_->path();
2971 }
2972
CreateImage(gfx::ImageSkia * source_image,float scale)2973 PP_Resource PepperPluginInstanceImpl::CreateImage(gfx::ImageSkia* source_image,
2974 float scale) {
2975 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(scale);
2976
2977 if (image_skia_rep.is_null() || image_skia_rep.scale() != scale)
2978 return 0;
2979
2980 scoped_refptr<PPB_ImageData_Impl> image_data(
2981 new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM));
2982 if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
2983 image_skia_rep.pixel_width(),
2984 image_skia_rep.pixel_height(),
2985 false)) {
2986 return 0;
2987 }
2988
2989 ImageDataAutoMapper mapper(image_data.get());
2990 if (!mapper.is_valid())
2991 return 0;
2992
2993 SkCanvas* canvas = image_data->GetCanvas();
2994 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
2995 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
2996 canvas->writePixels(image_skia_rep.GetBitmap(), 0, 0);
2997
2998 return image_data->GetReference();
2999 }
3000
SwitchToOutOfProcessProxy(const base::FilePath & file_path,ppapi::PpapiPermissions permissions,const IPC::ChannelHandle & channel_handle,base::ProcessId plugin_pid,int plugin_child_id)3001 PP_ExternalPluginResult PepperPluginInstanceImpl::SwitchToOutOfProcessProxy(
3002 const base::FilePath& file_path,
3003 ppapi::PpapiPermissions permissions,
3004 const IPC::ChannelHandle& channel_handle,
3005 base::ProcessId plugin_pid,
3006 int plugin_child_id) {
3007 // Create a new module for each instance of the external plugin that is using
3008 // the IPC based out-of-process proxy. We can't use the existing module,
3009 // because it is configured for the in-process plugin, and we must keep it
3010 // that way to allow the page to create other instances.
3011 scoped_refptr<PluginModule> external_plugin_module(
3012 module_->CreateModuleForExternalPluginInstance());
3013
3014 RendererPpapiHostImpl* renderer_ppapi_host =
3015 external_plugin_module->CreateOutOfProcessModule(
3016 render_frame_, file_path, permissions, channel_handle, plugin_pid,
3017 plugin_child_id, true,
3018 render_frame_->GetTaskRunner(blink::TaskType::kInternalDefault));
3019 if (!renderer_ppapi_host) {
3020 DLOG(ERROR) << "CreateExternalPluginModule() failed";
3021 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
3022 }
3023
3024 // Finally, switch the instance to the proxy.
3025 return external_plugin_module->InitAsProxiedExternalPlugin(this);
3026 }
3027
SetAlwaysOnTop(bool on_top)3028 void PepperPluginInstanceImpl::SetAlwaysOnTop(bool on_top) {
3029 always_on_top_ = on_top;
3030 }
3031
DoSetCursor(std::unique_ptr<ui::Cursor> cursor)3032 void PepperPluginInstanceImpl::DoSetCursor(std::unique_ptr<ui::Cursor> cursor) {
3033 cursor_ = std::move(cursor);
3034 if (fullscreen_container_)
3035 fullscreen_container_->PepperDidChangeCursor(*cursor_);
3036 else if (render_frame_)
3037 render_frame_->PepperDidChangeCursor(this, *cursor_);
3038 }
3039
IsFullPagePlugin()3040 bool PepperPluginInstanceImpl::IsFullPagePlugin() {
3041 WebLocalFrame* frame = container()->GetDocument().GetFrame();
3042 return frame->View()->MainFrame()->IsWebLocalFrame() &&
3043 frame->View()
3044 ->MainFrame()
3045 ->ToWebLocalFrame()
3046 ->GetDocument()
3047 .IsPluginDocument();
3048 }
3049
FlashSetFullscreen(bool fullscreen,bool delay_report)3050 bool PepperPluginInstanceImpl::FlashSetFullscreen(bool fullscreen,
3051 bool delay_report) {
3052 TRACE_EVENT0("ppapi", "PepperPluginInstanceImpl::FlashSetFullscreen");
3053 // Keep a reference on the stack. See NOTE above.
3054 scoped_refptr<PepperPluginInstanceImpl> ref(this);
3055
3056 // We check whether we are trying to switch to the state we're already going
3057 // to (i.e. if we're already switching to fullscreen but the fullscreen
3058 // container isn't ready yet, don't do anything more).
3059 if (fullscreen == FlashIsFullscreenOrPending())
3060 return true;
3061
3062 if (!SetFullscreenCommon(fullscreen))
3063 return false;
3064
3065 // Unbind current 2D or 3D graphics context.
3066 DVLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
3067 if (fullscreen) {
3068 DCHECK(!fullscreen_container_);
3069 fullscreen_container_ =
3070 render_frame_->CreatePepperFullscreenContainer(this);
3071 UpdateLayer(false);
3072 } else {
3073 DCHECK(fullscreen_container_);
3074 fullscreen_container_->Destroy();
3075 fullscreen_container_ = nullptr;
3076 UpdateFlashFullscreenState(false);
3077 if (!delay_report) {
3078 ReportGeometry();
3079 } else {
3080 base::ThreadTaskRunnerHandle::Get()->PostTask(
3081 FROM_HERE,
3082 base::BindOnce(&PepperPluginInstanceImpl::ReportGeometry, this));
3083 }
3084 }
3085
3086 return true;
3087 }
3088
IsRectTopmost(const gfx::Rect & rect)3089 bool PepperPluginInstanceImpl::IsRectTopmost(const gfx::Rect& rect) {
3090 if (flash_fullscreen_)
3091 return true;
3092
3093 return container_->IsRectTopmost(rect);
3094 }
3095
Navigate(const ppapi::URLRequestInfoData & request,const char * target,bool from_user_action)3096 int32_t PepperPluginInstanceImpl::Navigate(
3097 const ppapi::URLRequestInfoData& request,
3098 const char* target,
3099 bool from_user_action) {
3100 if (!container_)
3101 return PP_ERROR_FAILED;
3102
3103 WebDocument document = container_->GetDocument();
3104 WebLocalFrame* frame = document.GetFrame();
3105 if (!frame)
3106 return PP_ERROR_FAILED;
3107
3108 ppapi::URLRequestInfoData completed_request = request;
3109
3110 WebURLRequest web_request;
3111 if (!CreateWebURLRequest(
3112 pp_instance_, &completed_request, frame, &web_request)) {
3113 return PP_ERROR_FAILED;
3114 }
3115 web_request.SetSiteForCookies(document.SiteForCookies());
3116 if (HasTransientUserActivation())
3117 web_request.SetHasUserGesture(true);
3118
3119 GURL gurl(web_request.Url());
3120 if (gurl.SchemeIs(url::kJavaScriptScheme)) {
3121 // In imitation of the NPAPI implementation, only |target_frame == frame| is
3122 // allowed for security reasons.
3123 WebFrame* target_frame =
3124 frame->FindFrameByName(WebString::FromUTF8(target));
3125 if (target_frame != frame)
3126 return PP_ERROR_NOACCESS;
3127
3128 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
3129 // need that?
3130 WebString result = container_->ExecuteScriptURL(gurl, false);
3131 return result.IsNull() ? PP_ERROR_FAILED : PP_OK;
3132 }
3133
3134 // Only GETs and POSTs are supported.
3135 if (web_request.HttpMethod() != "GET" && web_request.HttpMethod() != "POST")
3136 return PP_ERROR_BADARGUMENT;
3137
3138 WebString target_str = WebString::FromUTF8(target);
3139 container_->LoadFrameRequest(web_request, target_str);
3140 return PP_OK;
3141 }
3142
MakePendingFileRefRendererHost(const base::FilePath & path)3143 int PepperPluginInstanceImpl::MakePendingFileRefRendererHost(
3144 const base::FilePath& path) {
3145 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3146 PepperFileRefRendererHost* file_ref_host(
3147 new PepperFileRefRendererHost(host_impl, pp_instance(), 0, path));
3148 return host_impl->GetPpapiHost()->AddPendingResourceHost(
3149 std::unique_ptr<ppapi::host::ResourceHost>(file_ref_host));
3150 }
3151
SetEmbedProperty(PP_Var key,PP_Var value)3152 void PepperPluginInstanceImpl::SetEmbedProperty(PP_Var key, PP_Var value) {
3153 if (message_channel_)
3154 message_channel_->SetReadOnlyProperty(key, value);
3155 }
3156
CanAccessMainFrame() const3157 bool PepperPluginInstanceImpl::CanAccessMainFrame() const {
3158 if (!container_)
3159 return false;
3160 blink::WebDocument containing_document = container_->GetDocument();
3161
3162 if (!containing_document.GetFrame() ||
3163 !containing_document.GetFrame()->View() ||
3164 !containing_document.GetFrame()->View()->MainFrame()) {
3165 return false;
3166 }
3167 blink::WebFrame* main_frame =
3168 containing_document.GetFrame()->View()->MainFrame();
3169
3170 return containing_document.GetSecurityOrigin().CanAccess(
3171 main_frame->GetSecurityOrigin());
3172 }
3173
KeepSizeAttributesBeforeFullscreen()3174 void PepperPluginInstanceImpl::KeepSizeAttributesBeforeFullscreen() {
3175 WebElement element = container_->GetElement();
3176 width_before_fullscreen_ = element.GetAttribute(WebString::FromUTF8(kWidth));
3177 height_before_fullscreen_ =
3178 element.GetAttribute(WebString::FromUTF8(kHeight));
3179 border_before_fullscreen_ =
3180 element.GetAttribute(WebString::FromUTF8(kBorder));
3181 style_before_fullscreen_ = element.GetAttribute(WebString::FromUTF8(kStyle));
3182 }
3183
SetSizeAttributesForFullscreen()3184 void PepperPluginInstanceImpl::SetSizeAttributesForFullscreen() {
3185 if (!render_frame_)
3186 return;
3187
3188 // TODO(miu): Revisit this logic. If the style must be modified for correct
3189 // behavior, the width and height should probably be set to 100%, rather than
3190 // a fixed screen size.
3191
3192 blink::WebScreenInfo info =
3193 render_frame_->GetLocalRootRenderWidget()->GetScreenInfo();
3194 screen_size_for_fullscreen_ = gfx::Size(info.rect.width, info.rect.height);
3195 std::string width = base::NumberToString(screen_size_for_fullscreen_.width());
3196 std::string height =
3197 base::NumberToString(screen_size_for_fullscreen_.height());
3198
3199 WebElement element = container_->GetElement();
3200 element.SetAttribute(WebString::FromUTF8(kWidth), WebString::FromUTF8(width));
3201 element.SetAttribute(WebString::FromUTF8(kHeight),
3202 WebString::FromUTF8(height));
3203 element.SetAttribute(WebString::FromUTF8(kBorder), WebString::FromUTF8("0"));
3204
3205 // There should be no style settings that matter in fullscreen mode,
3206 // so just replace them instead of appending.
3207 // NOTE: "position: fixed" and "display: block" reset the plugin and
3208 // using %% settings might not work without them (e.g. if the plugin is a
3209 // child of a container element).
3210 std::string style;
3211 style += StringPrintf("width: %s !important; ", width.c_str());
3212 style += StringPrintf("height: %s !important; ", height.c_str());
3213 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
3214 container_->GetElement().SetAttribute(kStyle, WebString::FromUTF8(style));
3215 }
3216
ResetSizeAttributesAfterFullscreen()3217 void PepperPluginInstanceImpl::ResetSizeAttributesAfterFullscreen() {
3218 screen_size_for_fullscreen_ = gfx::Size();
3219 WebElement element = container_->GetElement();
3220 element.SetAttribute(WebString::FromUTF8(kWidth), width_before_fullscreen_);
3221 element.SetAttribute(WebString::FromUTF8(kHeight), height_before_fullscreen_);
3222 element.SetAttribute(WebString::FromUTF8(kBorder), border_before_fullscreen_);
3223 element.SetAttribute(WebString::FromUTF8(kStyle), style_before_fullscreen_);
3224 }
3225
SetFullscreenCommon(bool fullscreen) const3226 bool PepperPluginInstanceImpl::SetFullscreenCommon(bool fullscreen) const {
3227 if (!render_frame_)
3228 return false;
3229
3230 if (fullscreen) {
3231 if (!render_frame_->render_view()
3232 ->renderer_preferences()
3233 .plugin_fullscreen_allowed) {
3234 return false;
3235 }
3236
3237 if (!HasTransientUserActivation())
3238 return false;
3239 }
3240 return true;
3241 }
3242
IsMouseLocked()3243 bool PepperPluginInstanceImpl::IsMouseLocked() {
3244 return GetMouseLockDispatcher()->IsMouseLockedTo(
3245 GetOrCreateLockTargetAdapter());
3246 }
3247
LockMouse(bool request_unadjusted_movement)3248 bool PepperPluginInstanceImpl::LockMouse(bool request_unadjusted_movement) {
3249 WebLocalFrame* requester_frame = container_->GetDocument().GetFrame();
3250 return GetMouseLockDispatcher()->LockMouse(
3251 GetOrCreateLockTargetAdapter(), requester_frame,
3252 base::OnceCallback<void(blink::mojom::PointerLockResult)>(),
3253 request_unadjusted_movement);
3254 }
3255
3256 MouseLockDispatcher::LockTarget*
GetOrCreateLockTargetAdapter()3257 PepperPluginInstanceImpl::GetOrCreateLockTargetAdapter() {
3258 if (!lock_target_)
3259 lock_target_ = std::make_unique<PluginInstanceLockTarget>(this);
3260 return lock_target_.get();
3261 }
3262
GetMouseLockDispatcher()3263 MouseLockDispatcher* PepperPluginInstanceImpl::GetMouseLockDispatcher() {
3264 if (flash_fullscreen_) {
3265 RenderWidgetFullscreenPepper* container =
3266 static_cast<RenderWidgetFullscreenPepper*>(fullscreen_container_);
3267 return container->mouse_lock_dispatcher();
3268 }
3269 if (render_frame_)
3270 return render_frame_->GetLocalRootRenderWidget()->mouse_lock_dispatcher();
3271 return nullptr;
3272 }
3273
UnSetAndDeleteLockTargetAdapter()3274 void PepperPluginInstanceImpl::UnSetAndDeleteLockTargetAdapter() {
3275 if (lock_target_) {
3276 GetMouseLockDispatcher()->OnLockTargetDestroyed(lock_target_.get());
3277 lock_target_.reset();
3278 }
3279 }
3280
DidDataFromWebURLResponse(const blink::WebURLResponse & response,int pending_host_id,const ppapi::URLResponseInfoData & data)3281 void PepperPluginInstanceImpl::DidDataFromWebURLResponse(
3282 const blink::WebURLResponse& response,
3283 int pending_host_id,
3284 const ppapi::URLResponseInfoData& data) {
3285 if (is_deleted_)
3286 return;
3287
3288 RendererPpapiHostImpl* host_impl = module_->renderer_ppapi_host();
3289
3290 if (host_impl->in_process_router()) {
3291 // Running in-process, we can just create the resource and call the
3292 // PPP_Instance function directly.
3293 scoped_refptr<ppapi::proxy::URLLoaderResource> loader_resource(
3294 new ppapi::proxy::URLLoaderResource(
3295 host_impl->in_process_router()->GetPluginConnection(pp_instance()),
3296 pp_instance(),
3297 pending_host_id,
3298 data));
3299
3300 PP_Resource loader_pp_resource = loader_resource->GetReference();
3301 if (!instance_interface_->HandleDocumentLoad(pp_instance(),
3302 loader_pp_resource))
3303 loader_resource->Close();
3304 // We don't pass a ref into the plugin, if it wants one, it will have taken
3305 // an additional one.
3306 ppapi::PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(
3307 loader_pp_resource);
3308 } else {
3309 // Running out-of-process. Initiate an IPC call to notify the plugin
3310 // process.
3311 ppapi::proxy::HostDispatcher* dispatcher =
3312 ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
3313 dispatcher->Send(new PpapiMsg_PPPInstance_HandleDocumentLoad(
3314 ppapi::API_ID_PPP_INSTANCE, pp_instance(), pending_host_id, data));
3315 }
3316 }
3317
ConvertRectToDIP(PP_Rect * rect) const3318 void PepperPluginInstanceImpl::ConvertRectToDIP(PP_Rect* rect) const {
3319 rect->point.x *= viewport_to_dip_scale_;
3320 rect->point.y *= viewport_to_dip_scale_;
3321 rect->size.width *= viewport_to_dip_scale_;
3322 rect->size.height *= viewport_to_dip_scale_;
3323 }
3324
ConvertDIPToViewport(gfx::Rect * rect) const3325 void PepperPluginInstanceImpl::ConvertDIPToViewport(gfx::Rect* rect) const {
3326 rect->set_x(rect->x() / viewport_to_dip_scale_);
3327 rect->set_y(rect->y() / viewport_to_dip_scale_);
3328 rect->set_width(rect->width() / viewport_to_dip_scale_);
3329 rect->set_height(rect->height() / viewport_to_dip_scale_);
3330 }
3331
IncrementTextureReferenceCount(const viz::TransferableResource & resource)3332 void PepperPluginInstanceImpl::IncrementTextureReferenceCount(
3333 const viz::TransferableResource& resource) {
3334 auto it =
3335 std::find_if(texture_ref_counts_.begin(), texture_ref_counts_.end(),
3336 [&resource](const MailboxRefCount& ref_count) {
3337 return ref_count.first == resource.mailbox_holder.mailbox;
3338 });
3339 if (it == texture_ref_counts_.end()) {
3340 texture_ref_counts_.emplace_back(resource.mailbox_holder.mailbox, 1);
3341 return;
3342 }
3343
3344 it->second++;
3345 }
3346
DecrementTextureReferenceCount(const viz::TransferableResource & resource)3347 bool PepperPluginInstanceImpl::DecrementTextureReferenceCount(
3348 const viz::TransferableResource& resource) {
3349 auto it =
3350 std::find_if(texture_ref_counts_.begin(), texture_ref_counts_.end(),
3351 [&resource](const MailboxRefCount& ref_count) {
3352 return ref_count.first == resource.mailbox_holder.mailbox;
3353 });
3354 DCHECK(it != texture_ref_counts_.end());
3355
3356 if (it->second == 1) {
3357 texture_ref_counts_.erase(it);
3358 return true;
3359 }
3360
3361 it->second--;
3362 return false;
3363 }
3364
IsTextureInUse(const viz::TransferableResource & resource) const3365 bool PepperPluginInstanceImpl::IsTextureInUse(
3366 const viz::TransferableResource& resource) const {
3367 auto it =
3368 std::find_if(texture_ref_counts_.begin(), texture_ref_counts_.end(),
3369 [&resource](const MailboxRefCount& ref_count) {
3370 return ref_count.first == resource.mailbox_holder.mailbox;
3371 });
3372 return it != texture_ref_counts_.end();
3373 }
3374
HandleAccessibilityChange()3375 void PepperPluginInstanceImpl::HandleAccessibilityChange() {
3376 if (render_frame_ && render_frame_->GetRenderAccessibility() &&
3377 LoadPdfInterface()) {
3378 plugin_pdf_interface_->EnableAccessibility(pp_instance());
3379 }
3380 }
3381
3382 } // namespace content
3383