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