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