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