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