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