Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(23)

Side by Side Diff: webkit/plugins/ppapi/ppapi_plugin_instance.cc

Issue 19744007: Create a public API around webkit::ppapi::PluginInstance and use it in chrome. After this, webkit/p… (Closed) Base URL: svn://chrome-svn/chrome/trunk/src/
Patch Set: Created 7 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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 "webkit/plugins/ppapi/ppapi_plugin_instance.h"
6
7 #include "base/bind.h"
8 #include "base/callback_helpers.h"
9 #include "base/debug/trace_event.h"
10 #include "base/logging.h"
11 #include "base/memory/linked_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/stl_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_offset_string_conversions.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/time/time.h"
18 #include "cc/layers/texture_layer.h"
19 #include "ppapi/c/dev/ppb_find_dev.h"
20 #include "ppapi/c/dev/ppb_zoom_dev.h"
21 #include "ppapi/c/dev/ppp_find_dev.h"
22 #include "ppapi/c/dev/ppp_selection_dev.h"
23 #include "ppapi/c/dev/ppp_text_input_dev.h"
24 #include "ppapi/c/dev/ppp_zoom_dev.h"
25 #include "ppapi/c/pp_rect.h"
26 #include "ppapi/c/ppb_audio_config.h"
27 #include "ppapi/c/ppb_core.h"
28 #include "ppapi/c/ppb_gamepad.h"
29 #include "ppapi/c/ppp_input_event.h"
30 #include "ppapi/c/ppp_instance.h"
31 #include "ppapi/c/ppp_messaging.h"
32 #include "ppapi/c/ppp_mouse_lock.h"
33 #include "ppapi/c/private/ppp_instance_private.h"
34 #include "ppapi/shared_impl/ppapi_permissions.h"
35 #include "ppapi/shared_impl/ppapi_preferences.h"
36 #include "ppapi/shared_impl/ppb_gamepad_shared.h"
37 #include "ppapi/shared_impl/ppb_input_event_shared.h"
38 #include "ppapi/shared_impl/ppb_url_util_shared.h"
39 #include "ppapi/shared_impl/ppb_view_shared.h"
40 #include "ppapi/shared_impl/ppp_instance_combined.h"
41 #include "ppapi/shared_impl/resource.h"
42 #include "ppapi/shared_impl/scoped_pp_resource.h"
43 #include "ppapi/shared_impl/time_conversion.h"
44 #include "ppapi/shared_impl/url_request_info_data.h"
45 #include "ppapi/shared_impl/var.h"
46 #include "ppapi/thunk/enter.h"
47 #include "ppapi/thunk/ppb_buffer_api.h"
48 #include "printing/metafile.h"
49 #include "printing/metafile_skia_wrapper.h"
50 #include "printing/units.h"
51 #include "skia/ext/platform_canvas.h"
52 #include "skia/ext/platform_device.h"
53 #include "third_party/WebKit/public/platform/WebGamepads.h"
54 #include "third_party/WebKit/public/platform/WebString.h"
55 #include "third_party/WebKit/public/platform/WebURL.h"
56 #include "third_party/WebKit/public/platform/WebURLError.h"
57 #include "third_party/WebKit/public/platform/WebURLRequest.h"
58 #include "third_party/WebKit/public/web/WebBindings.h"
59 #include "third_party/WebKit/public/web/WebCompositionUnderline.h"
60 #include "third_party/WebKit/public/web/WebCursorInfo.h"
61 #include "third_party/WebKit/public/web/WebDocument.h"
62 #include "third_party/WebKit/public/web/WebElement.h"
63 #include "third_party/WebKit/public/web/WebFrame.h"
64 #include "third_party/WebKit/public/web/WebInputEvent.h"
65 #include "third_party/WebKit/public/web/WebPluginContainer.h"
66 #include "third_party/WebKit/public/web/WebPrintParams.h"
67 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
68 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
69 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
70 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
71 #include "third_party/WebKit/public/web/WebView.h"
72 #include "third_party/skia/include/core/SkCanvas.h"
73 #include "third_party/skia/include/core/SkRect.h"
74 #include "ui/base/range/range.h"
75 #include "ui/gfx/image/image_skia.h"
76 #include "ui/gfx/image/image_skia_rep.h"
77 #include "ui/gfx/rect_conversions.h"
78 #include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h"
79 #include "v8/include/v8.h"
80 #include "webkit/plugins/plugin_constants.h"
81 #include "webkit/plugins/ppapi/common.h"
82 #include "webkit/plugins/ppapi/content_decryptor_delegate.h"
83 #include "webkit/plugins/ppapi/event_conversion.h"
84 #include "webkit/plugins/ppapi/fullscreen_container.h"
85 #include "webkit/plugins/ppapi/gfx_conversion.h"
86 #include "webkit/plugins/ppapi/host_globals.h"
87 #include "webkit/plugins/ppapi/message_channel.h"
88 #include "webkit/plugins/ppapi/npapi_glue.h"
89 #include "webkit/plugins/ppapi/plugin_module.h"
90 #include "webkit/plugins/ppapi/plugin_object.h"
91 #include "webkit/plugins/ppapi/ppb_buffer_impl.h"
92 #include "webkit/plugins/ppapi/ppb_file_ref_impl.h"
93 #include "webkit/plugins/ppapi/ppb_graphics_3d_impl.h"
94 #include "webkit/plugins/ppapi/ppb_image_data_impl.h"
95 #include "webkit/plugins/ppapi/ppp_pdf.h"
96 #include "webkit/plugins/ppapi/url_request_info_util.h"
97 #include "webkit/plugins/sad_plugin.h"
98 #include "webkit/renderer/compositor_bindings/web_layer_impl.h"
99
100 #if defined(OS_MACOSX)
101 #include "printing/metafile_impl.h"
102 #endif // defined(OS_MACOSX)
103
104 #if defined(OS_WIN)
105 #include "base/metrics/histogram.h"
106 #include "base/win/windows_version.h"
107 #include "skia/ext/platform_canvas.h"
108 #include "ui/gfx/codec/jpeg_codec.h"
109 #include "ui/gfx/gdi_util.h"
110 #endif
111
112 using base::StringPrintf;
113 using ppapi::InputEventData;
114 using ppapi::PpapiGlobals;
115 using ppapi::PPB_InputEvent_Shared;
116 using ppapi::PPB_View_Shared;
117 using ppapi::PPP_Instance_Combined;
118 using ppapi::Resource;
119 using ppapi::ScopedPPResource;
120 using ppapi::StringVar;
121 using ppapi::TrackedCallback;
122 using ppapi::thunk::EnterResourceNoLock;
123 using ppapi::thunk::PPB_Buffer_API;
124 using ppapi::thunk::PPB_Gamepad_API;
125 using ppapi::thunk::PPB_Graphics2D_API;
126 using ppapi::thunk::PPB_Graphics3D_API;
127 using ppapi::thunk::PPB_ImageData_API;
128 using ppapi::Var;
129 using ppapi::ArrayBufferVar;
130 using ppapi::ViewData;
131 using WebKit::WebBindings;
132 using WebKit::WebCanvas;
133 using WebKit::WebCursorInfo;
134 using WebKit::WebDocument;
135 using WebKit::WebElement;
136 using WebKit::WebFrame;
137 using WebKit::WebInputEvent;
138 using WebKit::WebPlugin;
139 using WebKit::WebPluginContainer;
140 using WebKit::WebPrintParams;
141 using WebKit::WebPrintScalingOption;
142 using WebKit::WebScopedUserGesture;
143 using WebKit::WebString;
144 using WebKit::WebURLError;
145 using WebKit::WebURLLoader;
146 using WebKit::WebURLLoaderClient;
147 using WebKit::WebURLRequest;
148 using WebKit::WebURLResponse;
149 using WebKit::WebUserGestureIndicator;
150 using WebKit::WebUserGestureToken;
151 using WebKit::WebView;
152
153 namespace webkit {
154 namespace ppapi {
155
156 #if defined(OS_WIN)
157 // Exported by pdf.dll
158 typedef bool (*RenderPDFPageToDCProc)(
159 const unsigned char* pdf_buffer, int buffer_size, int page_number, HDC dc,
160 int dpi_x, int dpi_y, int bounds_origin_x, int bounds_origin_y,
161 int bounds_width, int bounds_height, bool fit_to_bounds,
162 bool stretch_to_bounds, bool keep_aspect_ratio, bool center_in_bounds,
163 bool autorotate);
164
165 void DrawEmptyRectangle(HDC dc) {
166 // TODO(sanjeevr): This is a temporary hack. If we output a JPEG
167 // to the EMF, the EnumEnhMetaFile call fails in the browser
168 // process. The failure also happens if we output nothing here.
169 // We need to investigate the reason for this failure and fix it.
170 // In the meantime this temporary hack of drawing an empty
171 // rectangle in the DC gets us by.
172 Rectangle(dc, 0, 0, 0, 0);
173 }
174 #endif // defined(OS_WIN)
175
176 namespace {
177
178 // Check PP_TextInput_Type and ui::TextInputType are kept in sync.
179 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NONE) == \
180 int(PP_TEXTINPUT_TYPE_NONE), mismatching_enums);
181 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TEXT) == \
182 int(PP_TEXTINPUT_TYPE_TEXT), mismatching_enums);
183 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_PASSWORD) == \
184 int(PP_TEXTINPUT_TYPE_PASSWORD), mismatching_enums);
185 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_SEARCH) == \
186 int(PP_TEXTINPUT_TYPE_SEARCH), mismatching_enums);
187 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_EMAIL) == \
188 int(PP_TEXTINPUT_TYPE_EMAIL), mismatching_enums);
189 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NUMBER) == \
190 int(PP_TEXTINPUT_TYPE_NUMBER), mismatching_enums);
191 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TELEPHONE) == \
192 int(PP_TEXTINPUT_TYPE_TELEPHONE), mismatching_enums);
193 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_URL) == \
194 int(PP_TEXTINPUT_TYPE_URL), mismatching_enums);
195
196 // The default text input type is to regard the plugin always accept text input.
197 // This is for allowing users to use input methods even on completely-IME-
198 // unaware plugins (e.g., PPAPI Flash or PDF plugin for M16).
199 // Plugins need to explicitly opt out the text input mode if they know
200 // that they don't accept texts.
201 const ui::TextInputType kPluginDefaultTextInputType = ui::TEXT_INPUT_TYPE_TEXT;
202
203 #define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
204 COMPILE_ASSERT(static_cast<int>(WebCursorInfo::webkit_name) \
205 == static_cast<int>(np_name), \
206 mismatching_enums)
207
208 #define COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(webkit_name, pp_name) \
209 COMPILE_ASSERT(static_cast<int>(webkit_name) \
210 == static_cast<int>(pp_name), \
211 mismatching_enums)
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 COMPILE_ASSERT_MATCHING_ENUM(TypePointer, PP_MOUSECURSOR_TYPE_POINTER);
220 COMPILE_ASSERT_MATCHING_ENUM(TypeCross, PP_MOUSECURSOR_TYPE_CROSS);
221 COMPILE_ASSERT_MATCHING_ENUM(TypeHand, PP_MOUSECURSOR_TYPE_HAND);
222 COMPILE_ASSERT_MATCHING_ENUM(TypeIBeam, PP_MOUSECURSOR_TYPE_IBEAM);
223 COMPILE_ASSERT_MATCHING_ENUM(TypeWait, PP_MOUSECURSOR_TYPE_WAIT);
224 COMPILE_ASSERT_MATCHING_ENUM(TypeHelp, PP_MOUSECURSOR_TYPE_HELP);
225 COMPILE_ASSERT_MATCHING_ENUM(TypeEastResize, PP_MOUSECURSOR_TYPE_EASTRESIZE);
226 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthResize, PP_MOUSECURSOR_TYPE_NORTHRESIZE);
227 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastResize,
228 PP_MOUSECURSOR_TYPE_NORTHEASTRESIZE);
229 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestResize,
230 PP_MOUSECURSOR_TYPE_NORTHWESTRESIZE);
231 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthResize, PP_MOUSECURSOR_TYPE_SOUTHRESIZE);
232 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastResize,
233 PP_MOUSECURSOR_TYPE_SOUTHEASTRESIZE);
234 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestResize,
235 PP_MOUSECURSOR_TYPE_SOUTHWESTRESIZE);
236 COMPILE_ASSERT_MATCHING_ENUM(TypeWestResize, PP_MOUSECURSOR_TYPE_WESTRESIZE);
237 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
238 PP_MOUSECURSOR_TYPE_NORTHSOUTHRESIZE);
239 COMPILE_ASSERT_MATCHING_ENUM(TypeEastWestResize,
240 PP_MOUSECURSOR_TYPE_EASTWESTRESIZE);
241 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
242 PP_MOUSECURSOR_TYPE_NORTHEASTSOUTHWESTRESIZE);
243 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
244 PP_MOUSECURSOR_TYPE_NORTHWESTSOUTHEASTRESIZE);
245 COMPILE_ASSERT_MATCHING_ENUM(TypeColumnResize,
246 PP_MOUSECURSOR_TYPE_COLUMNRESIZE);
247 COMPILE_ASSERT_MATCHING_ENUM(TypeRowResize, PP_MOUSECURSOR_TYPE_ROWRESIZE);
248 COMPILE_ASSERT_MATCHING_ENUM(TypeMiddlePanning,
249 PP_MOUSECURSOR_TYPE_MIDDLEPANNING);
250 COMPILE_ASSERT_MATCHING_ENUM(TypeEastPanning, PP_MOUSECURSOR_TYPE_EASTPANNING);
251 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthPanning,
252 PP_MOUSECURSOR_TYPE_NORTHPANNING);
253 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
254 PP_MOUSECURSOR_TYPE_NORTHEASTPANNING);
255 COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
256 PP_MOUSECURSOR_TYPE_NORTHWESTPANNING);
257 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthPanning,
258 PP_MOUSECURSOR_TYPE_SOUTHPANNING);
259 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
260 PP_MOUSECURSOR_TYPE_SOUTHEASTPANNING);
261 COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
262 PP_MOUSECURSOR_TYPE_SOUTHWESTPANNING);
263 COMPILE_ASSERT_MATCHING_ENUM(TypeWestPanning, PP_MOUSECURSOR_TYPE_WESTPANNING);
264 COMPILE_ASSERT_MATCHING_ENUM(TypeMove, PP_MOUSECURSOR_TYPE_MOVE);
265 COMPILE_ASSERT_MATCHING_ENUM(TypeVerticalText,
266 PP_MOUSECURSOR_TYPE_VERTICALTEXT);
267 COMPILE_ASSERT_MATCHING_ENUM(TypeCell, PP_MOUSECURSOR_TYPE_CELL);
268 COMPILE_ASSERT_MATCHING_ENUM(TypeContextMenu, PP_MOUSECURSOR_TYPE_CONTEXTMENU);
269 COMPILE_ASSERT_MATCHING_ENUM(TypeAlias, PP_MOUSECURSOR_TYPE_ALIAS);
270 COMPILE_ASSERT_MATCHING_ENUM(TypeProgress, PP_MOUSECURSOR_TYPE_PROGRESS);
271 COMPILE_ASSERT_MATCHING_ENUM(TypeNoDrop, PP_MOUSECURSOR_TYPE_NODROP);
272 COMPILE_ASSERT_MATCHING_ENUM(TypeCopy, PP_MOUSECURSOR_TYPE_COPY);
273 COMPILE_ASSERT_MATCHING_ENUM(TypeNone, PP_MOUSECURSOR_TYPE_NONE);
274 COMPILE_ASSERT_MATCHING_ENUM(TypeNotAllowed, PP_MOUSECURSOR_TYPE_NOTALLOWED);
275 COMPILE_ASSERT_MATCHING_ENUM(TypeZoomIn, PP_MOUSECURSOR_TYPE_ZOOMIN);
276 COMPILE_ASSERT_MATCHING_ENUM(TypeZoomOut, PP_MOUSECURSOR_TYPE_ZOOMOUT);
277 COMPILE_ASSERT_MATCHING_ENUM(TypeGrab, PP_MOUSECURSOR_TYPE_GRAB);
278 COMPILE_ASSERT_MATCHING_ENUM(TypeGrabbing, PP_MOUSECURSOR_TYPE_GRABBING);
279 // Do not assert WebCursorInfo::TypeCustom == PP_CURSORTYPE_CUSTOM;
280 // PP_CURSORTYPE_CUSTOM is pinned to allow new cursor types.
281
282 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(WebKit::WebPrintScalingOptionNone,
283 PP_PRINTSCALINGOPTION_NONE);
284 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
285 WebKit::WebPrintScalingOptionFitToPrintableArea,
286 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
287 COMPILE_ASSERT_PRINT_SCALING_MATCHING_ENUM(
288 WebKit::WebPrintScalingOptionSourceSize, PP_PRINTSCALINGOPTION_SOURCE_SIZE);
289
290 // Sets |*security_origin| to be the WebKit security origin associated with the
291 // document containing the given plugin instance. On success, returns true. If
292 // the instance is invalid, returns false and |*security_origin| will be
293 // unchanged.
294 bool SecurityOriginForInstance(PP_Instance instance_id,
295 WebKit::WebSecurityOrigin* security_origin) {
296 PluginInstance* instance = HostGlobals::Get()->GetInstance(instance_id);
297 if (!instance)
298 return false;
299
300 WebElement plugin_element = instance->container()->element();
301 *security_origin = plugin_element.document().securityOrigin();
302 return true;
303 }
304
305 // Convert the given vector to an array of C-strings. The strings in the
306 // returned vector are only guaranteed valid so long as the vector of strings
307 // is not modified.
308 scoped_ptr<const char*[]> StringVectorToArgArray(
309 const std::vector<std::string>& vector) {
310 scoped_ptr<const char*[]> array(new const char*[vector.size()]);
311 for (size_t i = 0; i < vector.size(); ++i)
312 array[i] = vector[i].c_str();
313 return array.Pass();
314 }
315
316 } // namespace
317
318 // static
319 PluginInstance* PluginInstance::Create(PluginDelegate* delegate,
320 content::RenderView* render_view,
321 PluginModule* module,
322 WebPluginContainer* container,
323 const GURL& plugin_url) {
324 base::Callback<const void*(const char*)> get_plugin_interface_func =
325 base::Bind(&PluginModule::GetPluginInterface, module);
326 PPP_Instance_Combined* ppp_instance_combined =
327 PPP_Instance_Combined::Create(get_plugin_interface_func);
328 if (!ppp_instance_combined)
329 return NULL;
330 return new PluginInstance(delegate, render_view, module,
331 ppp_instance_combined, container, plugin_url);
332 }
333
334 PluginInstance::NaClDocumentLoader::NaClDocumentLoader()
335 : finished_loading_(false) {
336 }
337
338 PluginInstance::NaClDocumentLoader::~NaClDocumentLoader(){
339 }
340
341 void PluginInstance::NaClDocumentLoader::ReplayReceivedData(
342 WebURLLoaderClient* document_loader) {
343 for (std::list<std::string>::iterator it = data_.begin();
344 it != data_.end(); ++it) {
345 document_loader->didReceiveData(NULL, it->c_str(), it->length(),
346 0 /* encoded_data_length */);
347 }
348 if (finished_loading_) {
349 document_loader->didFinishLoading(NULL,
350 0 /* finish_time */);
351 }
352 if (error_.get()) {
353 document_loader->didFail(NULL, *error_);
354 }
355 }
356
357 void PluginInstance::NaClDocumentLoader::didReceiveData(
358 WebURLLoader* loader,
359 const char* data,
360 int data_length,
361 int encoded_data_length) {
362 data_.push_back(std::string(data, data_length));
363 }
364
365 void PluginInstance::NaClDocumentLoader::didFinishLoading(
366 WebURLLoader* loader,
367 double finish_time) {
368 DCHECK(!finished_loading_);
369 finished_loading_ = true;
370 }
371
372 void PluginInstance::NaClDocumentLoader::didFail(
373 WebURLLoader* loader,
374 const WebURLError& error) {
375 DCHECK(!error_.get());
376 error_.reset(new WebURLError(error));
377 }
378
379 PluginInstance::GamepadImpl::GamepadImpl(PluginDelegate* delegate)
380 : Resource(::ppapi::Resource::Untracked()),
381 delegate_(delegate) {
382 }
383
384 PPB_Gamepad_API* PluginInstance::GamepadImpl::AsPPB_Gamepad_API() {
385 return this;
386 }
387
388 void PluginInstance::GamepadImpl::Sample(PP_Instance /* instance */,
389 PP_GamepadsSampleData* data) {
390 WebKit::WebGamepads webkit_data;
391 delegate_->SampleGamepads(&webkit_data);
392 ConvertWebKitGamepadData(
393 *reinterpret_cast<const ::ppapi::WebKitGamepads*>(&webkit_data), data);
394 }
395
396 PluginInstance::PluginInstance(
397 PluginDelegate* delegate,
398 content::RenderView* render_view,
399 PluginModule* module,
400 ::ppapi::PPP_Instance_Combined* instance_interface,
401 WebPluginContainer* container,
402 const GURL& plugin_url)
403 : delegate_(delegate),
404 render_view_(render_view),
405 module_(module),
406 instance_interface_(instance_interface),
407 pp_instance_(0),
408 container_(container),
409 layer_bound_to_fullscreen_(false),
410 plugin_url_(plugin_url),
411 full_frame_(false),
412 sent_initial_did_change_view_(false),
413 view_change_weak_ptr_factory_(this),
414 bound_graphics_2d_platform_(NULL),
415 has_webkit_focus_(false),
416 has_content_area_focus_(false),
417 find_identifier_(-1),
418 plugin_find_interface_(NULL),
419 plugin_input_event_interface_(NULL),
420 plugin_messaging_interface_(NULL),
421 plugin_mouse_lock_interface_(NULL),
422 plugin_pdf_interface_(NULL),
423 plugin_private_interface_(NULL),
424 plugin_selection_interface_(NULL),
425 plugin_textinput_interface_(NULL),
426 plugin_zoom_interface_(NULL),
427 checked_for_plugin_input_event_interface_(false),
428 checked_for_plugin_messaging_interface_(false),
429 checked_for_plugin_pdf_interface_(false),
430 gamepad_impl_(new GamepadImpl(delegate)),
431 plugin_print_interface_(NULL),
432 plugin_graphics_3d_interface_(NULL),
433 always_on_top_(false),
434 fullscreen_container_(NULL),
435 flash_fullscreen_(false),
436 desired_fullscreen_state_(false),
437 sad_plugin_(NULL),
438 input_event_mask_(0),
439 filtered_input_event_mask_(0),
440 text_input_type_(kPluginDefaultTextInputType),
441 text_input_caret_(0, 0, 0, 0),
442 text_input_caret_bounds_(0, 0, 0, 0),
443 text_input_caret_set_(false),
444 selection_caret_(0),
445 selection_anchor_(0),
446 pending_user_gesture_(0.0),
447 document_loader_(NULL),
448 nacl_document_load_(false),
449 npp_(new NPP_t),
450 isolate_(v8::Isolate::GetCurrent()) {
451 pp_instance_ = HostGlobals::Get()->AddInstance(this);
452
453 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
454 DCHECK(delegate);
455 module_->InstanceCreated(this);
456 delegate_->InstanceCreated(this);
457
458 view_data_.is_page_visible = delegate->IsPageVisible();
459 resource_creation_ = delegate_->CreateResourceCreationAPI(this);
460
461 // TODO(bbudge) remove this when the trusted NaCl plugin has been removed.
462 // We must defer certain plugin events for NaCl instances since we switch
463 // from the in-process to the out-of-process proxy after instantiating them.
464 if (module->name() == "Native Client")
465 nacl_document_load_ = true;
466 }
467
468 PluginInstance::~PluginInstance() {
469 DCHECK(!fullscreen_container_);
470
471 // Force-unbind any Graphics. In the case of Graphics2D, if the plugin
472 // leaks the graphics 2D, it may actually get cleaned up after our
473 // destruction, so we need its pointers to be up-to-date.
474 BindGraphics(pp_instance(), 0);
475
476 // Free all the plugin objects. This will automatically clear the back-
477 // pointer from the NPObject so WebKit can't call into the plugin any more.
478 //
479 // Swap out the set so we can delete from it (the objects will try to
480 // unregister themselves inside the delete call).
481 PluginObjectSet plugin_object_copy;
482 live_plugin_objects_.swap(plugin_object_copy);
483 for (PluginObjectSet::iterator i = plugin_object_copy.begin();
484 i != plugin_object_copy.end(); ++i)
485 delete *i;
486
487 if (TrackedCallback::IsPending(lock_mouse_callback_))
488 lock_mouse_callback_->Abort();
489
490 delegate_->InstanceDeleted(this);
491 module_->InstanceDeleted(this);
492 // If we switched from the NaCl plugin module, notify it too.
493 if (original_module_.get())
494 original_module_->InstanceDeleted(this);
495
496 // This should be last since some of the above "instance deleted" calls will
497 // want to look up in the global map to get info off of our object.
498 HostGlobals::Get()->InstanceDeleted(pp_instance_);
499 }
500
501 // NOTE: Any of these methods that calls into the plugin needs to take into
502 // account that the plugin may use Var to remove the <embed> from the DOM, which
503 // will make the WebPluginImpl drop its reference, usually the last one. If a
504 // method needs to access a member of the instance after the call has returned,
505 // then it needs to keep its own reference on the stack.
506
507 void PluginInstance::Delete() {
508 // Keep a reference on the stack. See NOTE above.
509 scoped_refptr<PluginInstance> ref(this);
510 // Force the MessageChannel to release its "passthrough object" which should
511 // release our last reference to the "InstanceObject" and will probably
512 // destroy it. We want to do this prior to calling DidDestroy in case the
513 // destructor of the instance object tries to use the instance.
514 message_channel_->SetPassthroughObject(NULL);
515 // If this is a NaCl plugin instance, shut down the NaCl plugin by calling
516 // its DidDestroy. Don't call DidDestroy on the untrusted plugin instance,
517 // since there is little that it can do at this point.
518 if (original_instance_interface_)
519 original_instance_interface_->DidDestroy(pp_instance());
520 else
521 instance_interface_->DidDestroy(pp_instance());
522 // Ensure we don't attempt to call functions on the destroyed instance.
523 original_instance_interface_.reset();
524 instance_interface_.reset();
525
526 if (fullscreen_container_) {
527 fullscreen_container_->Destroy();
528 fullscreen_container_ = NULL;
529 }
530 bound_graphics_3d_ = NULL;
531 UpdateLayer();
532 container_ = NULL;
533 }
534
535 void PluginInstance::Paint(WebCanvas* canvas,
536 const gfx::Rect& plugin_rect,
537 const gfx::Rect& paint_rect) {
538 TRACE_EVENT0("ppapi", "PluginInstance::Paint");
539 if (module()->is_crashed()) {
540 // Crashed plugin painting.
541 if (!sad_plugin_) // Lazily initialize bitmap.
542 sad_plugin_ = delegate_->GetSadPluginBitmap();
543 if (sad_plugin_)
544 webkit::PaintSadPlugin(canvas, plugin_rect, *sad_plugin_);
545 return;
546 }
547
548 PluginDelegate::PlatformGraphics2D* bound_graphics_2d = GetBoundGraphics2D();
549 if (bound_graphics_2d)
550 bound_graphics_2d->Paint(canvas, plugin_rect, paint_rect);
551 }
552
553 void PluginInstance::InvalidateRect(const gfx::Rect& rect) {
554 if (fullscreen_container_) {
555 if (rect.IsEmpty())
556 fullscreen_container_->Invalidate();
557 else
558 fullscreen_container_->InvalidateRect(rect);
559 } else {
560 if (!container_ ||
561 view_data_.rect.size.width == 0 || view_data_.rect.size.height == 0)
562 return; // Nothing to do.
563 if (rect.IsEmpty())
564 container_->invalidate();
565 else
566 container_->invalidateRect(rect);
567 }
568 }
569
570 void PluginInstance::ScrollRect(int dx, int dy, const gfx::Rect& rect) {
571 if (fullscreen_container_) {
572 fullscreen_container_->ScrollRect(dx, dy, rect);
573 } else {
574 if (full_frame_ && !IsViewAccelerated()) {
575 container_->scrollRect(dx, dy, rect);
576 } else {
577 // Can't do optimized scrolling since there could be other elements on top
578 // of us or the view renders via the accelerated compositor which is
579 // incompatible with the move and backfill scrolling model.
580 InvalidateRect(rect);
581 }
582 }
583 }
584
585 void PluginInstance::CommitBackingTexture() {
586 if (texture_layer_.get())
587 texture_layer_->SetNeedsDisplay();
588 }
589
590 void PluginInstance::InstanceCrashed() {
591 // Force free all resources and vars.
592 HostGlobals::Get()->InstanceCrashed(pp_instance());
593
594 // Free any associated graphics.
595 SetFullscreen(false);
596 FlashSetFullscreen(false, false);
597 // Unbind current 2D or 3D graphics context.
598 BindGraphics(pp_instance(), 0);
599 InvalidateRect(gfx::Rect());
600
601 delegate()->PluginCrashed(this);
602 }
603
604 static void SetGPUHistogram(const ::ppapi::Preferences& prefs,
605 const std::vector<std::string>& arg_names,
606 const std::vector<std::string>& arg_values) {
607 // Calculate a histogram to let us determine how likely people are to try to
608 // run Stage3D content on machines that have it blacklisted.
609 #if defined(OS_WIN)
610 bool needs_gpu = false;
611 bool is_xp = base::win::GetVersion() <= base::win::VERSION_XP;
612
613 for (size_t i = 0; i < arg_names.size(); i++) {
614 if (arg_names[i] == "wmode") {
615 // In theory content other than Flash could have a "wmode" argument,
616 // but that's pretty unlikely.
617 if (arg_values[i] == "direct" || arg_values[i] == "gpu")
618 needs_gpu = true;
619 break;
620 }
621 }
622 // 0 : No 3D content and GPU is blacklisted
623 // 1 : No 3D content and GPU is not blacklisted
624 // 2 : 3D content but GPU is blacklisted
625 // 3 : 3D content and GPU is not blacklisted
626 // 4 : No 3D content and GPU is blacklisted on XP
627 // 5 : No 3D content and GPU is not blacklisted on XP
628 // 6 : 3D content but GPU is blacklisted on XP
629 // 7 : 3D content and GPU is not blacklisted on XP
630 UMA_HISTOGRAM_ENUMERATION("Flash.UsesGPU",
631 is_xp * 4 + needs_gpu * 2 + prefs.is_webgl_supported, 8);
632 #endif
633 }
634
635 bool PluginInstance::Initialize(const std::vector<std::string>& arg_names,
636 const std::vector<std::string>& arg_values,
637 bool full_frame) {
638 message_channel_.reset(new MessageChannel(this));
639
640 full_frame_ = full_frame;
641
642 UpdateTouchEventRequest();
643 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
644
645 SetGPUHistogram(delegate_->GetPreferences(), arg_names, arg_values);
646
647 argn_ = arg_names;
648 argv_ = arg_values;
649 scoped_ptr<const char*[]> argn_array(StringVectorToArgArray(argn_));
650 scoped_ptr<const char*[]> argv_array(StringVectorToArgArray(argv_));
651 bool success = PP_ToBool(instance_interface_->DidCreate(pp_instance(),
652 argn_.size(),
653 argn_array.get(),
654 argv_array.get()));
655 if (success)
656 message_channel_->StopQueueingJavaScriptMessages();
657 return success;
658 }
659
660 bool PluginInstance::HandleDocumentLoad(
661 const WebKit::WebURLResponse& response) {
662 DCHECK(!document_loader_);
663 if (!nacl_document_load_) {
664 if (module()->is_crashed()) {
665 // Don't create a resource for a crashed plugin.
666 container()->element().document().frame()->stopLoading();
667 return false;
668 }
669 delegate()->HandleDocumentLoad(this, response);
670 // If the load was not abandoned, document_loader_ will now be set. It's
671 // possible that the load was canceled by now and document_loader_ was
672 // already nulled out.
673 } else {
674 // The NaCl proxy isn't available, so save the response and record document
675 // load notifications for later replay.
676 nacl_document_response_ = response;
677 nacl_document_loader_.reset(new NaClDocumentLoader());
678 document_loader_ = nacl_document_loader_.get();
679 }
680 return true;
681 }
682
683 bool PluginInstance::SendCompositionEventToPlugin(PP_InputEvent_Type type,
684 const base::string16& text) {
685 std::vector<WebKit::WebCompositionUnderline> empty;
686 return SendCompositionEventWithUnderlineInformationToPlugin(
687 type, text, empty, static_cast<int>(text.size()),
688 static_cast<int>(text.size()));
689 }
690
691 bool PluginInstance::SendCompositionEventWithUnderlineInformationToPlugin(
692 PP_InputEvent_Type type,
693 const base::string16& text,
694 const std::vector<WebKit::WebCompositionUnderline>& underlines,
695 int selection_start,
696 int selection_end) {
697 // Keep a reference on the stack. See NOTE above.
698 scoped_refptr<PluginInstance> ref(this);
699
700 if (!LoadInputEventInterface())
701 return false;
702
703 PP_InputEvent_Class event_class = PP_INPUTEVENT_CLASS_IME;
704 if (!(filtered_input_event_mask_ & event_class) &&
705 !(input_event_mask_ & event_class))
706 return false;
707
708 ::ppapi::InputEventData event;
709 event.event_type = type;
710 event.event_time_stamp = ::ppapi::TimeTicksToPPTimeTicks(
711 base::TimeTicks::Now());
712
713 // Convert UTF16 text to UTF8 with offset conversion.
714 std::vector<size_t> utf16_offsets;
715 utf16_offsets.push_back(selection_start);
716 utf16_offsets.push_back(selection_end);
717 for (size_t i = 0; i < underlines.size(); ++i) {
718 utf16_offsets.push_back(underlines[i].startOffset);
719 utf16_offsets.push_back(underlines[i].endOffset);
720 }
721 std::vector<size_t> utf8_offsets(utf16_offsets);
722 event.character_text = base::UTF16ToUTF8AndAdjustOffsets(text, &utf8_offsets);
723
724 // Set the converted selection range.
725 event.composition_selection_start = (utf8_offsets[0] == std::string::npos ?
726 event.character_text.size() : utf8_offsets[0]);
727 event.composition_selection_end = (utf8_offsets[1] == std::string::npos ?
728 event.character_text.size() : utf8_offsets[1]);
729
730 // Set the converted segmentation points.
731 // Be sure to add 0 and size(), and remove duplication or errors.
732 std::set<size_t> offset_set(utf8_offsets.begin()+2, utf8_offsets.end());
733 offset_set.insert(0);
734 offset_set.insert(event.character_text.size());
735 offset_set.erase(std::string::npos);
736 event.composition_segment_offsets.assign(offset_set.begin(),
737 offset_set.end());
738
739 // Set the composition target.
740 for (size_t i = 0; i < underlines.size(); ++i) {
741 if (underlines[i].thick) {
742 std::vector<uint32_t>::iterator it =
743 std::find(event.composition_segment_offsets.begin(),
744 event.composition_segment_offsets.end(),
745 utf8_offsets[2*i+2]);
746 if (it != event.composition_segment_offsets.end()) {
747 event.composition_target_segment =
748 it - event.composition_segment_offsets.begin();
749 break;
750 }
751 }
752 }
753
754 // Send the event.
755 bool handled = false;
756 if (filtered_input_event_mask_ & event_class)
757 event.is_filtered = true;
758 else
759 handled = true; // Unfiltered events are assumed to be handled.
760 scoped_refptr<PPB_InputEvent_Shared> event_resource(
761 new PPB_InputEvent_Shared(::ppapi::OBJECT_IS_IMPL, pp_instance(), event));
762 handled |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
763 pp_instance(), event_resource->pp_resource()));
764 return handled;
765 }
766
767 void PluginInstance::RequestInputEventsHelper(uint32_t event_classes) {
768 if (event_classes & PP_INPUTEVENT_CLASS_TOUCH)
769 UpdateTouchEventRequest();
770 if (event_classes & PP_INPUTEVENT_CLASS_WHEEL)
771 container_->setWantsWheelEvents(IsAcceptingWheelEvents());
772 }
773
774 bool PluginInstance::HandleCompositionStart(const base::string16& text) {
775 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_START,
776 text);
777 }
778
779 bool PluginInstance::HandleCompositionUpdate(
780 const base::string16& text,
781 const std::vector<WebKit::WebCompositionUnderline>& underlines,
782 int selection_start,
783 int selection_end) {
784 return SendCompositionEventWithUnderlineInformationToPlugin(
785 PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE,
786 text, underlines, selection_start, selection_end);
787 }
788
789 bool PluginInstance::HandleCompositionEnd(const base::string16& text) {
790 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_COMPOSITION_END,
791 text);
792 }
793
794 bool PluginInstance::HandleTextInput(const base::string16& text) {
795 return SendCompositionEventToPlugin(PP_INPUTEVENT_TYPE_IME_TEXT,
796 text);
797 }
798
799 void PluginInstance::GetSurroundingText(base::string16* text,
800 ui::Range* range) const {
801 std::vector<size_t> offsets;
802 offsets.push_back(selection_anchor_);
803 offsets.push_back(selection_caret_);
804 *text = base::UTF8ToUTF16AndAdjustOffsets(surrounding_text_, &offsets);
805 range->set_start(offsets[0] == base::string16::npos ? text->size()
806 : offsets[0]);
807 range->set_end(offsets[1] == base::string16::npos ? text->size()
808 : offsets[1]);
809 }
810
811 bool PluginInstance::IsPluginAcceptingCompositionEvents() const {
812 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_IME) ||
813 (input_event_mask_ & PP_INPUTEVENT_CLASS_IME);
814 }
815
816 gfx::Rect PluginInstance::GetCaretBounds() const {
817 if (!text_input_caret_set_) {
818 // If it is never set by the plugin, use the bottom left corner.
819 return gfx::Rect(view_data_.rect.point.x,
820 view_data_.rect.point.y + view_data_.rect.size.height,
821 0, 0);
822 }
823
824 // TODO(kinaba) Take CSS transformation into accont.
825 // TODO(kinaba) Take bounding_box into account. On some platforms, an
826 // "exclude rectangle" where candidate window must avoid the region can be
827 // passed to IME. Currently, we pass only the caret rectangle because
828 // it is the only information supported uniformly in Chromium.
829 gfx::Rect caret(text_input_caret_);
830 caret.Offset(view_data_.rect.point.x, view_data_.rect.point.y);
831 return caret;
832 }
833
834 bool PluginInstance::HandleInputEvent(const WebKit::WebInputEvent& event,
835 WebCursorInfo* cursor_info) {
836 TRACE_EVENT0("ppapi", "PluginInstance::HandleInputEvent");
837
838 if (WebInputEvent::isMouseEventType(event.type))
839 delegate()->DidReceiveMouseEvent(this);
840
841 // Don't dispatch input events to crashed plugins.
842 if (module()->is_crashed())
843 return false;
844
845 // Keep a reference on the stack. See NOTE above.
846 scoped_refptr<PluginInstance> ref(this);
847
848 bool rv = false;
849 if (LoadInputEventInterface()) {
850 PP_InputEvent_Class event_class = ClassifyInputEvent(event.type);
851 if (!event_class)
852 return false;
853
854 if ((filtered_input_event_mask_ & event_class) ||
855 (input_event_mask_ & event_class)) {
856 // Actually send the event.
857 std::vector< ::ppapi::InputEventData > events;
858 CreateInputEventData(event, &events);
859
860 // Allow the user gesture to be pending after the plugin handles the
861 // event. This allows out-of-process plugins to respond to the user
862 // gesture after processing has finished here.
863 if (WebUserGestureIndicator::isProcessingUserGesture()) {
864 pending_user_gesture_ =
865 ::ppapi::EventTimeToPPTimeTicks(event.timeStampSeconds);
866 pending_user_gesture_token_ =
867 WebUserGestureIndicator::currentUserGestureToken();
868 pending_user_gesture_token_.setOutOfProcess();
869 }
870
871 // Each input event may generate more than one PP_InputEvent.
872 for (size_t i = 0; i < events.size(); i++) {
873 if (filtered_input_event_mask_ & event_class)
874 events[i].is_filtered = true;
875 else
876 rv = true; // Unfiltered events are assumed to be handled.
877 scoped_refptr<PPB_InputEvent_Shared> event_resource(
878 new PPB_InputEvent_Shared(::ppapi::OBJECT_IS_IMPL,
879 pp_instance(), events[i]));
880
881 rv |= PP_ToBool(plugin_input_event_interface_->HandleInputEvent(
882 pp_instance(), event_resource->pp_resource()));
883 }
884 }
885 }
886
887 if (cursor_)
888 *cursor_info = *cursor_;
889 return rv;
890 }
891
892 void PluginInstance::HandleMessage(PP_Var message) {
893 TRACE_EVENT0("ppapi", "PluginInstance::HandleMessage");
894 // Keep a reference on the stack. See NOTE above.
895 scoped_refptr<PluginInstance> ref(this);
896 if (!LoadMessagingInterface())
897 return;
898 plugin_messaging_interface_->HandleMessage(pp_instance(), message);
899 }
900
901 PP_Var PluginInstance::GetInstanceObject() {
902 // Keep a reference on the stack. See NOTE above.
903 scoped_refptr<PluginInstance> ref(this);
904
905 // If the plugin supports the private instance interface, try to retrieve its
906 // instance object.
907 if (LoadPrivateInterface())
908 return plugin_private_interface_->GetInstanceObject(pp_instance());
909 return PP_MakeUndefined();
910 }
911
912 void PluginInstance::ViewChanged(const gfx::Rect& position,
913 const gfx::Rect& clip,
914 const std::vector<gfx::Rect>& cut_outs_rects) {
915 // WebKit can give weird (x,y) positions for empty clip rects (since the
916 // position technically doesn't matter). But we want to make these
917 // consistent since this is given to the plugin, so force everything to 0
918 // in the "everything is clipped" case.
919 gfx::Rect new_clip;
920 if (!clip.IsEmpty())
921 new_clip = clip;
922
923 cut_outs_rects_ = cut_outs_rects;
924
925 view_data_.rect = PP_FromGfxRect(position);
926 view_data_.clip_rect = PP_FromGfxRect(clip);
927 view_data_.device_scale = container_->deviceScaleFactor();
928 view_data_.css_scale = container_->pageZoomFactor() *
929 container_->pageScaleFactor();
930
931 if (desired_fullscreen_state_ || view_data_.is_fullscreen) {
932 WebElement element = container_->element();
933 WebDocument document = element.document();
934 bool is_fullscreen_element = (element == document.fullScreenElement());
935 if (!view_data_.is_fullscreen && desired_fullscreen_state_ &&
936 delegate()->IsInFullscreenMode() && is_fullscreen_element) {
937 // Entered fullscreen. Only possible via SetFullscreen().
938 view_data_.is_fullscreen = true;
939 } else if (view_data_.is_fullscreen && !is_fullscreen_element) {
940 // Exited fullscreen. Possible via SetFullscreen() or F11/link,
941 // so desired_fullscreen_state might be out-of-date.
942 desired_fullscreen_state_ = false;
943 view_data_.is_fullscreen = false;
944
945 // This operation will cause the plugin to re-layout which will send more
946 // DidChangeView updates. Schedule an asynchronous update and suppress
947 // notifications until that completes to avoid sending intermediate sizes
948 // to the plugins.
949 ScheduleAsyncDidChangeView();
950
951 // Reset the size attributes that we hacked to fill in the screen and
952 // retrigger ViewChanged. Make sure we don't forward duplicates of
953 // this view to the plugin.
954 ResetSizeAttributesAfterFullscreen();
955 return;
956 }
957 }
958
959 UpdateFlashFullscreenState(fullscreen_container_ != NULL);
960
961 SendDidChangeView();
962 }
963
964 void PluginInstance::SetWebKitFocus(bool has_focus) {
965 if (has_webkit_focus_ == has_focus)
966 return;
967
968 bool old_plugin_focus = PluginHasFocus();
969 has_webkit_focus_ = has_focus;
970 if (PluginHasFocus() != old_plugin_focus)
971 SendFocusChangeNotification();
972 }
973
974 void PluginInstance::SetContentAreaFocus(bool has_focus) {
975 if (has_content_area_focus_ == has_focus)
976 return;
977
978 bool old_plugin_focus = PluginHasFocus();
979 has_content_area_focus_ = has_focus;
980 if (PluginHasFocus() != old_plugin_focus)
981 SendFocusChangeNotification();
982 }
983
984 void PluginInstance::PageVisibilityChanged(bool is_visible) {
985 if (is_visible == view_data_.is_page_visible)
986 return; // Nothing to do.
987 view_data_.is_page_visible = is_visible;
988
989 // If the initial DidChangeView notification hasn't been sent to the plugin,
990 // let it pass the visibility state for us, instead of sending a notification
991 // immediately. It is possible that PluginInstance::ViewChanged() hasn't been
992 // called for the first time. In that case, most of the fields in |view_data_|
993 // haven't been properly initialized.
994 if (sent_initial_did_change_view_)
995 SendDidChangeView();
996 }
997
998 void PluginInstance::ViewWillInitiatePaint() {
999 if (GetBoundGraphics2D())
1000 GetBoundGraphics2D()->ViewWillInitiatePaint();
1001 else if (bound_graphics_3d_.get())
1002 bound_graphics_3d_->ViewWillInitiatePaint();
1003 }
1004
1005 void PluginInstance::ViewInitiatedPaint() {
1006 if (GetBoundGraphics2D())
1007 GetBoundGraphics2D()->ViewInitiatedPaint();
1008 else if (bound_graphics_3d_.get())
1009 bound_graphics_3d_->ViewInitiatedPaint();
1010 }
1011
1012 void PluginInstance::ViewFlushedPaint() {
1013 // Keep a reference on the stack. See NOTE above.
1014 scoped_refptr<PluginInstance> ref(this);
1015 if (GetBoundGraphics2D())
1016 GetBoundGraphics2D()->ViewFlushedPaint();
1017 else if (bound_graphics_3d_.get())
1018 bound_graphics_3d_->ViewFlushedPaint();
1019 }
1020
1021 bool PluginInstance::GetBitmapForOptimizedPluginPaint(
1022 const gfx::Rect& paint_bounds,
1023 TransportDIB** dib,
1024 gfx::Rect* location,
1025 gfx::Rect* clip,
1026 float* scale_factor) {
1027 if (!always_on_top_)
1028 return false;
1029 if (!GetBoundGraphics2D() || !GetBoundGraphics2D()->IsAlwaysOpaque())
1030 return false;
1031
1032 // We specifically want to compare against the area covered by the backing
1033 // store when seeing if we cover the given paint bounds, since the backing
1034 // store could be smaller than the declared plugin area.
1035 PPB_ImageData_Impl* image_data = GetBoundGraphics2D()->ImageData();
1036 // ImageDatas created by NaCl don't have a PlatformImage, so can't be
1037 // optimized this way.
1038 if (!image_data->PlatformImage())
1039 return false;
1040
1041 gfx::Point plugin_origin = PP_ToGfxPoint(view_data_.rect.point);
1042 gfx::Vector2d plugin_offset = plugin_origin.OffsetFromOrigin();
1043 // Convert |paint_bounds| to be relative to the left-top corner of the plugin.
1044 gfx::Rect relative_paint_bounds(paint_bounds);
1045 relative_paint_bounds.Offset(-plugin_offset);
1046
1047 gfx::Rect pixel_plugin_backing_store_rect(
1048 0, 0, image_data->width(), image_data->height());
1049 float scale = GetBoundGraphics2D()->GetScale();
1050 gfx::Rect plugin_backing_store_rect = gfx::ToEnclosedRect(
1051 gfx::ScaleRect(pixel_plugin_backing_store_rect, scale));
1052
1053 gfx::Rect clip_page = PP_ToGfxRect(view_data_.clip_rect);
1054 gfx::Rect plugin_paint_rect =
1055 gfx::IntersectRects(plugin_backing_store_rect, clip_page);
1056 if (!plugin_paint_rect.Contains(relative_paint_bounds))
1057 return false;
1058
1059 // Don't do optimized painting if the area to paint intersects with the
1060 // cut-out rects, otherwise we will paint over them.
1061 for (std::vector<gfx::Rect>::const_iterator iter = cut_outs_rects_.begin();
1062 iter != cut_outs_rects_.end(); ++iter) {
1063 if (relative_paint_bounds.Intersects(*iter))
1064 return false;
1065 }
1066
1067 *dib = image_data->PlatformImage()->GetTransportDIB();
1068 plugin_backing_store_rect.Offset(plugin_offset);
1069 *location = plugin_backing_store_rect;
1070 clip_page.Offset(plugin_offset);
1071 *clip = clip_page;
1072 // The plugin scale factor is inverted, e.g. for a device scale factor of 2x
1073 // the plugin scale factor is 0.5.
1074 *scale_factor = 1.0 / scale;
1075 return true;
1076 }
1077
1078 base::string16 PluginInstance::GetSelectedText(bool html) {
1079 // Keep a reference on the stack. See NOTE above.
1080 scoped_refptr<PluginInstance> ref(this);
1081 if (!LoadSelectionInterface())
1082 return base::string16();
1083
1084 PP_Var rv = plugin_selection_interface_->GetSelectedText(pp_instance(),
1085 PP_FromBool(html));
1086 StringVar* string = StringVar::FromPPVar(rv);
1087 base::string16 selection;
1088 if (string)
1089 selection = UTF8ToUTF16(string->value());
1090 // Release the ref the plugin transfered to us.
1091 HostGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1092 return selection;
1093 }
1094
1095 base::string16 PluginInstance::GetLinkAtPosition(const gfx::Point& point) {
1096 // Keep a reference on the stack. See NOTE above.
1097 scoped_refptr<PluginInstance> ref(this);
1098 if (!LoadPdfInterface())
1099 return base::string16();
1100
1101 PP_Point p;
1102 p.x = point.x();
1103 p.y = point.y();
1104 PP_Var rv = plugin_pdf_interface_->GetLinkAtPosition(pp_instance(), p);
1105 StringVar* string = StringVar::FromPPVar(rv);
1106 base::string16 link;
1107 if (string)
1108 link = UTF8ToUTF16(string->value());
1109 // Release the ref the plugin transfered to us.
1110 PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(rv);
1111 return link;
1112 }
1113
1114 void PluginInstance::RequestSurroundingText(
1115 size_t desired_number_of_characters) {
1116 // Keep a reference on the stack. See NOTE above.
1117 scoped_refptr<PluginInstance> ref(this);
1118 if (!LoadTextInputInterface())
1119 return;
1120 plugin_textinput_interface_->RequestSurroundingText(
1121 pp_instance(), desired_number_of_characters);
1122 }
1123
1124 void PluginInstance::Zoom(double factor, bool text_only) {
1125 // Keep a reference on the stack. See NOTE above.
1126 scoped_refptr<PluginInstance> ref(this);
1127 if (!LoadZoomInterface())
1128 return;
1129 plugin_zoom_interface_->Zoom(pp_instance(), factor, PP_FromBool(text_only));
1130 }
1131
1132 bool PluginInstance::StartFind(const base::string16& search_text,
1133 bool case_sensitive,
1134 int identifier) {
1135 // Keep a reference on the stack. See NOTE above.
1136 scoped_refptr<PluginInstance> ref(this);
1137 if (!LoadFindInterface())
1138 return false;
1139 find_identifier_ = identifier;
1140 return PP_ToBool(
1141 plugin_find_interface_->StartFind(
1142 pp_instance(),
1143 UTF16ToUTF8(search_text.c_str()).c_str(),
1144 PP_FromBool(case_sensitive)));
1145 }
1146
1147 void PluginInstance::SelectFindResult(bool forward) {
1148 // Keep a reference on the stack. See NOTE above.
1149 scoped_refptr<PluginInstance> ref(this);
1150 if (LoadFindInterface())
1151 plugin_find_interface_->SelectFindResult(pp_instance(),
1152 PP_FromBool(forward));
1153 }
1154
1155 void PluginInstance::StopFind() {
1156 // Keep a reference on the stack. See NOTE above.
1157 scoped_refptr<PluginInstance> ref(this);
1158 if (!LoadFindInterface())
1159 return;
1160 find_identifier_ = -1;
1161 plugin_find_interface_->StopFind(pp_instance());
1162 }
1163
1164 bool PluginInstance::LoadFindInterface() {
1165 if (!plugin_find_interface_) {
1166 plugin_find_interface_ =
1167 static_cast<const PPP_Find_Dev*>(module_->GetPluginInterface(
1168 PPP_FIND_DEV_INTERFACE));
1169 }
1170
1171 return !!plugin_find_interface_;
1172 }
1173
1174 bool PluginInstance::LoadInputEventInterface() {
1175 if (!checked_for_plugin_input_event_interface_) {
1176 checked_for_plugin_input_event_interface_ = true;
1177 plugin_input_event_interface_ =
1178 static_cast<const PPP_InputEvent*>(module_->GetPluginInterface(
1179 PPP_INPUT_EVENT_INTERFACE));
1180 }
1181 return !!plugin_input_event_interface_;
1182 }
1183
1184 bool PluginInstance::LoadMessagingInterface() {
1185 if (!checked_for_plugin_messaging_interface_) {
1186 checked_for_plugin_messaging_interface_ = true;
1187 plugin_messaging_interface_ =
1188 static_cast<const PPP_Messaging*>(module_->GetPluginInterface(
1189 PPP_MESSAGING_INTERFACE));
1190 }
1191 return !!plugin_messaging_interface_;
1192 }
1193
1194 bool PluginInstance::LoadMouseLockInterface() {
1195 if (!plugin_mouse_lock_interface_) {
1196 plugin_mouse_lock_interface_ =
1197 static_cast<const PPP_MouseLock*>(module_->GetPluginInterface(
1198 PPP_MOUSELOCK_INTERFACE));
1199 }
1200
1201 return !!plugin_mouse_lock_interface_;
1202 }
1203
1204 bool PluginInstance::LoadPdfInterface() {
1205 if (!checked_for_plugin_pdf_interface_) {
1206 checked_for_plugin_pdf_interface_ = true;
1207 plugin_pdf_interface_ =
1208 static_cast<const PPP_Pdf_1*>(module_->GetPluginInterface(
1209 PPP_PDF_INTERFACE_1));
1210 }
1211
1212 return !!plugin_pdf_interface_;
1213 }
1214
1215 bool PluginInstance::LoadPrintInterface() {
1216 // Only check for the interface if the plugin has dev permission.
1217 if (!module_->permissions().HasPermission(::ppapi::PERMISSION_DEV))
1218 return false;
1219 if (!plugin_print_interface_) {
1220 plugin_print_interface_ = static_cast<const PPP_Printing_Dev*>(
1221 module_->GetPluginInterface(PPP_PRINTING_DEV_INTERFACE));
1222 }
1223 return !!plugin_print_interface_;
1224 }
1225
1226 bool PluginInstance::LoadPrivateInterface() {
1227 // Only check for the interface if the plugin has private permission.
1228 if (!module_->permissions().HasPermission(::ppapi::PERMISSION_PRIVATE))
1229 return false;
1230 if (!plugin_private_interface_) {
1231 plugin_private_interface_ = static_cast<const PPP_Instance_Private*>(
1232 module_->GetPluginInterface(PPP_INSTANCE_PRIVATE_INTERFACE));
1233 }
1234
1235 return !!plugin_private_interface_;
1236 }
1237
1238 bool PluginInstance::LoadSelectionInterface() {
1239 if (!plugin_selection_interface_) {
1240 plugin_selection_interface_ =
1241 static_cast<const PPP_Selection_Dev*>(module_->GetPluginInterface(
1242 PPP_SELECTION_DEV_INTERFACE));
1243 }
1244 return !!plugin_selection_interface_;
1245 }
1246
1247 bool PluginInstance::LoadTextInputInterface() {
1248 if (!plugin_textinput_interface_) {
1249 plugin_textinput_interface_ =
1250 static_cast<const PPP_TextInput_Dev*>(module_->GetPluginInterface(
1251 PPP_TEXTINPUT_DEV_INTERFACE));
1252 }
1253
1254 return !!plugin_textinput_interface_;
1255 }
1256
1257 bool PluginInstance::LoadZoomInterface() {
1258 if (!plugin_zoom_interface_) {
1259 plugin_zoom_interface_ =
1260 static_cast<const PPP_Zoom_Dev*>(module_->GetPluginInterface(
1261 PPP_ZOOM_DEV_INTERFACE));
1262 }
1263
1264 return !!plugin_zoom_interface_;
1265 }
1266
1267 bool PluginInstance::PluginHasFocus() const {
1268 return flash_fullscreen_ || (has_webkit_focus_ && has_content_area_focus_);
1269 }
1270
1271 void PluginInstance::SendFocusChangeNotification() {
1272 // This call can happen during PluginInstance destruction, because WebKit
1273 // informs the plugin it's losing focus. See crbug.com/236574
1274 if (!delegate_ || !instance_interface_)
1275 return;
1276 bool has_focus = PluginHasFocus();
1277 delegate()->PluginFocusChanged(this, has_focus);
1278 instance_interface_->DidChangeFocus(pp_instance(), PP_FromBool(has_focus));
1279 }
1280
1281 void PluginInstance::UpdateTouchEventRequest() {
1282 bool raw_touch = (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH) ||
1283 (input_event_mask_ & PP_INPUTEVENT_CLASS_TOUCH);
1284 container_->requestTouchEventType(raw_touch ?
1285 WebKit::WebPluginContainer::TouchEventRequestTypeRaw :
1286 WebKit::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse);
1287 }
1288
1289 bool PluginInstance::IsAcceptingWheelEvents() const {
1290 return (filtered_input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL) ||
1291 (input_event_mask_ & PP_INPUTEVENT_CLASS_WHEEL);
1292 }
1293
1294 void PluginInstance::ScheduleAsyncDidChangeView() {
1295 if (view_change_weak_ptr_factory_.HasWeakPtrs())
1296 return; // Already scheduled.
1297 base::MessageLoop::current()->PostTask(
1298 FROM_HERE,
1299 base::Bind(&PluginInstance::SendAsyncDidChangeView,
1300 view_change_weak_ptr_factory_.GetWeakPtr()));
1301 }
1302
1303 void PluginInstance::SendAsyncDidChangeView() {
1304 // The bound callback that owns the weak pointer is still valid until after
1305 // this function returns. SendDidChangeView checks HasWeakPtrs, so we need to
1306 // invalidate them here.
1307 // NOTE: If we ever want to have more than one pending callback, it should
1308 // use a different factory, or we should have a different strategy here.
1309 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
1310 SendDidChangeView();
1311 }
1312
1313 void PluginInstance::SendDidChangeView() {
1314 // Don't send DidChangeView to crashed plugins.
1315 if (module()->is_crashed())
1316 return;
1317
1318 if (view_change_weak_ptr_factory_.HasWeakPtrs() ||
1319 (sent_initial_did_change_view_ &&
1320 last_sent_view_data_.Equals(view_data_)))
1321 return; // Nothing to update.
1322
1323 const PP_Size& size = view_data_.rect.size;
1324 // Avoid sending a notification with a huge rectangle.
1325 if (size.width < 0 || size.width > kMaxPluginSideLength ||
1326 size.height < 0 || size.height > kMaxPluginSideLength ||
1327 // We know this won't overflow due to above checks.
1328 static_cast<uint32>(size.width) * static_cast<uint32>(size.height) >
1329 kMaxPluginSize) {
1330 return;
1331 }
1332
1333 sent_initial_did_change_view_ = true;
1334 last_sent_view_data_ = view_data_;
1335 ScopedPPResource resource(
1336 ScopedPPResource::PassRef(),
1337 (new PPB_View_Shared(::ppapi::OBJECT_IS_IMPL,
1338 pp_instance(), view_data_))->GetReference());
1339
1340 instance_interface_->DidChangeView(pp_instance(), resource,
1341 &view_data_.rect,
1342 &view_data_.clip_rect);
1343 }
1344
1345 void PluginInstance::ReportGeometry() {
1346 // If this call was delayed, we may have transitioned back to fullscreen in
1347 // the mean time, so only report the geometry if we are actually in normal
1348 // mode.
1349 if (container_ && !fullscreen_container_ && !flash_fullscreen_)
1350 container_->reportGeometry();
1351 }
1352
1353 bool PluginInstance::GetPreferredPrintOutputFormat(
1354 PP_PrintOutputFormat_Dev* format) {
1355 // Keep a reference on the stack. See NOTE above.
1356 scoped_refptr<PluginInstance> ref(this);
1357 if (!LoadPrintInterface())
1358 return false;
1359 uint32_t supported_formats =
1360 plugin_print_interface_->QuerySupportedFormats(pp_instance());
1361 if (supported_formats & PP_PRINTOUTPUTFORMAT_PDF) {
1362 *format = PP_PRINTOUTPUTFORMAT_PDF;
1363 return true;
1364 }
1365 return false;
1366 }
1367
1368 bool PluginInstance::SupportsPrintInterface() {
1369 PP_PrintOutputFormat_Dev format;
1370 return GetPreferredPrintOutputFormat(&format);
1371 }
1372
1373 bool PluginInstance::IsPrintScalingDisabled() {
1374 DCHECK(plugin_print_interface_);
1375 if (!plugin_print_interface_)
1376 return false;
1377 return plugin_print_interface_->IsScalingDisabled(pp_instance()) == PP_TRUE;
1378 }
1379
1380 int PluginInstance::PrintBegin(const WebPrintParams& print_params) {
1381 // Keep a reference on the stack. See NOTE above.
1382 scoped_refptr<PluginInstance> ref(this);
1383 PP_PrintOutputFormat_Dev format;
1384 if (!GetPreferredPrintOutputFormat(&format)) {
1385 // PrintBegin should not have been called since SupportsPrintInterface
1386 // would have returned false;
1387 NOTREACHED();
1388 return 0;
1389 }
1390 int num_pages = 0;
1391 PP_PrintSettings_Dev print_settings;
1392 print_settings.printable_area = PP_FromGfxRect(print_params.printableArea);
1393 print_settings.content_area = PP_FromGfxRect(print_params.printContentArea);
1394 print_settings.paper_size = PP_FromGfxSize(print_params.paperSize);
1395 print_settings.dpi = print_params.printerDPI;
1396 print_settings.orientation = PP_PRINTORIENTATION_NORMAL;
1397 print_settings.grayscale = PP_FALSE;
1398 print_settings.print_scaling_option = static_cast<PP_PrintScalingOption_Dev>(
1399 print_params.printScalingOption);
1400 print_settings.format = format;
1401 num_pages = plugin_print_interface_->Begin(pp_instance(),
1402 &print_settings);
1403 if (!num_pages)
1404 return 0;
1405 current_print_settings_ = print_settings;
1406 canvas_.clear();
1407 ranges_.clear();
1408 return num_pages;
1409 }
1410
1411 bool PluginInstance::PrintPage(int page_number, WebKit::WebCanvas* canvas) {
1412 #if defined(ENABLE_PRINTING)
1413 DCHECK(plugin_print_interface_);
1414 PP_PrintPageNumberRange_Dev page_range;
1415 page_range.first_page_number = page_range.last_page_number = page_number;
1416 // The canvas only has a metafile on it for print preview.
1417 bool save_for_later =
1418 (printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas) != NULL);
1419 #if defined(OS_MACOSX) || defined(OS_WIN)
1420 save_for_later = save_for_later && skia::IsPreviewMetafile(*canvas);
1421 #endif
1422 if (save_for_later) {
1423 ranges_.push_back(page_range);
1424 canvas_ = skia::SharePtr(canvas);
1425 return true;
1426 } else {
1427 return PrintPageHelper(&page_range, 1, canvas);
1428 }
1429 #else // defined(ENABLED_PRINTING)
1430 return false;
1431 #endif
1432 }
1433
1434 bool PluginInstance::PrintPageHelper(PP_PrintPageNumberRange_Dev* page_ranges,
1435 int num_ranges,
1436 WebKit::WebCanvas* canvas) {
1437 // Keep a reference on the stack. See NOTE above.
1438 scoped_refptr<PluginInstance> ref(this);
1439 DCHECK(plugin_print_interface_);
1440 if (!plugin_print_interface_)
1441 return false;
1442 PP_Resource print_output = plugin_print_interface_->PrintPages(
1443 pp_instance(), page_ranges, num_ranges);
1444 if (!print_output)
1445 return false;
1446
1447 bool ret = false;
1448
1449 if (current_print_settings_.format == PP_PRINTOUTPUTFORMAT_PDF)
1450 ret = PrintPDFOutput(print_output, canvas);
1451
1452 // Now we need to release the print output resource.
1453 PluginModule::GetCore()->ReleaseResource(print_output);
1454
1455 return ret;
1456 }
1457
1458 void PluginInstance::PrintEnd() {
1459 // Keep a reference on the stack. See NOTE above.
1460 scoped_refptr<PluginInstance> ref(this);
1461 if (!ranges_.empty())
1462 PrintPageHelper(&(ranges_.front()), ranges_.size(), canvas_.get());
1463 canvas_.clear();
1464 ranges_.clear();
1465
1466 DCHECK(plugin_print_interface_);
1467 if (plugin_print_interface_)
1468 plugin_print_interface_->End(pp_instance());
1469
1470 memset(&current_print_settings_, 0, sizeof(current_print_settings_));
1471 #if defined(OS_MACOSX)
1472 last_printed_page_ = NULL;
1473 #endif // defined(OS_MACOSX)
1474 }
1475
1476 bool PluginInstance::CanRotateView() {
1477 if (!LoadPdfInterface())
1478 return false;
1479
1480 return true;
1481 }
1482
1483 void PluginInstance::SetBoundGraphics2DForTest(
1484 PluginDelegate::PlatformGraphics2D* graphics) {
1485 BindGraphics(pp_instance(), 0); // Unbind any old stuff.
1486 if (graphics) {
1487 bound_graphics_2d_platform_ = graphics;
1488 bound_graphics_2d_platform_->BindToInstance(this);
1489 }
1490 }
1491
1492 void PluginInstance::RotateView(WebPlugin::RotationType type) {
1493 if (!LoadPdfInterface())
1494 return;
1495 PP_PrivatePageTransformType transform_type =
1496 type == WebPlugin::RotationType90Clockwise ?
1497 PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW :
1498 PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW;
1499 plugin_pdf_interface_->Transform(pp_instance(), transform_type);
1500 // NOTE: plugin instance may have been deleted.
1501 }
1502
1503 bool PluginInstance::FlashIsFullscreenOrPending() {
1504 return fullscreen_container_ != NULL;
1505 }
1506
1507 bool PluginInstance::IsFullscreenOrPending() {
1508 return desired_fullscreen_state_;
1509 }
1510
1511 bool PluginInstance::SetFullscreen(bool fullscreen) {
1512 // Keep a reference on the stack. See NOTE above.
1513 scoped_refptr<PluginInstance> ref(this);
1514
1515 // Check whether we are trying to switch to the state we're already going
1516 // to (i.e. if we're already switching to fullscreen but the fullscreen
1517 // container isn't ready yet, don't do anything more).
1518 if (fullscreen == IsFullscreenOrPending())
1519 return false;
1520
1521 // Check whether we are trying to switch while the state is in transition.
1522 // The 2nd request gets dropped while messing up the internal state, so
1523 // disallow this.
1524 if (view_data_.is_fullscreen != desired_fullscreen_state_)
1525 return false;
1526
1527 if (fullscreen && !IsProcessingUserGesture())
1528 return false;
1529
1530 VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1531 desired_fullscreen_state_ = fullscreen;
1532
1533 if (fullscreen) {
1534 // Create the user gesture in case we're processing one that's pending.
1535 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1536 // WebKit does not resize the plugin to fill the screen in fullscreen mode,
1537 // so we will tweak plugin's attributes to support the expected behavior.
1538 KeepSizeAttributesBeforeFullscreen();
1539 SetSizeAttributesForFullscreen();
1540 container_->element().requestFullScreen();
1541 } else {
1542 container_->element().document().cancelFullScreen();
1543 }
1544 return true;
1545 }
1546
1547 void PluginInstance::FlashSetFullscreen(bool fullscreen, bool delay_report) {
1548 TRACE_EVENT0("ppapi", "PluginInstance::FlashSetFullscreen");
1549 // Keep a reference on the stack. See NOTE above.
1550 scoped_refptr<PluginInstance> ref(this);
1551
1552 // We check whether we are trying to switch to the state we're already going
1553 // to (i.e. if we're already switching to fullscreen but the fullscreen
1554 // container isn't ready yet, don't do anything more).
1555 if (fullscreen == FlashIsFullscreenOrPending())
1556 return;
1557
1558 // Unbind current 2D or 3D graphics context.
1559 VLOG(1) << "Setting fullscreen to " << (fullscreen ? "on" : "off");
1560 if (fullscreen) {
1561 DCHECK(!fullscreen_container_);
1562 fullscreen_container_ = delegate_->CreateFullscreenContainer(this);
1563 UpdateLayer();
1564 } else {
1565 DCHECK(fullscreen_container_);
1566 fullscreen_container_->Destroy();
1567 fullscreen_container_ = NULL;
1568 UpdateFlashFullscreenState(false);
1569 if (!delay_report) {
1570 ReportGeometry();
1571 } else {
1572 base::MessageLoop::current()->PostTask(
1573 FROM_HERE, base::Bind(&PluginInstance::ReportGeometry, this));
1574 }
1575 }
1576 }
1577
1578 void PluginInstance::UpdateFlashFullscreenState(bool flash_fullscreen) {
1579 bool is_mouselock_pending = TrackedCallback::IsPending(lock_mouse_callback_);
1580
1581 if (flash_fullscreen == flash_fullscreen_) {
1582 // Manually clear callback when fullscreen fails with mouselock pending.
1583 if (!flash_fullscreen && is_mouselock_pending)
1584 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1585 return;
1586 }
1587
1588 PPB_Graphics3D_Impl* graphics_3d = bound_graphics_3d_.get();
1589 if (graphics_3d)
1590 UpdateLayer();
1591
1592 bool old_plugin_focus = PluginHasFocus();
1593 flash_fullscreen_ = flash_fullscreen;
1594 if (is_mouselock_pending && !delegate()->IsMouseLocked(this)) {
1595 if (!IsProcessingUserGesture() &&
1596 !module_->permissions().HasPermission(
1597 ::ppapi::PERMISSION_BYPASS_USER_GESTURE)) {
1598 lock_mouse_callback_->Run(PP_ERROR_NO_USER_GESTURE);
1599 } else {
1600 // Open a user gesture here so the Webkit user gesture checks will succeed
1601 // for out-of-process plugins.
1602 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
1603 if (!delegate()->LockMouse(this))
1604 lock_mouse_callback_->Run(PP_ERROR_FAILED);
1605 }
1606 }
1607
1608 if (PluginHasFocus() != old_plugin_focus)
1609 SendFocusChangeNotification();
1610 }
1611
1612 int32_t PluginInstance::Navigate(const ::ppapi::URLRequestInfoData& request,
1613 const char* target,
1614 bool from_user_action) {
1615 if (!container_)
1616 return PP_ERROR_FAILED;
1617
1618 WebDocument document = container_->element().document();
1619 WebFrame* frame = document.frame();
1620 if (!frame)
1621 return PP_ERROR_FAILED;
1622
1623 ::ppapi::URLRequestInfoData completed_request = request;
1624
1625 WebURLRequest web_request;
1626 if (!CreateWebURLRequest(&completed_request, frame, &web_request))
1627 return PP_ERROR_FAILED;
1628 web_request.setFirstPartyForCookies(document.firstPartyForCookies());
1629 web_request.setHasUserGesture(from_user_action);
1630
1631 GURL gurl(web_request.url());
1632 if (gurl.SchemeIs("javascript")) {
1633 // In imitation of the NPAPI implementation, only |target_frame == frame| is
1634 // allowed for security reasons.
1635 WebFrame* target_frame =
1636 frame->view()->findFrameByName(WebString::fromUTF8(target), frame);
1637 if (target_frame != frame)
1638 return PP_ERROR_NOACCESS;
1639
1640 // TODO(viettrungluu): NPAPI sends the result back to the plugin -- do we
1641 // need that?
1642 WebString result = container_->executeScriptURL(gurl, from_user_action);
1643 return result.isNull() ? PP_ERROR_FAILED : PP_OK;
1644 }
1645
1646 // Only GETs and POSTs are supported.
1647 if (web_request.httpMethod() != "GET" &&
1648 web_request.httpMethod() != "POST")
1649 return PP_ERROR_BADARGUMENT;
1650
1651 WebString target_str = WebString::fromUTF8(target);
1652 container_->loadFrameRequest(web_request, target_str, false, NULL);
1653 return PP_OK;
1654 }
1655
1656 bool PluginInstance::IsRectTopmost(const gfx::Rect& rect) {
1657 if (flash_fullscreen_)
1658 return true;
1659
1660 return container_->isRectTopmost(rect);
1661 }
1662
1663 bool PluginInstance::IsViewAccelerated() {
1664 if (!container_)
1665 return false;
1666
1667 WebDocument document = container_->element().document();
1668 WebFrame* frame = document.frame();
1669 if (!frame)
1670 return false;
1671 WebView* view = frame->view();
1672 if (!view)
1673 return false;
1674
1675 return view->isAcceleratedCompositingActive();
1676 }
1677
1678 PluginDelegate::PlatformContext3D* PluginInstance::CreateContext3D() {
1679 return delegate_->CreateContext3D();
1680 }
1681
1682 bool PluginInstance::PrintPDFOutput(PP_Resource print_output,
1683 WebKit::WebCanvas* canvas) {
1684 #if defined(ENABLE_PRINTING)
1685 ::ppapi::thunk::EnterResourceNoLock<PPB_Buffer_API> enter(print_output, true);
1686 if (enter.failed())
1687 return false;
1688
1689 BufferAutoMapper mapper(enter.object());
1690 if (!mapper.data() || !mapper.size()) {
1691 NOTREACHED();
1692 return false;
1693 }
1694 #if defined(OS_WIN)
1695 // For Windows, we need the PDF DLL to render the output PDF to a DC.
1696 HMODULE pdf_module = GetModuleHandle(L"pdf.dll");
1697 if (!pdf_module)
1698 return false;
1699 RenderPDFPageToDCProc render_proc =
1700 reinterpret_cast<RenderPDFPageToDCProc>(
1701 GetProcAddress(pdf_module, "RenderPDFPageToDC"));
1702 if (!render_proc)
1703 return false;
1704 #endif // defined(OS_WIN)
1705
1706 bool ret = false;
1707 #if defined(OS_LINUX) || defined(OS_MACOSX)
1708 // On Linux we just set the final bits in the native metafile
1709 // (NativeMetafile and PreviewMetafile must have compatible formats,
1710 // i.e. both PDF for this to work).
1711 printing::Metafile* metafile =
1712 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1713 DCHECK(metafile != NULL);
1714 if (metafile)
1715 ret = metafile->InitFromData(mapper.data(), mapper.size());
1716 #elif defined(OS_WIN)
1717 printing::Metafile* metafile =
1718 printing::MetafileSkiaWrapper::GetMetafileFromCanvas(*canvas);
1719 if (metafile) {
1720 // We only have a metafile when doing print preview, so we just want to
1721 // pass the PDF off to preview.
1722 ret = metafile->InitFromData(mapper.data(), mapper.size());
1723 } else {
1724 // On Windows, we now need to render the PDF to the DC that backs the
1725 // supplied canvas.
1726 HDC dc = skia::BeginPlatformPaint(canvas);
1727 DrawEmptyRectangle(dc);
1728 gfx::Size size_in_pixels;
1729 size_in_pixels.set_width(printing::ConvertUnit(
1730 current_print_settings_.printable_area.size.width,
1731 static_cast<int>(printing::kPointsPerInch),
1732 current_print_settings_.dpi));
1733 size_in_pixels.set_height(printing::ConvertUnit(
1734 current_print_settings_.printable_area.size.height,
1735 static_cast<int>(printing::kPointsPerInch),
1736 current_print_settings_.dpi));
1737 // We need to scale down DC to fit an entire page into DC available area.
1738 // First, we'll try to use default scaling based on the 72dpi that is
1739 // used in webkit for printing.
1740 // If default scaling is not enough to fit the entire PDF without
1741 // Current metafile is based on screen DC and have current screen size.
1742 // Writing outside of those boundaries will result in the cut-off output.
1743 // On metafiles (this is the case here), scaling down will still record
1744 // original coordinates and we'll be able to print in full resolution.
1745 // Before playback we'll need to counter the scaling up that will happen
1746 // in the browser (printed_document_win.cc).
1747 double dynamic_scale = gfx::CalculatePageScale(dc, size_in_pixels.width(),
1748 size_in_pixels.height());
1749 double page_scale = static_cast<double>(printing::kPointsPerInch) /
1750 static_cast<double>(current_print_settings_.dpi);
1751
1752 if (dynamic_scale < page_scale) {
1753 page_scale = dynamic_scale;
1754 printing::MetafileSkiaWrapper::SetCustomScaleOnCanvas(*canvas,
1755 page_scale);
1756 }
1757
1758 gfx::ScaleDC(dc, page_scale);
1759
1760 ret = render_proc(static_cast<unsigned char*>(mapper.data()), mapper.size(),
1761 0, dc, current_print_settings_.dpi,
1762 current_print_settings_.dpi, 0, 0, size_in_pixels.width(),
1763 size_in_pixels.height(), true, false, true, true, true);
1764 skia::EndPlatformPaint(canvas);
1765 }
1766 #endif // defined(OS_WIN)
1767
1768 return ret;
1769 #else // defined(ENABLE_PRINTING)
1770 return false;
1771 #endif
1772 }
1773
1774 PluginDelegate::PlatformGraphics2D* PluginInstance::GetBoundGraphics2D() const {
1775 return bound_graphics_2d_platform_;
1776 }
1777
1778 static void IgnoreCallback(unsigned, bool) {}
1779
1780 void PluginInstance::UpdateLayer() {
1781 if (!container_)
1782 return;
1783
1784 gpu::Mailbox mailbox;
1785 if (bound_graphics_3d_.get()) {
1786 PluginDelegate::PlatformContext3D* context =
1787 bound_graphics_3d_->platform_context();
1788 context->GetBackingMailbox(&mailbox);
1789 }
1790 bool want_layer = !mailbox.IsZero();
1791
1792 if (want_layer == !!texture_layer_.get() &&
1793 layer_bound_to_fullscreen_ == !!fullscreen_container_)
1794 return;
1795
1796 if (texture_layer_.get()) {
1797 if (!layer_bound_to_fullscreen_)
1798 container_->setWebLayer(NULL);
1799 else if (fullscreen_container_)
1800 fullscreen_container_->SetLayer(NULL);
1801 web_layer_.reset();
1802 texture_layer_ = NULL;
1803 }
1804 if (want_layer) {
1805 DCHECK(bound_graphics_3d_.get());
1806 texture_layer_ = cc::TextureLayer::CreateForMailbox(NULL);
1807 web_layer_.reset(new webkit::WebLayerImpl(texture_layer_));
1808 if (fullscreen_container_) {
1809 fullscreen_container_->SetLayer(web_layer_.get());
1810 // Ignore transparency in fullscreen, since that's what Flash always
1811 // wants to do, and that lets it not recreate a context if
1812 // wmode=transparent was specified.
1813 texture_layer_->SetContentsOpaque(true);
1814 } else {
1815 container_->setWebLayer(web_layer_.get());
1816 texture_layer_->SetContentsOpaque(bound_graphics_3d_->IsOpaque());
1817 }
1818 texture_layer_->SetTextureMailbox(
1819 cc::TextureMailbox(mailbox, base::Bind(&IgnoreCallback), 0));
1820 }
1821 layer_bound_to_fullscreen_ = !!fullscreen_container_;
1822 }
1823
1824 void PluginInstance::AddPluginObject(PluginObject* plugin_object) {
1825 DCHECK(live_plugin_objects_.find(plugin_object) ==
1826 live_plugin_objects_.end());
1827 live_plugin_objects_.insert(plugin_object);
1828 }
1829
1830 void PluginInstance::RemovePluginObject(PluginObject* plugin_object) {
1831 // Don't actually verify that the object is in the set since during module
1832 // deletion we'll be in the process of freeing them.
1833 live_plugin_objects_.erase(plugin_object);
1834 }
1835
1836 bool PluginInstance::IsFullPagePlugin() const {
1837 WebFrame* frame = container()->element().document().frame();
1838 return frame->view()->mainFrame()->document().isPluginDocument();
1839 }
1840
1841 bool PluginInstance::IsProcessingUserGesture() {
1842 PP_TimeTicks now =
1843 ::ppapi::TimeTicksToPPTimeTicks(base::TimeTicks::Now());
1844 // Give a lot of slack so tests won't be flaky.
1845 const PP_TimeTicks kUserGestureDurationInSeconds = 10.0;
1846 return pending_user_gesture_token_.hasGestures() &&
1847 (now - pending_user_gesture_ < kUserGestureDurationInSeconds);
1848 }
1849
1850 WebUserGestureToken PluginInstance::CurrentUserGestureToken() {
1851 if (!IsProcessingUserGesture())
1852 pending_user_gesture_token_ = WebUserGestureToken();
1853 return pending_user_gesture_token_;
1854 }
1855
1856 void PluginInstance::OnLockMouseACK(bool succeeded) {
1857 if (TrackedCallback::IsPending(lock_mouse_callback_))
1858 lock_mouse_callback_->Run(succeeded ? PP_OK : PP_ERROR_FAILED);
1859 }
1860
1861 void PluginInstance::OnMouseLockLost() {
1862 if (LoadMouseLockInterface())
1863 plugin_mouse_lock_interface_->MouseLockLost(pp_instance());
1864 }
1865
1866 void PluginInstance::HandleMouseLockedInputEvent(
1867 const WebKit::WebMouseEvent& event) {
1868 // |cursor_info| is ignored since it is hidden when the mouse is locked.
1869 WebKit::WebCursorInfo cursor_info;
1870 HandleInputEvent(event, &cursor_info);
1871 }
1872
1873 void PluginInstance::SimulateInputEvent(const InputEventData& input_event) {
1874 WebView* web_view = container()->element().document().frame()->view();
1875 if (!web_view) {
1876 NOTREACHED();
1877 return;
1878 }
1879
1880 bool handled = SimulateIMEEvent(input_event);
1881 if (handled)
1882 return;
1883
1884 std::vector<linked_ptr<WebInputEvent> > events =
1885 CreateSimulatedWebInputEvents(
1886 input_event,
1887 view_data_.rect.point.x + view_data_.rect.size.width / 2,
1888 view_data_.rect.point.y + view_data_.rect.size.height / 2);
1889 for (std::vector<linked_ptr<WebInputEvent> >::iterator it = events.begin();
1890 it != events.end(); ++it) {
1891 web_view->handleInputEvent(*it->get());
1892 }
1893 }
1894
1895 bool PluginInstance::SimulateIMEEvent(const InputEventData& input_event) {
1896 switch (input_event.event_type) {
1897 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START:
1898 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE:
1899 SimulateImeSetCompositionEvent(input_event);
1900 break;
1901 case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END:
1902 DCHECK(input_event.character_text.empty());
1903 SimulateImeSetCompositionEvent(input_event);
1904 break;
1905 case PP_INPUTEVENT_TYPE_IME_TEXT:
1906 delegate()->SimulateImeConfirmComposition(
1907 UTF8ToUTF16(input_event.character_text));
1908 break;
1909 default:
1910 return false;
1911 }
1912 return true;
1913 }
1914
1915 void PluginInstance::SimulateImeSetCompositionEvent(
1916 const InputEventData& input_event) {
1917 std::vector<size_t> offsets;
1918 offsets.push_back(input_event.composition_selection_start);
1919 offsets.push_back(input_event.composition_selection_end);
1920 offsets.insert(offsets.end(),
1921 input_event.composition_segment_offsets.begin(),
1922 input_event.composition_segment_offsets.end());
1923
1924 base::string16 utf16_text =
1925 base::UTF8ToUTF16AndAdjustOffsets(input_event.character_text, &offsets);
1926
1927 std::vector<WebKit::WebCompositionUnderline> underlines;
1928 for (size_t i = 2; i + 1 < offsets.size(); ++i) {
1929 WebKit::WebCompositionUnderline underline;
1930 underline.startOffset = offsets[i];
1931 underline.endOffset = offsets[i + 1];
1932 if (input_event.composition_target_segment == static_cast<int32_t>(i - 2))
1933 underline.thick = true;
1934 underlines.push_back(underline);
1935 }
1936
1937 delegate()->SimulateImeSetComposition(
1938 utf16_text, underlines, offsets[0], offsets[1]);
1939 }
1940
1941 ContentDecryptorDelegate* PluginInstance::GetContentDecryptorDelegate() {
1942 if (content_decryptor_delegate_)
1943 return content_decryptor_delegate_.get();
1944
1945 const PPP_ContentDecryptor_Private* plugin_decryption_interface =
1946 static_cast<const PPP_ContentDecryptor_Private*>(
1947 module_->GetPluginInterface(
1948 PPP_CONTENTDECRYPTOR_PRIVATE_INTERFACE));
1949 if (!plugin_decryption_interface)
1950 return NULL;
1951
1952 content_decryptor_delegate_.reset(
1953 new ContentDecryptorDelegate(pp_instance_, plugin_decryption_interface));
1954 return content_decryptor_delegate_.get();
1955 }
1956
1957 PP_Bool PluginInstance::BindGraphics(PP_Instance instance,
1958 PP_Resource device) {
1959 TRACE_EVENT0("ppapi", "PluginInstance::BindGraphics");
1960 // The Graphics3D instance can't be destroyed until we call
1961 // UpdateLayer().
1962 scoped_refptr< ::ppapi::Resource> old_graphics = bound_graphics_3d_.get();
1963 if (bound_graphics_3d_.get()) {
1964 bound_graphics_3d_->BindToInstance(false);
1965 bound_graphics_3d_ = NULL;
1966 }
1967 if (bound_graphics_2d_platform_) {
1968 GetBoundGraphics2D()->BindToInstance(NULL);
1969 bound_graphics_2d_platform_ = NULL;
1970 }
1971
1972 // Special-case clearing the current device.
1973 if (!device) {
1974 UpdateLayer();
1975 InvalidateRect(gfx::Rect());
1976 return PP_TRUE;
1977 }
1978
1979 // Refuse to bind if in transition to fullscreen with PPB_FlashFullscreen or
1980 // to/from fullscreen with PPB_Fullscreen.
1981 if ((fullscreen_container_ && !flash_fullscreen_) ||
1982 desired_fullscreen_state_ != view_data_.is_fullscreen)
1983 return PP_FALSE;
1984
1985 PluginDelegate::PlatformGraphics2D* graphics_2d =
1986 delegate_->GetGraphics2D(this, device);
1987 EnterResourceNoLock<PPB_Graphics3D_API> enter_3d(device, false);
1988 PPB_Graphics3D_Impl* graphics_3d = enter_3d.succeeded() ?
1989 static_cast<PPB_Graphics3D_Impl*>(enter_3d.object()) : NULL;
1990
1991 if (graphics_2d) {
1992 if (graphics_2d->BindToInstance(this)) {
1993 bound_graphics_2d_platform_ = graphics_2d;
1994 UpdateLayer();
1995 return PP_TRUE;
1996 }
1997 } else if (graphics_3d) {
1998 // Make sure graphics can only be bound to the instance it is
1999 // associated with.
2000 if (graphics_3d->pp_instance() == pp_instance() &&
2001 graphics_3d->BindToInstance(true)) {
2002 bound_graphics_3d_ = graphics_3d;
2003 UpdateLayer();
2004 return PP_TRUE;
2005 }
2006 }
2007
2008 // The instance cannot be bound or the device is not a valid resource type.
2009 return PP_FALSE;
2010 }
2011
2012 PP_Bool PluginInstance::IsFullFrame(PP_Instance instance) {
2013 return PP_FromBool(full_frame());
2014 }
2015
2016 const ViewData* PluginInstance::GetViewData(PP_Instance instance) {
2017 return &view_data_;
2018 }
2019
2020 PP_Bool PluginInstance::FlashIsFullscreen(PP_Instance instance) {
2021 return PP_FromBool(flash_fullscreen_);
2022 }
2023
2024 PP_Var PluginInstance::GetWindowObject(PP_Instance instance) {
2025 if (!container_)
2026 return PP_MakeUndefined();
2027
2028 WebFrame* frame = container_->element().document().frame();
2029 if (!frame)
2030 return PP_MakeUndefined();
2031
2032 return NPObjectToPPVar(this, frame->windowObject());
2033 }
2034
2035 PP_Var PluginInstance::GetOwnerElementObject(PP_Instance instance) {
2036 if (!container_)
2037 return PP_MakeUndefined();
2038 return NPObjectToPPVar(this, container_->scriptableObjectForElement());
2039 }
2040
2041 PP_Var PluginInstance::ExecuteScript(PP_Instance instance,
2042 PP_Var script,
2043 PP_Var* exception) {
2044 // Executing the script may remove the plugin from the DOM, so we need to keep
2045 // a reference to ourselves so that we can still process the result after the
2046 // WebBindings::evaluate() below.
2047 scoped_refptr<PluginInstance> ref(this);
2048 TryCatch try_catch(exception);
2049 if (try_catch.has_exception())
2050 return PP_MakeUndefined();
2051
2052 // Convert the script into an inconvenient NPString object.
2053 StringVar* script_string = StringVar::FromPPVar(script);
2054 if (!script_string) {
2055 try_catch.SetException("Script param to ExecuteScript must be a string.");
2056 return PP_MakeUndefined();
2057 }
2058 NPString np_script;
2059 np_script.UTF8Characters = script_string->value().c_str();
2060 np_script.UTF8Length = script_string->value().length();
2061
2062 // Get the current frame to pass to the evaluate function.
2063 WebFrame* frame = container_->element().document().frame();
2064 if (!frame) {
2065 try_catch.SetException("No frame to execute script in.");
2066 return PP_MakeUndefined();
2067 }
2068
2069 NPVariant result;
2070 bool ok = false;
2071 if (IsProcessingUserGesture()) {
2072 WebKit::WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2073 ok = WebBindings::evaluate(NULL, frame->windowObject(), &np_script,
2074 &result);
2075 } else {
2076 ok = WebBindings::evaluate(NULL, frame->windowObject(), &np_script,
2077 &result);
2078 }
2079 if (!ok) {
2080 // TryCatch doesn't catch the exceptions properly. Since this is only for
2081 // a trusted API, just set to a general exception message.
2082 try_catch.SetException("Exception caught");
2083 WebBindings::releaseVariantValue(&result);
2084 return PP_MakeUndefined();
2085 }
2086
2087 PP_Var ret = NPVariantToPPVar(this, &result);
2088 WebBindings::releaseVariantValue(&result);
2089 return ret;
2090 }
2091
2092 uint32_t PluginInstance::GetAudioHardwareOutputSampleRate(
2093 PP_Instance instance) {
2094 return delegate()->GetAudioHardwareOutputSampleRate();
2095 }
2096
2097 uint32_t PluginInstance::GetAudioHardwareOutputBufferSize(
2098 PP_Instance instance) {
2099 return delegate()->GetAudioHardwareOutputBufferSize();
2100 }
2101
2102 PP_Var PluginInstance::GetDefaultCharSet(PP_Instance instance) {
2103 std::string encoding = delegate()->GetDefaultEncoding();
2104 return StringVar::StringToPPVar(encoding);
2105 }
2106
2107 // These PPB_ContentDecryptor_Private calls are responses to
2108 // PPP_ContentDecryptor_Private calls made on |content_decryptor_delegate_|.
2109 // Therefore, |content_decryptor_delegate_| must have been initialized when
2110 // the following methods are called.
2111 void PluginInstance::NeedKey(PP_Instance instance,
2112 PP_Var key_system_var,
2113 PP_Var session_id_var,
2114 PP_Var init_data_var) {
2115 content_decryptor_delegate_->NeedKey(
2116 key_system_var, session_id_var, init_data_var);
2117 }
2118
2119 void PluginInstance::KeyAdded(PP_Instance instance,
2120 PP_Var key_system_var,
2121 PP_Var session_id_var) {
2122 content_decryptor_delegate_->KeyAdded(key_system_var, session_id_var);
2123 }
2124
2125 void PluginInstance::KeyMessage(PP_Instance instance,
2126 PP_Var key_system_var,
2127 PP_Var session_id_var,
2128 PP_Var message_var,
2129 PP_Var default_url_var) {
2130 content_decryptor_delegate_->KeyMessage(
2131 key_system_var, session_id_var, message_var, default_url_var);
2132 }
2133
2134 void PluginInstance::KeyError(PP_Instance instance,
2135 PP_Var key_system_var,
2136 PP_Var session_id_var,
2137 int32_t media_error,
2138 int32_t system_code) {
2139 content_decryptor_delegate_->KeyError(
2140 key_system_var, session_id_var, media_error, system_code);
2141 }
2142
2143 void PluginInstance::DeliverBlock(PP_Instance instance,
2144 PP_Resource decrypted_block,
2145 const PP_DecryptedBlockInfo* block_info) {
2146 content_decryptor_delegate_->DeliverBlock(decrypted_block, block_info);
2147 }
2148
2149 void PluginInstance::DecoderInitializeDone(PP_Instance instance,
2150 PP_DecryptorStreamType decoder_type,
2151 uint32_t request_id,
2152 PP_Bool success) {
2153 content_decryptor_delegate_->DecoderInitializeDone(
2154 decoder_type, request_id, success);
2155 }
2156
2157 void PluginInstance::DecoderDeinitializeDone(
2158 PP_Instance instance,
2159 PP_DecryptorStreamType decoder_type,
2160 uint32_t request_id) {
2161 content_decryptor_delegate_->DecoderDeinitializeDone(decoder_type,
2162 request_id);
2163 }
2164
2165 void PluginInstance::DecoderResetDone(PP_Instance instance,
2166 PP_DecryptorStreamType decoder_type,
2167 uint32_t request_id) {
2168 content_decryptor_delegate_->DecoderResetDone(decoder_type, request_id);
2169 }
2170
2171
2172 void PluginInstance::DeliverFrame(PP_Instance instance,
2173 PP_Resource decrypted_frame,
2174 const PP_DecryptedFrameInfo* frame_info) {
2175 content_decryptor_delegate_->DeliverFrame(decrypted_frame, frame_info);
2176 }
2177
2178 void PluginInstance::DeliverSamples(PP_Instance instance,
2179 PP_Resource audio_frames,
2180 const PP_DecryptedBlockInfo* block_info) {
2181 content_decryptor_delegate_->DeliverSamples(audio_frames, block_info);
2182 }
2183
2184 void PluginInstance::NumberOfFindResultsChanged(PP_Instance instance,
2185 int32_t total,
2186 PP_Bool final_result) {
2187 DCHECK_NE(find_identifier_, -1);
2188 delegate_->NumberOfFindResultsChanged(find_identifier_, total,
2189 PP_ToBool(final_result));
2190 }
2191
2192 void PluginInstance::SelectedFindResultChanged(PP_Instance instance,
2193 int32_t index) {
2194 DCHECK_NE(find_identifier_, -1);
2195 delegate_->SelectedFindResultChanged(find_identifier_, index);
2196 }
2197
2198 PP_Bool PluginInstance::IsFullscreen(PP_Instance instance) {
2199 return PP_FromBool(view_data_.is_fullscreen);
2200 }
2201
2202 PP_Bool PluginInstance::SetFullscreen(PP_Instance instance,
2203 PP_Bool fullscreen) {
2204 return PP_FromBool(SetFullscreen(PP_ToBool(fullscreen)));
2205 }
2206
2207 PP_Bool PluginInstance::GetScreenSize(PP_Instance instance, PP_Size* size) {
2208 gfx::Size screen_size = delegate()->GetScreenSize();
2209 *size = PP_MakeSize(screen_size.width(), screen_size.height());
2210 return PP_TRUE;
2211 }
2212
2213 ::ppapi::Resource* PluginInstance::GetSingletonResource(
2214 PP_Instance instance,
2215 ::ppapi::SingletonResourceID id) {
2216 // Flash APIs and some others aren't implemented in-process.
2217 switch (id) {
2218 case ::ppapi::BROKER_SINGLETON_ID:
2219 case ::ppapi::BROWSER_FONT_SINGLETON_ID:
2220 case ::ppapi::CRX_FILESYSTEM_SINGLETON_ID:
2221 case ::ppapi::EXTENSIONS_COMMON_SINGLETON_ID:
2222 case ::ppapi::FLASH_CLIPBOARD_SINGLETON_ID:
2223 case ::ppapi::FLASH_FILE_SINGLETON_ID:
2224 case ::ppapi::FLASH_FULLSCREEN_SINGLETON_ID:
2225 case ::ppapi::FLASH_SINGLETON_ID:
2226 case ::ppapi::NETWORK_PROXY_SINGLETON_ID:
2227 case ::ppapi::PDF_SINGLETON_ID:
2228 case ::ppapi::TRUETYPE_FONT_SINGLETON_ID:
2229 NOTIMPLEMENTED();
2230 return NULL;
2231 case ::ppapi::GAMEPAD_SINGLETON_ID:
2232 return gamepad_impl_.get();
2233 }
2234
2235 NOTREACHED();
2236 return NULL;
2237 }
2238
2239 int32_t PluginInstance::RequestInputEvents(PP_Instance instance,
2240 uint32_t event_classes) {
2241 input_event_mask_ |= event_classes;
2242 filtered_input_event_mask_ &= ~(event_classes);
2243 RequestInputEventsHelper(event_classes);
2244 return ValidateRequestInputEvents(false, event_classes);
2245 }
2246
2247 int32_t PluginInstance::RequestFilteringInputEvents(PP_Instance instance,
2248 uint32_t event_classes) {
2249 filtered_input_event_mask_ |= event_classes;
2250 input_event_mask_ &= ~(event_classes);
2251 RequestInputEventsHelper(event_classes);
2252 return ValidateRequestInputEvents(true, event_classes);
2253 }
2254
2255 void PluginInstance::ClearInputEventRequest(PP_Instance instance,
2256 uint32_t event_classes) {
2257 input_event_mask_ &= ~(event_classes);
2258 filtered_input_event_mask_ &= ~(event_classes);
2259 RequestInputEventsHelper(event_classes);
2260 }
2261
2262 void PluginInstance::ZoomChanged(PP_Instance instance, double factor) {
2263 // We only want to tell the page to change its zoom if the whole page is the
2264 // plugin. If we're in an iframe, then don't do anything.
2265 if (!IsFullPagePlugin())
2266 return;
2267 container()->zoomLevelChanged(WebView::zoomFactorToZoomLevel(factor));
2268 }
2269
2270 void PluginInstance::ZoomLimitsChanged(PP_Instance instance,
2271 double minimum_factor,
2272 double maximium_factor) {
2273 if (minimum_factor > maximium_factor) {
2274 NOTREACHED();
2275 return;
2276 }
2277 delegate()->ZoomLimitsChanged(minimum_factor, maximium_factor);
2278 }
2279
2280 void PluginInstance::PostMessage(PP_Instance instance, PP_Var message) {
2281 message_channel_->PostMessageToJavaScript(message);
2282 }
2283
2284 PP_Bool PluginInstance::SetCursor(PP_Instance instance,
2285 PP_MouseCursor_Type type,
2286 PP_Resource image,
2287 const PP_Point* hot_spot) {
2288 if (!ValidateSetCursorParams(type, image, hot_spot))
2289 return PP_FALSE;
2290
2291 if (type != PP_MOUSECURSOR_TYPE_CUSTOM) {
2292 DoSetCursor(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
2293 return PP_TRUE;
2294 }
2295
2296 EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
2297 if (enter.failed())
2298 return PP_FALSE;
2299 PPB_ImageData_Impl* image_data =
2300 static_cast<PPB_ImageData_Impl*>(enter.object());
2301
2302 ImageDataAutoMapper auto_mapper(image_data);
2303 if (!auto_mapper.is_valid())
2304 return PP_FALSE;
2305
2306 scoped_ptr<WebCursorInfo> custom_cursor(
2307 new WebCursorInfo(WebCursorInfo::TypeCustom));
2308 custom_cursor->hotSpot.x = hot_spot->x;
2309 custom_cursor->hotSpot.y = hot_spot->y;
2310
2311 const SkBitmap* bitmap = image_data->GetMappedBitmap();
2312 // Make a deep copy, so that the cursor remains valid even after the original
2313 // image data gets freed.
2314 if (!bitmap->copyTo(&custom_cursor->customImage.getSkBitmap(),
2315 bitmap->config())) {
2316 return PP_FALSE;
2317 }
2318
2319 DoSetCursor(custom_cursor.release());
2320 return PP_TRUE;
2321 }
2322
2323 int32_t PluginInstance::LockMouse(PP_Instance instance,
2324 scoped_refptr<TrackedCallback> callback) {
2325 if (TrackedCallback::IsPending(lock_mouse_callback_))
2326 return PP_ERROR_INPROGRESS;
2327
2328 if (delegate()->IsMouseLocked(this))
2329 return PP_OK;
2330
2331 if (!CanAccessMainFrame())
2332 return PP_ERROR_NOACCESS;
2333
2334 if (!IsProcessingUserGesture())
2335 return PP_ERROR_NO_USER_GESTURE;
2336
2337 // Attempt mouselock only if Flash isn't waiting on fullscreen, otherwise
2338 // we wait and call LockMouse() in UpdateFlashFullscreenState().
2339 if (!FlashIsFullscreenOrPending() || flash_fullscreen()) {
2340 // Open a user gesture here so the Webkit user gesture checks will succeed
2341 // for out-of-process plugins.
2342 WebScopedUserGesture user_gesture(CurrentUserGestureToken());
2343 if (!delegate()->LockMouse(this))
2344 return PP_ERROR_FAILED;
2345 }
2346
2347 // Either mouselock succeeded or a Flash fullscreen is pending.
2348 lock_mouse_callback_ = callback;
2349 return PP_OK_COMPLETIONPENDING;
2350 }
2351
2352 void PluginInstance::UnlockMouse(PP_Instance instance) {
2353 delegate()->UnlockMouse(this);
2354 }
2355
2356 void PluginInstance::SetTextInputType(PP_Instance instance,
2357 PP_TextInput_Type type) {
2358 int itype = type;
2359 if (itype < 0 || itype > ui::TEXT_INPUT_TYPE_URL)
2360 itype = ui::TEXT_INPUT_TYPE_NONE;
2361 text_input_type_ = static_cast<ui::TextInputType>(itype);
2362 delegate()->PluginTextInputTypeChanged(this);
2363 }
2364
2365 void PluginInstance::UpdateCaretPosition(PP_Instance instance,
2366 const PP_Rect& caret,
2367 const PP_Rect& bounding_box) {
2368 text_input_caret_ = PP_ToGfxRect(caret);
2369 text_input_caret_bounds_ = PP_ToGfxRect(bounding_box);
2370 text_input_caret_set_ = true;
2371 delegate()->PluginCaretPositionChanged(this);
2372 }
2373
2374 void PluginInstance::CancelCompositionText(PP_Instance instance) {
2375 delegate()->PluginRequestedCancelComposition(this);
2376 }
2377
2378 void PluginInstance::SelectionChanged(PP_Instance instance) {
2379 // TODO(kinaba): currently the browser always calls RequestSurroundingText.
2380 // It can be optimized so that it won't call it back until the information
2381 // is really needed.
2382
2383 // Avoid calling in nested context or else this will reenter the plugin. This
2384 // uses a weak pointer rather than exploiting the fact that this class is
2385 // refcounted because we don't actually want this operation to affect the
2386 // lifetime of the instance.
2387 base::MessageLoop::current()->PostTask(
2388 FROM_HERE,
2389 base::Bind(&PluginInstance::RequestSurroundingText,
2390 AsWeakPtr(),
2391 static_cast<size_t>(kExtraCharsForTextInput)));
2392 }
2393
2394 void PluginInstance::UpdateSurroundingText(PP_Instance instance,
2395 const char* text,
2396 uint32_t caret,
2397 uint32_t anchor) {
2398 surrounding_text_ = text;
2399 selection_caret_ = caret;
2400 selection_anchor_ = anchor;
2401 delegate()->PluginSelectionChanged(this);
2402 }
2403
2404 PP_Var PluginInstance::ResolveRelativeToDocument(
2405 PP_Instance instance,
2406 PP_Var relative,
2407 PP_URLComponents_Dev* components) {
2408 StringVar* relative_string = StringVar::FromPPVar(relative);
2409 if (!relative_string)
2410 return PP_MakeNull();
2411
2412 WebElement plugin_element = container()->element();
2413 GURL document_url = plugin_element.document().baseURL();
2414 return ::ppapi::PPB_URLUtil_Shared::GenerateURLReturn(
2415 document_url.Resolve(relative_string->value()),
2416 components);
2417 }
2418
2419 PP_Bool PluginInstance::DocumentCanRequest(PP_Instance instance, PP_Var url) {
2420 StringVar* url_string = StringVar::FromPPVar(url);
2421 if (!url_string)
2422 return PP_FALSE;
2423
2424 WebKit::WebSecurityOrigin security_origin;
2425 if (!SecurityOriginForInstance(instance, &security_origin))
2426 return PP_FALSE;
2427
2428 GURL gurl(url_string->value());
2429 if (!gurl.is_valid())
2430 return PP_FALSE;
2431
2432 return BoolToPPBool(security_origin.canRequest(gurl));
2433 }
2434
2435 PP_Bool PluginInstance::DocumentCanAccessDocument(PP_Instance instance,
2436 PP_Instance target) {
2437 WebKit::WebSecurityOrigin our_origin;
2438 if (!SecurityOriginForInstance(instance, &our_origin))
2439 return PP_FALSE;
2440
2441 WebKit::WebSecurityOrigin target_origin;
2442 if (!SecurityOriginForInstance(instance, &target_origin))
2443 return PP_FALSE;
2444
2445 return BoolToPPBool(our_origin.canAccess(target_origin));
2446 }
2447
2448 PP_Var PluginInstance::GetDocumentURL(PP_Instance instance,
2449 PP_URLComponents_Dev* components) {
2450 WebKit::WebDocument document = container()->element().document();
2451 return ::ppapi::PPB_URLUtil_Shared::GenerateURLReturn(document.url(),
2452 components);
2453 }
2454
2455 PP_Var PluginInstance::GetPluginInstanceURL(
2456 PP_Instance instance,
2457 PP_URLComponents_Dev* components) {
2458 return ::ppapi::PPB_URLUtil_Shared::GenerateURLReturn(plugin_url_,
2459 components);
2460 }
2461
2462 PP_ExternalPluginResult PluginInstance::ResetAsProxied(
2463 scoped_refptr<PluginModule> module) {
2464 // Save the original module and switch over to the new one now that this
2465 // plugin is using the IPC-based proxy.
2466 original_module_ = module_;
2467 module_ = module;
2468
2469 // Don't send any messages to the plugin until DidCreate() has finished.
2470 message_channel_->QueueJavaScriptMessages();
2471
2472 // For NaCl instances, remember the NaCl plugin instance interface, so we
2473 // can shut it down by calling its DidDestroy in our Delete() method.
2474 original_instance_interface_.reset(instance_interface_.release());
2475
2476 base::Callback<const void*(const char*)> get_plugin_interface_func =
2477 base::Bind(&PluginModule::GetPluginInterface, module_.get());
2478 PPP_Instance_Combined* ppp_instance_combined =
2479 PPP_Instance_Combined::Create(get_plugin_interface_func);
2480 if (!ppp_instance_combined) {
2481 // The proxy must support at least one usable PPP_Instance interface.
2482 // While this could be a failure to implement the interface in the NaCl
2483 // module, it is more likely that the NaCl process has crashed. Either
2484 // way, report that module initialization failed.
2485 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2486 }
2487
2488 instance_interface_.reset(ppp_instance_combined);
2489 // Clear all PPP interfaces we may have cached.
2490 plugin_find_interface_ = NULL;
2491 plugin_input_event_interface_ = NULL;
2492 checked_for_plugin_input_event_interface_ = false;
2493 plugin_messaging_interface_ = NULL;
2494 checked_for_plugin_messaging_interface_ = false;
2495 plugin_mouse_lock_interface_ = NULL;
2496 plugin_pdf_interface_ = NULL;
2497 checked_for_plugin_pdf_interface_ = false;
2498 plugin_private_interface_ = NULL;
2499 plugin_selection_interface_ = NULL;
2500 plugin_textinput_interface_ = NULL;
2501 plugin_zoom_interface_ = NULL;
2502
2503 // Re-send the DidCreate event via the proxy.
2504 scoped_ptr<const char*[]> argn_array(StringVectorToArgArray(argn_));
2505 scoped_ptr<const char*[]> argv_array(StringVectorToArgArray(argv_));
2506 if (!instance_interface_->DidCreate(pp_instance(), argn_.size(),
2507 argn_array.get(), argv_array.get()))
2508 return PP_EXTERNAL_PLUGIN_ERROR_INSTANCE;
2509 message_channel_->StopQueueingJavaScriptMessages();
2510
2511 // Clear sent_initial_did_change_view_ and cancel any pending DidChangeView
2512 // event. This way, SendDidChangeView will send the "current" view
2513 // immediately (before other events like HandleDocumentLoad).
2514 sent_initial_did_change_view_ = false;
2515 view_change_weak_ptr_factory_.InvalidateWeakPtrs();
2516 SendDidChangeView();
2517
2518 DCHECK(nacl_document_load_);
2519 nacl_document_load_ = false;
2520 if (!nacl_document_response_.isNull()) {
2521 document_loader_ = NULL;
2522 // Pass the response to the new proxy.
2523 HandleDocumentLoad(nacl_document_response_);
2524 nacl_document_response_ = WebKit::WebURLResponse();
2525 // Replay any document load events we've received to the real loader.
2526 nacl_document_loader_->ReplayReceivedData(document_loader_);
2527 nacl_document_loader_.reset(NULL);
2528 }
2529
2530 return PP_EXTERNAL_PLUGIN_OK;
2531 }
2532
2533 bool PluginInstance::IsValidInstanceOf(PluginModule* module) {
2534 DCHECK(module);
2535 return module == module_.get() ||
2536 module == original_module_.get();
2537 }
2538
2539 NPP PluginInstance::instanceNPP() {
2540 return npp_.get();
2541 }
2542
2543 v8::Isolate* PluginInstance::GetIsolate() const {
2544 return isolate_;
2545 }
2546
2547 PluginInstance* PluginInstance::Get(PP_Instance instance_id) {
2548 return HostGlobals::Get()->GetInstance(instance_id);
2549 }
2550
2551 ::ppapi::VarTracker* PluginInstance::GetVarTracker() {
2552 return HostGlobals::Get()->GetVarTracker();
2553 }
2554
2555 PP_Resource PluginInstance::CreateExternalFileReference(
2556 const base::FilePath& external_file_path) {
2557 webkit::ppapi::PPB_FileRef_Impl* ref =
2558 webkit::ppapi::PPB_FileRef_Impl::CreateExternal(
2559 pp_instance(), external_file_path, "");
2560 return ref->GetReference();
2561 }
2562
2563 PP_Resource PluginInstance::CreateImage(gfx::ImageSkia* source_image,
2564 float scale) {
2565 ui::ScaleFactor scale_factor = ui::GetScaleFactorFromScale(scale);
2566 gfx::ImageSkiaRep image_skia_rep = source_image->GetRepresentation(
2567 scale_factor);
2568
2569 if (image_skia_rep.is_null() || image_skia_rep.scale_factor() != scale_factor)
2570 return 0;
2571
2572 scoped_refptr<webkit::ppapi::PPB_ImageData_Impl> image_data(
2573 new webkit::ppapi::PPB_ImageData_Impl(
2574 pp_instance(),
2575 webkit::ppapi::PPB_ImageData_Impl::PLATFORM));
2576 if (!image_data->Init(
2577 webkit::ppapi::PPB_ImageData_Impl::GetNativeImageDataFormat(),
2578 image_skia_rep.pixel_width(),
2579 image_skia_rep.pixel_height(),
2580 false)) {
2581 return 0;
2582 }
2583
2584 webkit::ppapi::ImageDataAutoMapper mapper(image_data.get());
2585 if (!mapper.is_valid())
2586 return 0;
2587
2588 skia::PlatformCanvas* canvas = image_data->GetPlatformCanvas();
2589 // Note: Do not SkBitmap::copyTo the canvas bitmap directly because it will
2590 // ignore the allocated pixels in shared memory and re-allocate a new buffer.
2591 canvas->writePixels(image_skia_rep.sk_bitmap(), 0, 0);
2592
2593 return image_data->GetReference();
2594 }
2595
2596 base::FilePath PluginInstance::GetModulePath() {
2597 return module_->path();
2598 }
2599
2600 PP_ExternalPluginResult PluginInstance::SwitchToOutOfProcessProxy(
2601 const base::FilePath& file_path,
2602 ::ppapi::PpapiPermissions permissions,
2603 const IPC::ChannelHandle& channel_handle,
2604 base::ProcessId plugin_pid,
2605 int plugin_child_id) {
2606 // Create a new module for each instance of the external plugin that is using
2607 // the IPC based out-of-process proxy. We can't use the existing module,
2608 // because it is configured for the in-process plugin, and we must keep it
2609 // that way to allow the page to create other instances.
2610 scoped_refptr<webkit::ppapi::PluginModule> external_plugin_module(
2611 module_->CreateModuleForExternalPluginInstance());
2612
2613 content::RendererPpapiHost* renderer_ppapi_host =
2614 delegate_->CreateExternalPluginModule(
2615 external_plugin_module,
2616 file_path,
2617 permissions,
2618 channel_handle,
2619 plugin_pid,
2620 plugin_child_id);
2621 if (!renderer_ppapi_host) {
2622 DLOG(ERROR) << "CreateExternalPluginModule() failed";
2623 return PP_EXTERNAL_PLUGIN_ERROR_MODULE;
2624 }
2625
2626 // Finally, switch the instance to the proxy.
2627 return external_plugin_module->InitAsProxiedExternalPlugin(this);
2628 }
2629
2630 void PluginInstance::DoSetCursor(WebCursorInfo* cursor) {
2631 cursor_.reset(cursor);
2632 if (fullscreen_container_) {
2633 fullscreen_container_->DidChangeCursor(*cursor);
2634 } else {
2635 delegate()->DidChangeCursor(this, *cursor);
2636 }
2637 }
2638
2639 bool PluginInstance::CanAccessMainFrame() const {
2640 if (!container_)
2641 return false;
2642 WebKit::WebDocument containing_document = container_->element().document();
2643
2644 if (!containing_document.frame() ||
2645 !containing_document.frame()->view() ||
2646 !containing_document.frame()->view()->mainFrame()) {
2647 return false;
2648 }
2649 WebKit::WebDocument main_document =
2650 containing_document.frame()->view()->mainFrame()->document();
2651
2652 return containing_document.securityOrigin().canAccess(
2653 main_document.securityOrigin());
2654 }
2655
2656 void PluginInstance::KeepSizeAttributesBeforeFullscreen() {
2657 WebElement element = container_->element();
2658 width_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kWidth));
2659 height_before_fullscreen_ =
2660 element.getAttribute(WebString::fromUTF8(kHeight));
2661 border_before_fullscreen_ =
2662 element.getAttribute(WebString::fromUTF8(kBorder));
2663 style_before_fullscreen_ = element.getAttribute(WebString::fromUTF8(kStyle));
2664 }
2665
2666 void PluginInstance::SetSizeAttributesForFullscreen() {
2667 screen_size_for_fullscreen_ = delegate()->GetScreenSize();
2668 std::string width = StringPrintf("%d", screen_size_for_fullscreen_.width());
2669 std::string height = StringPrintf("%d", screen_size_for_fullscreen_.height());
2670
2671 WebElement element = container_->element();
2672 element.setAttribute(WebString::fromUTF8(kWidth), WebString::fromUTF8(width));
2673 element.setAttribute(WebString::fromUTF8(kHeight),
2674 WebString::fromUTF8(height));
2675 element.setAttribute(WebString::fromUTF8(kBorder), WebString::fromUTF8("0"));
2676
2677 // There should be no style settings that matter in fullscreen mode,
2678 // so just replace them instead of appending.
2679 // NOTE: "position: fixed" and "display: block" reset the plugin and
2680 // using %% settings might not work without them (e.g. if the plugin is a
2681 // child of a container element).
2682 std::string style;
2683 style += StringPrintf("width: %s !important; ", width.c_str());
2684 style += StringPrintf("height: %s !important; ", height.c_str());
2685 style += "margin: 0 !important; padding: 0 !important; border: 0 !important";
2686 container_->element().setAttribute(kStyle, WebString::fromUTF8(style));
2687 }
2688
2689 void PluginInstance::ResetSizeAttributesAfterFullscreen() {
2690 screen_size_for_fullscreen_ = gfx::Size();
2691 WebElement element = container_->element();
2692 element.setAttribute(WebString::fromUTF8(kWidth), width_before_fullscreen_);
2693 element.setAttribute(WebString::fromUTF8(kHeight), height_before_fullscreen_);
2694 element.setAttribute(WebString::fromUTF8(kBorder), border_before_fullscreen_);
2695 element.setAttribute(WebString::fromUTF8(kStyle), style_before_fullscreen_);
2696 }
2697
2698 } // namespace ppapi
2699 } // namespace webkit
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698