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