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