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 #ifndef CONTENT_RENDERER_PEPPER_PEPPER_PLUGIN_INSTANCE_IMPL_H_
      6 #define CONTENT_RENDERER_PEPPER_PEPPER_PLUGIN_INSTANCE_IMPL_H_
      7 
      8 #include <list>
      9 #include <set>
     10 #include <string>
     11 #include <vector>
     12 
     13 #include "base/compiler_specific.h"
     14 #include "base/memory/ref_counted.h"
     15 #include "base/memory/scoped_ptr.h"
     16 #include "base/memory/weak_ptr.h"
     17 #include "base/strings/string16.h"
     18 #include "cc/layers/texture_layer_client.h"
     19 #include "content/common/content_export.h"
     20 #include "content/public/renderer/pepper_plugin_instance.h"
     21 #include "content/renderer/mouse_lock_dispatcher.h"
     22 #include "content/renderer/pepper/ppp_pdf.h"
     23 #include "ppapi/c/dev/pp_cursor_type_dev.h"
     24 #include "ppapi/c/dev/ppp_find_dev.h"
     25 #include "ppapi/c/dev/ppp_printing_dev.h"
     26 #include "ppapi/c/dev/ppp_selection_dev.h"
     27 #include "ppapi/c/dev/ppp_text_input_dev.h"
     28 #include "ppapi/c/dev/ppp_zoom_dev.h"
     29 #include "ppapi/c/pp_completion_callback.h"
     30 #include "ppapi/c/pp_instance.h"
     31 #include "ppapi/c/pp_time.h"
     32 #include "ppapi/c/pp_var.h"
     33 #include "ppapi/c/ppb_audio_config.h"
     34 #include "ppapi/c/ppb_gamepad.h"
     35 #include "ppapi/c/ppb_input_event.h"
     36 #include "ppapi/c/ppp_graphics_3d.h"
     37 #include "ppapi/c/ppp_input_event.h"
     38 #include "ppapi/c/ppp_messaging.h"
     39 #include "ppapi/c/ppp_mouse_lock.h"
     40 #include "ppapi/c/private/ppb_content_decryptor_private.h"
     41 #include "ppapi/c/private/ppp_instance_private.h"
     42 #include "ppapi/shared_impl/ppb_instance_shared.h"
     43 #include "ppapi/shared_impl/ppb_view_shared.h"
     44 #include "ppapi/shared_impl/singleton_resource_id.h"
     45 #include "ppapi/shared_impl/tracked_callback.h"
     46 #include "ppapi/thunk/ppb_gamepad_api.h"
     47 #include "ppapi/thunk/resource_creation_api.h"
     48 #include "skia/ext/refptr.h"
     49 #include "third_party/WebKit/public/platform/WebCanvas.h"
     50 #include "third_party/WebKit/public/platform/WebString.h"
     51 #include "third_party/WebKit/public/platform/WebURLLoaderClient.h"
     52 #include "third_party/WebKit/public/platform/WebURLResponse.h"
     53 #include "third_party/WebKit/public/web/WebPlugin.h"
     54 #include "third_party/WebKit/public/web/WebUserGestureToken.h"
     55 #include "ui/base/ime/text_input_type.h"
     56 #include "ui/gfx/rect.h"
     57 #include "url/gurl.h"
     58 
     59 struct PP_Point;
     60 struct _NPP;
     61 
     62 class SkBitmap;
     63 class TransportDIB;
     64 
     65 namespace WebKit {
     66 class WebInputEvent;
     67 class WebLayer;
     68 class WebMouseEvent;
     69 class WebPluginContainer;
     70 class WebURLLoader;
     71 class WebURLResponse;
     72 struct WebCompositionUnderline;
     73 struct WebCursorInfo;
     74 struct WebURLError;
     75 struct WebPrintParams;
     76 }
     77 
     78 namespace cc {
     79 class TextureLayer;
     80 }
     81 
     82 namespace ppapi {
     83 class Resource;
     84 struct InputEventData;
     85 struct PPP_Instance_Combined;
     86 }
     87 
     88 namespace ui {
     89 class Range;
     90 }
     91 
     92 namespace v8 {
     93 class Isolate;
     94 }
     95 
     96 namespace content {
     97 
     98 class ContentDecryptorDelegate;
     99 class FullscreenContainer;
    100 class MessageChannel;
    101 class PepperGraphics2DHost;
    102 class PluginModule;
    103 class PluginObject;
    104 class PPB_Graphics3D_Impl;
    105 class PPB_ImageData_Impl;
    106 class PPB_URLLoader_Impl;
    107 class RenderViewImpl;
    108 
    109 // Represents one time a plugin appears on one web page.
    110 //
    111 // Note: to get from a PP_Instance to a PepperPluginInstance*, use the
    112 // ResourceTracker.
    113 class CONTENT_EXPORT PepperPluginInstanceImpl
    114     : public base::RefCounted<PepperPluginInstanceImpl>,
    115       public base::SupportsWeakPtr<PepperPluginInstanceImpl>,
    116       public NON_EXPORTED_BASE(PepperPluginInstance),
    117       public ppapi::PPB_Instance_Shared {
    118  public:
    119   // Create and return a PepperPluginInstanceImpl object which supports the most
    120   // recent version of PPP_Instance possible by querying the given
    121   // get_plugin_interface function. If the plugin does not support any valid
    122   // PPP_Instance interface, returns NULL.
    123   static PepperPluginInstanceImpl* Create(
    124       RenderViewImpl* render_view,
    125       PluginModule* module,
    126       WebKit::WebPluginContainer* container,
    127       const GURL& plugin_url);
    128   RenderViewImpl* render_view() const { return render_view_; }
    129   PluginModule* module() const { return module_.get(); }
    130   MessageChannel& message_channel() { return *message_channel_; }
    131 
    132   WebKit::WebPluginContainer* container() const { return container_; }
    133 
    134   // Returns the PP_Instance uniquely identifying this instance. Guaranteed
    135   // nonzero.
    136   PP_Instance pp_instance() const { return pp_instance_; }
    137 
    138   ppapi::thunk::ResourceCreationAPI& resource_creation() {
    139     return *resource_creation_.get();
    140   }
    141 
    142   // Does some pre-destructor cleanup on the instance. This is necessary
    143   // because some cleanup depends on the plugin instance still existing (like
    144   // calling the plugin's DidDestroy function). This function is called from
    145   // the WebPlugin implementation when WebKit is about to remove the plugin.
    146   void Delete();
    147 
    148   // Paints the current backing store to the web page.
    149   void Paint(WebKit::WebCanvas* canvas,
    150              const gfx::Rect& plugin_rect,
    151              const gfx::Rect& paint_rect);
    152 
    153   // Schedules a paint of the page for the given region. The coordinates are
    154   // relative to the top-left of the plugin. This does nothing if the plugin
    155   // has not yet been positioned. You can supply an empty gfx::Rect() to
    156   // invalidate the entire plugin.
    157   void InvalidateRect(const gfx::Rect& rect);
    158 
    159   // Schedules a scroll of the plugin.  This uses optimized scrolling only for
    160   // full-frame plugins, as otherwise there could be other elements on top.  The
    161   // slow path can also be triggered if there is an overlapping frame.
    162   void ScrollRect(int dx, int dy, const gfx::Rect& rect);
    163 
    164   // Commit the backing texture to the screen once the side effects some
    165   // rendering up to an offscreen SwapBuffers are visible.
    166   void CommitBackingTexture();
    167 
    168   // Called when the out-of-process plugin implementing this instance crashed.
    169   void InstanceCrashed();
    170 
    171   // PPB_Instance and PPB_Instance_Private implementation.
    172   bool full_frame() const { return full_frame_; }
    173   const ppapi::ViewData& view_data() const { return view_data_; }
    174 
    175   // PPP_Instance and PPP_Instance_Private.
    176   bool Initialize(const std::vector<std::string>& arg_names,
    177                   const std::vector<std::string>& arg_values,
    178                   bool full_frame);
    179   bool HandleDocumentLoad(const WebKit::WebURLResponse& response);
    180   bool HandleInputEvent(const WebKit::WebInputEvent& event,
    181                         WebKit::WebCursorInfo* cursor_info);
    182   PP_Var GetInstanceObject();
    183   void ViewChanged(const gfx::Rect& position, const gfx::Rect& clip,
    184                    const std::vector<gfx::Rect>& cut_outs_rects);
    185 
    186   // Handlers for composition events.
    187   bool HandleCompositionStart(const base::string16& text);
    188   bool HandleCompositionUpdate(
    189       const base::string16& text,
    190       const std::vector<WebKit::WebCompositionUnderline>& underlines,
    191       int selection_start,
    192       int selection_end);
    193   bool HandleCompositionEnd(const base::string16& text);
    194   bool HandleTextInput(const base::string16& text);
    195 
    196   // Gets the current text input status.
    197   ui::TextInputType text_input_type() const { return text_input_type_; }
    198   gfx::Rect GetCaretBounds() const;
    199   bool IsPluginAcceptingCompositionEvents() const;
    200   void GetSurroundingText(base::string16* text, ui::Range* range) const;
    201 
    202   // Notifications about focus changes, see has_webkit_focus_ below.
    203   void SetWebKitFocus(bool has_focus);
    204   void SetContentAreaFocus(bool has_focus);
    205 
    206   // Notification about page visibility. The default is "visible".
    207   void PageVisibilityChanged(bool is_visible);
    208 
    209   // Notifications that the view is about to paint, has started painting, and
    210   // has flushed the painted content to the screen. These messages are used to
    211   // send Flush callbacks to the plugin for DeviceContext2D/3D.
    212   void ViewWillInitiatePaint();
    213   void ViewInitiatedPaint();
    214   void ViewFlushedPaint();
    215 
    216   // If this plugin can be painted merely by copying the backing store to the
    217   // screen, and the plugin bounds encloses the given paint bounds, returns
    218   // true. In this case, the location, clipping, and ID of the backing store
    219   // will be filled into the given output parameters.
    220   bool GetBitmapForOptimizedPluginPaint(
    221       const gfx::Rect& paint_bounds,
    222       TransportDIB** dib,
    223       gfx::Rect* dib_bounds,
    224       gfx::Rect* clip,
    225       float* scale_factor);
    226 
    227   // Tracks all live PluginObjects.
    228   void AddPluginObject(PluginObject* plugin_object);
    229   void RemovePluginObject(PluginObject* plugin_object);
    230 
    231   base::string16 GetSelectedText(bool html);
    232   base::string16 GetLinkAtPosition(const gfx::Point& point);
    233   void RequestSurroundingText(size_t desired_number_of_characters);
    234   void Zoom(double factor, bool text_only);
    235   bool StartFind(const base::string16& search_text,
    236                  bool case_sensitive,
    237                  int identifier);
    238   void SelectFindResult(bool forward);
    239   void StopFind();
    240 
    241   bool SupportsPrintInterface();
    242   bool IsPrintScalingDisabled();
    243   int PrintBegin(const WebKit::WebPrintParams& print_params);
    244   bool PrintPage(int page_number, WebKit::WebCanvas* canvas);
    245   void PrintEnd();
    246 
    247   bool CanRotateView();
    248   void RotateView(WebKit::WebPlugin::RotationType type);
    249 
    250   // There are 2 implementations of the fullscreen interface
    251   // PPB_FlashFullscreen is used by Pepper Flash.
    252   // PPB_Fullscreen is intended for other applications including NaCl.
    253   // The two interface are mutually exclusive.
    254 
    255   // Implementation of PPB_FlashFullscreen.
    256 
    257   // Because going to fullscreen is asynchronous (but going out is not), there
    258   // are 3 states:
    259   // - normal            : fullscreen_container_ == NULL
    260   //                       flash_fullscreen_ == false
    261   // - fullscreen pending: fullscreen_container_ != NULL
    262   //                       flash_fullscreen_ == false
    263   // - fullscreen        : fullscreen_container_ != NULL
    264   //                       flash_fullscreen_ == true
    265   //
    266   // In normal state, events come from webkit and painting goes back to it.
    267   // In fullscreen state, events come from the fullscreen container, and
    268   // painting goes back to it.
    269   // In pending state, events from webkit are ignored, and as soon as we
    270   // receive events from the fullscreen container, we go to the fullscreen
    271   // state.
    272   bool FlashIsFullscreenOrPending();
    273 
    274   // Updates |flash_fullscreen_| and sends focus change notification if
    275   // necessary.
    276   void UpdateFlashFullscreenState(bool flash_fullscreen);
    277 
    278   FullscreenContainer* fullscreen_container() const {
    279     return fullscreen_container_;
    280   }
    281 
    282   // Implementation of PPB_Fullscreen.
    283 
    284   // Because going to/from fullscreen is asynchronous, there are 4 states:
    285   // - normal            : desired_fullscreen_state_ == false
    286   //                       view_data_.is_fullscreen == false
    287   // - fullscreen pending: desired_fullscreen_state_ == true
    288   //                       view_data_.is_fullscreen == false
    289   // - fullscreen        : desired_fullscreen_state_ == true
    290   //                       view_data_.is_fullscreen == true
    291   // - normal pending    : desired_fullscreen_state_ = false
    292   //                       view_data_.is_fullscreen = true
    293   bool IsFullscreenOrPending();
    294 
    295   bool flash_fullscreen() const { return flash_fullscreen_; }
    296 
    297   // Switches between fullscreen and normal mode. The transition is
    298   // asynchronous. WebKit will trigger corresponding VewChanged calls.
    299   // Returns true on success, false on failure (e.g. trying to enter fullscreen
    300   // when not processing a user gesture or trying to set fullscreen when
    301   // already in fullscreen mode).
    302   bool SetFullscreen(bool fullscreen);
    303 
    304   // Implementation of PPP_Messaging.
    305   void HandleMessage(PP_Var message);
    306 
    307   // Returns true if the plugin is processing a user gesture.
    308   bool IsProcessingUserGesture();
    309 
    310   // Returns the user gesture token to use for creating a WebScopedUserGesture,
    311   // if IsProcessingUserGesture returned true.
    312   WebKit::WebUserGestureToken CurrentUserGestureToken();
    313 
    314   // A mouse lock request was pending and this reports success or failure.
    315   void OnLockMouseACK(bool succeeded);
    316   // A mouse lock was in place, but has been lost.
    317   void OnMouseLockLost();
    318   // A mouse lock is enabled and mouse events are being delivered.
    319   void HandleMouseLockedInputEvent(const WebKit::WebMouseEvent& event);
    320 
    321   // Simulates an input event to the plugin by passing it down to WebKit,
    322   // which sends it back up to the plugin as if it came from the user.
    323   void SimulateInputEvent(const ppapi::InputEventData& input_event);
    324 
    325   // Simulates an IME event at the level of RenderView which sends it back up to
    326   // the plugin as if it came from the user.
    327   bool SimulateIMEEvent(const ppapi::InputEventData& input_event);
    328   void SimulateImeSetCompositionEvent(
    329       const ppapi::InputEventData& input_event);
    330 
    331   // The document loader is valid when the plugin is "full-frame" and in this
    332   // case is non-NULL as long as the corresponding loader resource is alive.
    333   // This pointer is non-owning, so the loader must use set_document_loader to
    334   // clear itself when it is destroyed.
    335   WebKit::WebURLLoaderClient* document_loader() const {
    336     return document_loader_;
    337   }
    338   void set_document_loader(WebKit::WebURLLoaderClient* loader) {
    339     document_loader_ = loader;
    340   }
    341 
    342   ContentDecryptorDelegate* GetContentDecryptorDelegate();
    343 
    344   // PluginInstance implementation
    345   virtual RenderView* GetRenderView() OVERRIDE;
    346   virtual WebKit::WebPluginContainer* GetContainer() OVERRIDE;
    347   virtual ppapi::VarTracker* GetVarTracker() OVERRIDE;
    348   virtual const GURL& GetPluginURL() OVERRIDE;
    349   virtual base::FilePath GetModulePath() OVERRIDE;
    350   virtual PP_Resource CreateExternalFileReference(
    351       const base::FilePath& external_file_path) OVERRIDE;
    352   virtual PP_Resource CreateImage(gfx::ImageSkia* source_image,
    353                                   float scale) OVERRIDE;
    354   virtual PP_ExternalPluginResult SwitchToOutOfProcessProxy(
    355       const base::FilePath& file_path,
    356       ppapi::PpapiPermissions permissions,
    357       const IPC::ChannelHandle& channel_handle,
    358       base::ProcessId plugin_pid,
    359       int plugin_child_id) OVERRIDE;
    360   virtual void SetAlwaysOnTop(bool on_top) OVERRIDE;
    361   virtual bool IsFullPagePlugin() OVERRIDE;
    362   virtual void FlashSetFullscreen(bool fullscreen, bool delay_report) OVERRIDE;
    363   virtual bool IsRectTopmost(const gfx::Rect& rect) OVERRIDE;
    364   virtual int32_t Navigate(const ppapi::URLRequestInfoData& request,
    365                            const char* target,
    366                            bool from_user_action) OVERRIDE;
    367 
    368   // PPB_Instance_API implementation.
    369   virtual PP_Bool BindGraphics(PP_Instance instance,
    370                                PP_Resource device) OVERRIDE;
    371   virtual PP_Bool IsFullFrame(PP_Instance instance) OVERRIDE;
    372   virtual const ppapi::ViewData* GetViewData(PP_Instance instance) OVERRIDE;
    373   virtual PP_Bool FlashIsFullscreen(PP_Instance instance) OVERRIDE;
    374   virtual PP_Var GetWindowObject(PP_Instance instance) OVERRIDE;
    375   virtual PP_Var GetOwnerElementObject(PP_Instance instance) OVERRIDE;
    376   virtual PP_Var ExecuteScript(PP_Instance instance,
    377                                PP_Var script,
    378                                PP_Var* exception) OVERRIDE;
    379   virtual uint32_t GetAudioHardwareOutputSampleRate(PP_Instance instance)
    380       OVERRIDE;
    381   virtual uint32_t GetAudioHardwareOutputBufferSize(PP_Instance instance)
    382       OVERRIDE;
    383   virtual PP_Var GetDefaultCharSet(PP_Instance instance) OVERRIDE;
    384   virtual void NumberOfFindResultsChanged(PP_Instance instance,
    385                                           int32_t total,
    386                                           PP_Bool final_result) OVERRIDE;
    387   virtual void SelectedFindResultChanged(PP_Instance instance,
    388                                          int32_t index) OVERRIDE;
    389   virtual PP_Bool IsFullscreen(PP_Instance instance) OVERRIDE;
    390   virtual PP_Bool SetFullscreen(PP_Instance instance,
    391                                 PP_Bool fullscreen) OVERRIDE;
    392   virtual PP_Bool GetScreenSize(PP_Instance instance, PP_Size* size)
    393       OVERRIDE;
    394   virtual ppapi::Resource* GetSingletonResource(PP_Instance instance,
    395       ppapi::SingletonResourceID id) OVERRIDE;
    396   virtual int32_t RequestInputEvents(PP_Instance instance,
    397                                      uint32_t event_classes) OVERRIDE;
    398   virtual int32_t RequestFilteringInputEvents(PP_Instance instance,
    399                                               uint32_t event_classes) OVERRIDE;
    400   virtual void ClearInputEventRequest(PP_Instance instance,
    401                                       uint32_t event_classes) OVERRIDE;
    402   virtual void ZoomChanged(PP_Instance instance, double factor) OVERRIDE;
    403   virtual void ZoomLimitsChanged(PP_Instance instance,
    404                                  double minimum_factor,
    405                                  double maximum_factor) OVERRIDE;
    406   virtual void PostMessage(PP_Instance instance, PP_Var message) OVERRIDE;
    407   virtual PP_Bool SetCursor(PP_Instance instance,
    408                             PP_MouseCursor_Type type,
    409                             PP_Resource image,
    410                             const PP_Point* hot_spot) OVERRIDE;
    411   virtual int32_t LockMouse(
    412       PP_Instance instance,
    413       scoped_refptr<ppapi::TrackedCallback> callback) OVERRIDE;
    414   virtual void UnlockMouse(PP_Instance instance) OVERRIDE;
    415   virtual void SetTextInputType(PP_Instance instance,
    416                                 PP_TextInput_Type type) OVERRIDE;
    417   virtual void UpdateCaretPosition(PP_Instance instance,
    418                                    const PP_Rect& caret,
    419                                    const PP_Rect& bounding_box) OVERRIDE;
    420   virtual void CancelCompositionText(PP_Instance instance) OVERRIDE;
    421   virtual void SelectionChanged(PP_Instance instance) OVERRIDE;
    422   virtual void UpdateSurroundingText(PP_Instance instance,
    423                                      const char* text,
    424                                      uint32_t caret,
    425                                      uint32_t anchor) OVERRIDE;
    426   virtual PP_Var ResolveRelativeToDocument(
    427       PP_Instance instance,
    428       PP_Var relative,
    429       PP_URLComponents_Dev* components) OVERRIDE;
    430   virtual PP_Bool DocumentCanRequest(PP_Instance instance, PP_Var url) OVERRIDE;
    431   virtual PP_Bool DocumentCanAccessDocument(PP_Instance instance,
    432                                             PP_Instance target) OVERRIDE;
    433   virtual PP_Var GetDocumentURL(PP_Instance instance,
    434                                 PP_URLComponents_Dev* components) OVERRIDE;
    435   virtual PP_Var GetPluginInstanceURL(
    436       PP_Instance instance,
    437       PP_URLComponents_Dev* components) OVERRIDE;
    438 
    439   // PPB_ContentDecryptor_Private implementation.
    440   virtual void NeedKey(PP_Instance instance,
    441                        PP_Var key_system,
    442                        PP_Var session_id,
    443                        PP_Var init_data) OVERRIDE;
    444   virtual void KeyAdded(PP_Instance instance,
    445                         PP_Var key_system,
    446                         PP_Var session_id) OVERRIDE;
    447   virtual void KeyMessage(PP_Instance instance,
    448                           PP_Var key_system,
    449                           PP_Var session_id,
    450                           PP_Var message,
    451                           PP_Var default_url) OVERRIDE;
    452   virtual void KeyError(PP_Instance instance,
    453                         PP_Var key_system,
    454                         PP_Var session_id,
    455                         int32_t media_error,
    456                         int32_t system_code) OVERRIDE;
    457   virtual void DeliverBlock(PP_Instance instance,
    458                             PP_Resource decrypted_block,
    459                             const PP_DecryptedBlockInfo* block_info) OVERRIDE;
    460   virtual void DecoderInitializeDone(PP_Instance instance,
    461                                      PP_DecryptorStreamType decoder_type,
    462                                      uint32_t request_id,
    463                                      PP_Bool success) OVERRIDE;
    464   virtual void DecoderDeinitializeDone(PP_Instance instance,
    465                                        PP_DecryptorStreamType decoder_type,
    466                                        uint32_t request_id) OVERRIDE;
    467   virtual void DecoderResetDone(PP_Instance instance,
    468                                 PP_DecryptorStreamType decoder_type,
    469                                 uint32_t request_id) OVERRIDE;
    470   virtual void DeliverFrame(PP_Instance instance,
    471                             PP_Resource decrypted_frame,
    472                             const PP_DecryptedFrameInfo* frame_info) OVERRIDE;
    473   virtual void DeliverSamples(PP_Instance instance,
    474                               PP_Resource audio_frames,
    475                               const PP_DecryptedBlockInfo* block_info) OVERRIDE;
    476 
    477   // Reset this instance as proxied. Assigns the instance a new module, resets
    478   // cached interfaces to point to the out-of-process proxy and re-sends
    479   // DidCreate, DidChangeView, and HandleDocumentLoad (if necessary).
    480   // This should be used only when switching an in-process instance to an
    481   // external out-of-process instance.
    482   PP_ExternalPluginResult ResetAsProxied(scoped_refptr<PluginModule> module);
    483 
    484   // Checks whether this is a valid instance of the given module. After calling
    485   // ResetAsProxied above, a NaCl plugin instance's module changes, so external
    486   // hosts won't recognize it as a valid instance of the original module. This
    487   // method fixes that be checking that either module_ or original_module_ match
    488   // the given module.
    489   bool IsValidInstanceOf(PluginModule* module);
    490 
    491   // Returns the plugin NPP identifier that this plugin will use to identify
    492   // itself when making NPObject scripting calls to WebBindings.
    493   struct _NPP* instanceNPP();
    494 
    495   // Returns the v8::Isolate that was current when this Instance was created.
    496   // This is not inlined so as to avoid an unnecessary header include of v8.h.
    497   v8::Isolate* GetIsolate() const;
    498 
    499  private:
    500   friend class base::RefCounted<PepperPluginInstanceImpl>;
    501   friend class PpapiUnittest;
    502 
    503   // Delete should be called by the WebPlugin before this destructor.
    504   virtual ~PepperPluginInstanceImpl();
    505 
    506   // Class to record document load notifications and play them back once the
    507   // real document loader becomes available. Used only by external instances.
    508   class ExternalDocumentLoader : public WebKit::WebURLLoaderClient {
    509    public:
    510     ExternalDocumentLoader();
    511     virtual ~ExternalDocumentLoader();
    512 
    513     void ReplayReceivedData(WebURLLoaderClient* document_loader);
    514 
    515     // WebKit::WebURLLoaderClient implementation.
    516     virtual void didReceiveData(WebKit::WebURLLoader* loader,
    517                                 const char* data,
    518                                 int data_length,
    519                                 int encoded_data_length);
    520     virtual void didFinishLoading(WebKit::WebURLLoader* loader,
    521                                   double finish_time);
    522     virtual void didFail(WebKit::WebURLLoader* loader,
    523                          const WebKit::WebURLError& error);
    524 
    525    private:
    526     std::list<std::string> data_;
    527     bool finished_loading_;
    528     scoped_ptr<WebKit::WebURLError> error_;
    529   };
    530 
    531   // Implements PPB_Gamepad_API. This is just to avoid having an excessive
    532   // number of interfaces implemented by PepperPluginInstanceImpl.
    533   class GamepadImpl : public ppapi::thunk::PPB_Gamepad_API,
    534                       public ppapi::Resource {
    535    public:
    536     GamepadImpl();
    537     // Resource implementation.
    538     virtual ppapi::thunk::PPB_Gamepad_API* AsPPB_Gamepad_API() OVERRIDE;
    539     virtual void Sample(PP_Instance instance,
    540                         PP_GamepadsSampleData* data) OVERRIDE;
    541    private:
    542     virtual ~GamepadImpl();
    543   };
    544 
    545   // See the static Create functions above for creating PepperPluginInstanceImpl
    546   // objects. This constructor is private so that we can hide the
    547   // PPP_Instance_Combined details while still having 1 constructor to maintain
    548   // for member initialization.
    549   PepperPluginInstanceImpl(RenderViewImpl* render_view,
    550                            PluginModule* module,
    551                            ppapi::PPP_Instance_Combined* instance_interface,
    552                            WebKit::WebPluginContainer* container,
    553                            const GURL& plugin_url);
    554 
    555   bool LoadFindInterface();
    556   bool LoadInputEventInterface();
    557   bool LoadMessagingInterface();
    558   bool LoadMouseLockInterface();
    559   bool LoadPdfInterface();
    560   bool LoadPrintInterface();
    561   bool LoadPrivateInterface();
    562   bool LoadSelectionInterface();
    563   bool LoadTextInputInterface();
    564   bool LoadZoomInterface();
    565 
    566   // Determines if we think the plugin has focus, both content area and webkit
    567   // (see has_webkit_focus_ below).
    568   bool PluginHasFocus() const;
    569   void SendFocusChangeNotification();
    570 
    571   void UpdateTouchEventRequest();
    572 
    573   // Returns true if the plugin has registered to accept wheel events.
    574   bool IsAcceptingWheelEvents() const;
    575 
    576   void ScheduleAsyncDidChangeView();
    577   void SendAsyncDidChangeView();
    578   void SendDidChangeView();
    579 
    580   // Reports the current plugin geometry to the plugin by calling
    581   // DidChangeView.
    582   void ReportGeometry();
    583 
    584   // Queries the plugin for supported print formats and sets |format| to the
    585   // best format to use. Returns false if the plugin does not support any
    586   // print format that we can handle (we can handle only PDF).
    587   bool GetPreferredPrintOutputFormat(PP_PrintOutputFormat_Dev* format);
    588   bool PrintPDFOutput(PP_Resource print_output, WebKit::WebCanvas* canvas);
    589 
    590   // Updates the layer for compositing. This creates a layer and attaches to the
    591   // container if:
    592   // - we have a bound Graphics3D
    593   // - the Graphics3D has a texture
    594   // - we are not in Flash full-screen mode (or transitioning to it)
    595   // Otherwise it destroys the layer.
    596   // It does either operation lazily.
    597   void UpdateLayer();
    598 
    599   // Internal helper function for PrintPage().
    600   bool PrintPageHelper(PP_PrintPageNumberRange_Dev* page_ranges,
    601                        int num_ranges,
    602                        WebKit::WebCanvas* canvas);
    603 
    604   void DoSetCursor(WebKit::WebCursorInfo* cursor);
    605 
    606   // Internal helper functions for HandleCompositionXXX().
    607   bool SendCompositionEventToPlugin(
    608       PP_InputEvent_Type type,
    609       const base::string16& text);
    610   bool SendCompositionEventWithUnderlineInformationToPlugin(
    611       PP_InputEvent_Type type,
    612       const base::string16& text,
    613       const std::vector<WebKit::WebCompositionUnderline>& underlines,
    614       int selection_start,
    615       int selection_end);
    616 
    617   // Internal helper function for XXXInputEvents().
    618   void RequestInputEventsHelper(uint32_t event_classes);
    619 
    620   // Checks if the security origin of the document containing this instance can
    621   // assess the security origin of the main frame document.
    622   bool CanAccessMainFrame() const;
    623 
    624   // Returns true if the WebView the plugin is in renders via the accelerated
    625   // compositing path.
    626   bool IsViewAccelerated();
    627 
    628   // Track, set and reset size attributes to control the size of the plugin
    629   // in and out of fullscreen mode.
    630   void KeepSizeAttributesBeforeFullscreen();
    631   void SetSizeAttributesForFullscreen();
    632   void ResetSizeAttributesAfterFullscreen();
    633 
    634   bool IsMouseLocked();
    635   bool LockMouse();
    636   MouseLockDispatcher* GetMouseLockDispatcher();
    637   MouseLockDispatcher::LockTarget* GetOrCreateLockTargetAdapter();
    638   void UnSetAndDeleteLockTargetAdapter();
    639 
    640   void DidDataFromWebURLResponse(
    641       const WebKit::WebURLResponse& response,
    642       int pending_host_id,
    643       const ppapi::URLResponseInfoData& data);
    644 
    645   RenderViewImpl* render_view_;
    646   scoped_refptr<PluginModule> module_;
    647   scoped_ptr<ppapi::PPP_Instance_Combined> instance_interface_;
    648   // If this is the NaCl plugin, we create a new module when we switch to the
    649   // IPC-based PPAPI proxy. Store the original module and instance interface
    650   // so we can shut down properly.
    651   scoped_refptr<PluginModule> original_module_;
    652   scoped_ptr<ppapi::PPP_Instance_Combined> original_instance_interface_;
    653 
    654   PP_Instance pp_instance_;
    655 
    656   // NULL until we have been initialized.
    657   WebKit::WebPluginContainer* container_;
    658   scoped_refptr<cc::TextureLayer> texture_layer_;
    659   scoped_ptr<WebKit::WebLayer> web_layer_;
    660   bool layer_bound_to_fullscreen_;
    661 
    662   // Plugin URL.
    663   GURL plugin_url_;
    664 
    665   // Indicates whether this is a full frame instance, which means it represents
    666   // an entire document rather than an embed tag.
    667   bool full_frame_;
    668 
    669   // Stores the current state of the plugin view.
    670   ppapi::ViewData view_data_;
    671   // The last state sent to the plugin. It is only valid after
    672   // |sent_initial_did_change_view_| is set to true.
    673   ppapi::ViewData last_sent_view_data_;
    674 
    675   // Indicates if we've ever sent a didChangeView to the plugin. This ensures we
    676   // always send an initial notification, even if the position and clip are the
    677   // same as the default values.
    678   bool sent_initial_did_change_view_;
    679 
    680   // We use a weak ptr factory for scheduling DidChangeView events so that we
    681   // can tell whether updates are pending and consolidate them. When there's
    682   // already a weak ptr pending (HasWeakPtrs is true), code should update the
    683   // view_data_ but not send updates. This also allows us to cancel scheduled
    684   // view change events.
    685   base::WeakPtrFactory<PepperPluginInstanceImpl> view_change_weak_ptr_factory_;
    686 
    687   // The current device context for painting in 2D and 3D.
    688   scoped_refptr<PPB_Graphics3D_Impl> bound_graphics_3d_;
    689   PepperGraphics2DHost* bound_graphics_2d_platform_;
    690 
    691   // We track two types of focus, one from WebKit, which is the focus among
    692   // all elements of the page, one one from the browser, which is whether the
    693   // tab/window has focus. We tell the plugin it has focus only when both of
    694   // these values are set to true.
    695   bool has_webkit_focus_;
    696   bool has_content_area_focus_;
    697 
    698   // The id of the current find operation, or -1 if none is in process.
    699   int find_identifier_;
    700 
    701   // Helper object that creates resources.
    702   scoped_ptr<ppapi::thunk::ResourceCreationAPI> resource_creation_;
    703 
    704   // The plugin-provided interfaces.
    705   // When adding PPP interfaces, make sure to reset them in ResetAsProxied.
    706   const PPP_Find_Dev* plugin_find_interface_;
    707   const PPP_InputEvent* plugin_input_event_interface_;
    708   const PPP_Messaging* plugin_messaging_interface_;
    709   const PPP_MouseLock* plugin_mouse_lock_interface_;
    710   const PPP_Pdf* plugin_pdf_interface_;
    711   const PPP_Instance_Private* plugin_private_interface_;
    712   const PPP_Selection_Dev* plugin_selection_interface_;
    713   const PPP_TextInput_Dev* plugin_textinput_interface_;
    714   const PPP_Zoom_Dev* plugin_zoom_interface_;
    715 
    716   // Flags indicating whether we have asked this plugin instance for the
    717   // corresponding interfaces, so that we can ask only once.
    718   // When adding flags, make sure to reset them in ResetAsProxied.
    719   bool checked_for_plugin_input_event_interface_;
    720   bool checked_for_plugin_messaging_interface_;
    721   bool checked_for_plugin_pdf_interface_;
    722 
    723   // This is only valid between a successful PrintBegin call and a PrintEnd
    724   // call.
    725   PP_PrintSettings_Dev current_print_settings_;
    726 #if defined(OS_MACOSX)
    727   // On the Mac, when we draw the bitmap to the PDFContext, it seems necessary
    728   // to keep the pixels valid until CGContextEndPage is called. We use this
    729   // variable to hold on to the pixels.
    730   scoped_refptr<PPB_ImageData_Impl> last_printed_page_;
    731 #endif  // defined(OS_MACOSX)
    732   // Always when printing to PDF on Linux and when printing for preview on Mac
    733   // and Win, the entire document goes into one metafile.  However, when users
    734   // print only a subset of all the pages, it is impossible to know if a call
    735   // to PrintPage() is the last call. Thus in PrintPage(), just store the page
    736   // number in |ranges_|. The hack is in PrintEnd(), where a valid |canvas_|
    737   // is preserved in PrintWebViewHelper::PrintPages. This makes it possible
    738   // to generate the entire PDF given the variables below:
    739   //
    740   // The most recently used WebCanvas, guaranteed to be valid.
    741   skia::RefPtr<WebKit::WebCanvas> canvas_;
    742   // An array of page ranges.
    743   std::vector<PP_PrintPageNumberRange_Dev> ranges_;
    744 
    745   scoped_refptr<ppapi::Resource> gamepad_impl_;
    746 
    747   // The plugin print interface.
    748   const PPP_Printing_Dev* plugin_print_interface_;
    749 
    750   // The plugin 3D interface.
    751   const PPP_Graphics3D* plugin_graphics_3d_interface_;
    752 
    753   // Contains the cursor if it's set by the plugin.
    754   scoped_ptr<WebKit::WebCursorInfo> cursor_;
    755 
    756   // Set to true if this plugin thinks it will always be on top. This allows us
    757   // to use a more optimized painting path in some cases.
    758   bool always_on_top_;
    759   // Even if |always_on_top_| is true, the plugin is not fully visible if there
    760   // are some cut-out areas (occupied by iframes higher in the stacking order).
    761   // This information is used in the optimized painting path.
    762   std::vector<gfx::Rect> cut_outs_rects_;
    763 
    764   // Implementation of PPB_FlashFullscreen.
    765 
    766   // Plugin container for fullscreen mode. NULL if not in fullscreen mode. Note:
    767   // there is a transition state where fullscreen_container_ is non-NULL but
    768   // flash_fullscreen_ is false (see above).
    769   FullscreenContainer* fullscreen_container_;
    770 
    771   // True if we are in "flash" fullscreen mode. False if we are in normal mode
    772   // or in transition to fullscreen. Normal fullscreen mode is indicated in
    773   // the ViewData.
    774   bool flash_fullscreen_;
    775 
    776   // Implementation of PPB_Fullscreen.
    777 
    778   // Since entering fullscreen mode is an asynchronous operation, we set this
    779   // variable to the desired state at the time we issue the fullscreen change
    780   // request. The plugin will receive a DidChangeView event when it goes
    781   // fullscreen.
    782   bool desired_fullscreen_state_;
    783 
    784   // WebKit does not resize the plugin when going into fullscreen mode, so we do
    785   // this here by modifying the various plugin attributes and then restoring
    786   // them on exit.
    787   WebKit::WebString width_before_fullscreen_;
    788   WebKit::WebString height_before_fullscreen_;
    789   WebKit::WebString border_before_fullscreen_;
    790   WebKit::WebString style_before_fullscreen_;
    791   gfx::Size screen_size_for_fullscreen_;
    792 
    793   // The MessageChannel used to implement bidirectional postMessage for the
    794   // instance.
    795   scoped_ptr<MessageChannel> message_channel_;
    796 
    797   // Bitmap for crashed plugin. Lazily initialized, non-owning pointer.
    798   SkBitmap* sad_plugin_;
    799 
    800   typedef std::set<PluginObject*> PluginObjectSet;
    801   PluginObjectSet live_plugin_objects_;
    802 
    803   // Classes of events that the plugin has registered for, both for filtering
    804   // and not. The bits are PP_INPUTEVENT_CLASS_*.
    805   uint32_t input_event_mask_;
    806   uint32_t filtered_input_event_mask_;
    807 
    808   // Text composition status.
    809   ui::TextInputType text_input_type_;
    810   gfx::Rect text_input_caret_;
    811   gfx::Rect text_input_caret_bounds_;
    812   bool text_input_caret_set_;
    813 
    814   // Text selection status.
    815   std::string surrounding_text_;
    816   size_t selection_caret_;
    817   size_t selection_anchor_;
    818 
    819   scoped_refptr<ppapi::TrackedCallback> lock_mouse_callback_;
    820 
    821   // Track pending user gestures so out-of-process plugins can respond to
    822   // a user gesture after it has been processed.
    823   PP_TimeTicks pending_user_gesture_;
    824   WebKit::WebUserGestureToken pending_user_gesture_token_;
    825 
    826   // We store the arguments so we can re-send them if we are reset to talk to
    827   // NaCl via the IPC NaCl proxy.
    828   std::vector<std::string> argn_;
    829   std::vector<std::string> argv_;
    830 
    831   // Non-owning pointer to the document loader, if any.
    832   WebKit::WebURLLoaderClient* document_loader_;
    833   // State for deferring document loads. Used only by external instances.
    834   WebKit::WebURLResponse external_document_response_;
    835   scoped_ptr<ExternalDocumentLoader> external_document_loader_;
    836   bool external_document_load_;
    837 
    838   // The ContentDecryptorDelegate forwards PPP_ContentDecryptor_Private
    839   // calls and handles PPB_ContentDecryptor_Private calls.
    840   scoped_ptr<ContentDecryptorDelegate> content_decryptor_delegate_;
    841 
    842   // Dummy NPP value used when calling in to WebBindings, to allow the bindings
    843   // to correctly track NPObjects belonging to this plugin instance.
    844   scoped_ptr<struct _NPP> npp_;
    845 
    846   // We store the isolate at construction so that we can be sure to use the
    847   // Isolate in which this Instance was created when interacting with v8.
    848   v8::Isolate* isolate_;
    849 
    850   scoped_ptr<MouseLockDispatcher::LockTarget> lock_target_;
    851 
    852   friend class PpapiPluginInstanceTest;
    853   DISALLOW_COPY_AND_ASSIGN(PepperPluginInstanceImpl);
    854 };
    855 
    856 }  // namespace content
    857 
    858 #endif  // CONTENT_RENDERER_PEPPER_PEPPER_PLUGIN_INSTANCE_IMPL_H_
    859