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