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