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