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 PPAPI_CPP_INSTANCE_H_ 6 #define PPAPI_CPP_INSTANCE_H_ 7 8 /// @file 9 /// This file defines the C++ wrapper for an instance. 10 11 #include <map> 12 #include <string> 13 14 #include "ppapi/c/pp_instance.h" 15 #include "ppapi/c/pp_resource.h" 16 #include "ppapi/c/pp_stdint.h" 17 #include "ppapi/c/ppb_console.h" 18 #include "ppapi/cpp/instance_handle.h" 19 #include "ppapi/cpp/view.h" 20 21 // Windows defines 'PostMessage', so we have to undef it. 22 #ifdef PostMessage 23 #undef PostMessage 24 #endif 25 26 struct PP_InputEvent; 27 28 /// The C++ interface to the Pepper API. 29 namespace pp { 30 31 class Graphics2D; 32 class Graphics3D; 33 class InputEvent; 34 class InstanceHandle; 35 class Rect; 36 class URLLoader; 37 class Var; 38 39 class Instance { 40 public: 41 /// Default constructor. Construction of an instance should only be done in 42 /// response to a browser request in <code>Module::CreateInstance</code>. 43 /// Otherwise, the instance will lack the proper bookkeeping in the browser 44 /// and in the C++ wrapper. 45 /// 46 /// Init() will be called immediately after the constructor. This allows you 47 /// to perform initialization tasks that can fail and to report that failure 48 /// to the browser. 49 explicit Instance(PP_Instance instance); 50 51 /// Destructor. When the instance is removed from the web page, 52 /// the <code>pp::Instance</code> object will be deleted. You should never 53 /// delete the <code>Instance</code> object yourself since the lifetime is 54 /// handled by the C++ wrapper and is controlled by the browser's calls to 55 /// the <code>PPP_Instance</code> interface. 56 /// 57 /// The <code>PP_Instance</code> identifier will still be valid during this 58 /// call so the instance can perform cleanup-related tasks. Once this function 59 /// returns, the <code>PP_Instance</code> handle will be invalid. This means 60 /// that you can't do any asynchronous operations such as network requests or 61 /// file writes from this destructor since they will be immediately canceled. 62 /// 63 /// <strong>Note:</strong> This function may be skipped in certain 64 /// call so the instance can perform cleanup-related tasks. Once this function 65 /// returns, the <code>PP_Instance</code> handle will be invalid. This means 66 /// that you can't do any asynchronous operations such as network requests or 67 /// file writes from this destructor since they will be immediately canceled. 68 virtual ~Instance(); 69 70 /// This function returns the <code>PP_Instance</code> identifying this 71 /// object. 72 /// 73 /// @return A <code>PP_Instance</code> identifying this object. pp_instance()74 PP_Instance pp_instance() const { return pp_instance_; } 75 76 /// Init() initializes this instance with the provided arguments. This 77 /// function will be called immediately after the instance object is 78 /// constructed. 79 /// 80 /// @param[in] argc The number of arguments contained in <code>argn</code> 81 /// and <code>argv</code>. 82 /// 83 /// @param[in] argn An array of argument names. These argument names are 84 /// supplied in the \<embed\> tag, for example: 85 /// <code>\<embed id="nacl_module" dimensions="2"\></code> will produce two 86 /// argument names: "id" and "dimensions". 87 /// 88 /// @param[in] argv An array of argument values. These are the values of the 89 /// arguments listed in the \<embed\> tag, for example 90 /// <code>\<embed id="nacl_module" dimensions="2"\></code> will produce two 91 /// argument values: "nacl_module" and "2". The indices of these values 92 /// match the indices of the corresponding names in <code>argn</code>. 93 /// 94 /// @return true on success. Returning false causes the instance to be 95 /// deleted and no other functions to be called. 96 virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]); 97 98 /// @{ 99 /// @name PPP_Instance methods for the module to override: 100 101 /// DidChangeView() is called when the view information for the Instance 102 /// has changed. See the <code>View</code> object for information. 103 /// 104 /// Most implementations will want to check if the size and user visibility 105 /// changed, and either resize themselves or start/stop generating updates. 106 /// 107 /// You should not call the default implementation. For 108 /// backwards-compatibility, it will call the deprecated version of 109 /// DidChangeView below. 110 virtual void DidChangeView(const View& view); 111 112 /// Deprecated backwards-compatible version of <code>DidChangeView()</code>. 113 /// New code should derive from the version that takes a 114 /// <code>ViewChanged</code> object rather than this version. This function 115 /// is called by the default implementation of the newer 116 /// <code>DidChangeView</code> function for source compatibility with older 117 /// code. 118 /// 119 /// A typical implementation will check the size of the <code>position</code> 120 /// argument and reallocate the graphics context when a different size is 121 /// received. Note that this function will be called for scroll events where 122 /// the size doesn't change, so you should always check that the size is 123 /// actually different before doing any reallocations. 124 /// 125 /// @param[in] position The location on the page of the instance. The 126 /// position is relative to the top left corner of the viewport, which changes 127 /// as the page is scrolled. Generally the size of this value will be used to 128 /// create a graphics device, and the position is ignored (most things are 129 /// relative to the instance so the absolute position isn't useful in most 130 /// cases). 131 /// 132 /// @param[in] clip The visible region of the instance. This is relative to 133 /// the top left of the instance's coordinate system (not the page). If the 134 /// instance is invisible, <code>clip</code> will be (0, 0, 0, 0). 135 /// 136 /// It's recommended to check for invisible instances and to stop 137 /// generating graphics updates in this case to save system resources. It's 138 /// not usually worthwhile, however, to generate partial updates according to 139 /// the clip when the instance is partially visible. Instead, update the 140 /// entire region. The time saved doing partial paints is usually not 141 /// significant and it can create artifacts when scrolling (this notification 142 /// is sent asynchronously from scrolling so there can be flashes of old 143 /// content in the exposed regions). 144 virtual void DidChangeView(const Rect& position, const Rect& clip); 145 146 /// DidChangeFocus() is called when an instance has gained or lost focus. 147 /// Having focus means that keyboard events will be sent to the instance. 148 /// An instance's default condition is that it will not have focus. 149 /// 150 /// The focus flag takes into account both browser tab and window focus as 151 /// well as focus of the plugin element on the page. In order to be deemed 152 /// to have focus, the browser window must be topmost, the tab must be 153 /// selected in the window, and the instance must be the focused element on 154 /// the page. 155 /// 156 /// <strong>Note:</strong>Clicks on instances will give focus only if you 157 /// handle the click event. Return <code>true</code> from 158 /// <code>HandleInputEvent</code> in <code>PPP_InputEvent</code> (or use 159 /// unfiltered events) to signal that the click event was handled. Otherwise, 160 /// the browser will bubble the event and give focus to the element on the 161 /// page that actually did end up consuming it. If you're not getting focus, 162 /// check to make sure you're either requesting them via 163 /// <code>RequestInputEvents()<code> (which implicitly marks all input events 164 /// as consumed) or via <code>RequestFilteringInputEvents()</code> and 165 /// returning true from your event handler. 166 /// 167 /// @param[in] has_focus Indicates the new focused state of the instance. 168 virtual void DidChangeFocus(bool has_focus); 169 170 /// HandleInputEvent() handles input events from the browser. The default 171 /// implementation does nothing and returns false. 172 /// 173 /// In order to receive input events, you must register for them by calling 174 /// RequestInputEvents() or RequestFilteringInputEvents(). By 175 /// default, no events are delivered. 176 /// 177 /// If the event was handled, it will not be forwarded to the web page or 178 /// browser. If it was not handled, it will bubble according to the normal 179 /// rules. So it is important that an instance respond accurately with whether 180 /// event propagation should continue. 181 /// 182 /// Event propagation also controls focus. If you handle an event like a mouse 183 /// event, typically the instance will be given focus. Returning false from 184 /// a filtered event handler or not registering for an event type means that 185 /// the click will be given to a lower part of the page and your instance will 186 /// not receive focus. This allows an instance to be partially transparent, 187 /// where clicks on the transparent areas will behave like clicks to the 188 /// underlying page. 189 /// 190 /// In general, you should try to keep input event handling short. Especially 191 /// for filtered input events, the browser or page may be blocked waiting for 192 /// you to respond. 193 /// 194 /// The caller of this function will maintain a reference to the input event 195 /// resource during this call. Unless you take a reference to the resource 196 /// to hold it for later, you don't need to release it. 197 /// 198 /// <strong>Note: </strong>If you're not receiving input events, make sure 199 /// you register for the event classes you want by calling 200 /// <code>RequestInputEvents</code> or 201 /// <code>RequestFilteringInputEvents</code>. If you're still not receiving 202 /// keyboard input events, make sure you're returning true (or using a 203 /// non-filtered event handler) for mouse events. Otherwise, the instance will 204 /// not receive focus and keyboard events will not be sent. 205 /// 206 /// Refer to <code>RequestInputEvents</code> and 207 /// <code>RequestFilteringInputEvents</code> for further information. 208 /// 209 /// @param[in] event The event to handle. 210 /// 211 /// @return true if the event was handled, false if not. If you have 212 /// registered to filter this class of events by calling 213 /// <code>RequestFilteringInputEvents</code>, and you return false, 214 /// the event will be forwarded to the page (and eventually the browser) 215 /// for the default handling. For non-filtered events, the return value 216 /// will be ignored. 217 virtual bool HandleInputEvent(const pp::InputEvent& event); 218 219 /// HandleDocumentLoad() is called after Init() for a full-frame 220 /// instance that was instantiated based on the MIME type of a DOMWindow 221 /// navigation. This situation only applies to modules that are 222 /// pre-registered to handle certain MIME types. If you haven't specifically 223 /// registered to handle a MIME type or aren't positive this applies to you, 224 /// your implementation of this function can just return false. 225 /// 226 /// The given url_loader corresponds to a <code>URLLoader</code> object that 227 /// is already opened. Its response headers may be queried using 228 /// GetResponseInfo(). If you want to use the <code>URLLoader</code> to read 229 /// data, you will need to save a copy of it or the underlying resource will 230 /// be freed when this function returns and the load will be canceled. 231 /// 232 /// This method returns false if the module cannot handle the data. In 233 /// response to this method, the module should call ReadResponseBody() to read 234 /// the incoming data. 235 /// 236 /// @param[in] url_loader An open <code>URLLoader</code> instance. 237 /// 238 /// @return true if the data was handled, false otherwise. 239 virtual bool HandleDocumentLoad(const URLLoader& url_loader); 240 241 /// HandleMessage() is a function that the browser calls when PostMessage() 242 /// is invoked on the DOM element for the instance in JavaScript. Note 243 /// that PostMessage() in the JavaScript interface is asynchronous, meaning 244 /// JavaScript execution will not be blocked while HandleMessage() is 245 /// processing the message. 246 /// 247 /// When converting JavaScript arrays, any object properties whose name 248 /// is not an array index are ignored. When passing arrays and objects, the 249 /// entire reference graph will be converted and transferred. If the reference 250 /// graph has cycles, the message will not be sent and an error will be logged 251 /// to the console. 252 /// 253 /// <strong>Example:</strong> 254 /// 255 /// The following JavaScript code invokes <code>HandleMessage</code>, passing 256 /// the instance on which it was invoked, with <code>message</code> being a 257 /// string <code>Var</code> containing "Hello world!" 258 /// 259 /// @code{.html} 260 /// 261 /// <body> 262 /// <object id="plugin" 263 /// type="application/x-ppapi-postMessage-example"/> 264 /// <script type="text/javascript"> 265 /// document.getElementById('plugin').postMessage("Hello world!"); 266 /// </script> 267 /// </body> 268 /// 269 /// @endcode 270 /// 271 /// Refer to PostMessage() for sending messages to JavaScript. 272 /// 273 /// @param[in] message A <code>Var</code> which has been converted from a 274 /// JavaScript value. JavaScript array/object types are supported from Chrome 275 /// M29 onward. All JavaScript values are copied when passing them to the 276 /// plugin. 277 virtual void HandleMessage(const Var& message); 278 279 /// @} 280 281 /// @{ 282 /// @name PPB_Instance methods for querying the browser: 283 284 /// BindGraphics() binds the given graphics as the current display surface. 285 /// The contents of this device is what will be displayed in the instance's 286 /// area on the web page. The device must be a 2D or a 3D device. 287 /// 288 /// You can pass an <code>is_null()</code> (default constructed) Graphics2D 289 /// as the device parameter to unbind all devices from the given instance. 290 /// The instance will then appear transparent. Re-binding the same device 291 /// will return <code>true</code> and will do nothing. 292 /// 293 /// Any previously-bound device will be released. It is an error to bind 294 /// a device when it is already bound to another instance. If you want 295 /// to move a device between instances, first unbind it from the old one, and 296 /// then rebind it to the new one. 297 /// 298 /// Binding a device will invalidate that portion of the web page to flush the 299 /// contents of the new device to the screen. 300 /// 301 /// @param[in] graphics A <code>Graphics2D</code> to bind. 302 /// 303 /// @return true if bind was successful or false if the device was not the 304 /// correct type. On success, a reference to the device will be held by the 305 /// instance, so the caller can release its reference if it chooses. 306 bool BindGraphics(const Graphics2D& graphics); 307 308 /// Binds the given Graphics3D as the current display surface. 309 /// Refer to <code>BindGraphics(const Graphics2D& graphics)</code> for 310 /// further information. 311 /// 312 /// @param[in] graphics A <code>Graphics3D</code> to bind. 313 /// 314 /// @return true if bind was successful or false if the device was not the 315 /// correct type. On success, a reference to the device will be held by the 316 /// instance, so the caller can release its reference if it chooses. 317 bool BindGraphics(const Graphics3D& graphics); 318 319 /// IsFullFrame() determines if the instance is full-frame (repr). 320 /// Such an instance represents the entire document in a frame rather than an 321 /// embedded resource. This can happen if the user does a top-level 322 /// navigation or the page specifies an iframe to a resource with a MIME 323 /// type registered by the module. 324 /// 325 /// @return true if the instance is full-frame, false if not. 326 bool IsFullFrame(); 327 328 /// RequestInputEvents() requests that input events corresponding to the 329 /// given input events are delivered to the instance. 330 /// 331 /// By default, no input events are delivered. Call this function with the 332 /// classes of events you are interested in to have them be delivered to 333 /// the instance. Calling this function will override any previous setting for 334 /// each specified class of input events (for example, if you previously 335 /// called RequestFilteringInputEvents(), this function will set those events 336 /// to non-filtering mode). 337 /// 338 /// Input events may have high overhead, so you should only request input 339 /// events that your plugin will actually handle. For example, the browser may 340 /// do optimizations for scroll or touch events that can be processed 341 /// substantially faster if it knows there are no non-default receivers for 342 /// that message. Requesting that such messages be delivered, even if they are 343 /// processed very quickly, may have a noticeable effect on the performance of 344 /// the page. 345 /// 346 /// When requesting input events through this function, the events will be 347 /// delivered and <em>not</em> bubbled to the page. This means that even if 348 /// you aren't interested in the message, no other parts of the page will get 349 /// the message. 350 /// 351 /// <strong>Example:</strong> 352 /// 353 /// @code 354 /// RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); 355 /// RequestFilteringInputEvents( 356 /// PP_INPUTEVENT_CLASS_WHEEL | PP_INPUTEVENT_CLASS_KEYBOARD); 357 /// 358 /// @endcode 359 /// 360 /// @param event_classes A combination of flags from 361 /// <code>PP_InputEvent_Class</code> that identifies the classes of events 362 /// the instance is requesting. The flags are combined by logically ORing 363 /// their values. 364 /// 365 /// @return <code>PP_OK</code> if the operation succeeded, 366 /// <code>PP_ERROR_BADARGUMENT</code> if instance is invalid, or 367 /// <code>PP_ERROR_NOTSUPPORTED</code> if one of the event class bits were 368 /// illegal. In the case of an invalid bit, all valid bits will be applied 369 /// and only the illegal bits will be ignored. 370 int32_t RequestInputEvents(uint32_t event_classes); 371 372 /// RequestFilteringInputEvents() requests that input events corresponding 373 /// to the given input events are delivered to the instance for filtering. 374 /// 375 /// By default, no input events are delivered. In most cases you would 376 /// register to receive events by calling RequestInputEvents(). In some cases, 377 /// however, you may wish to filter events such that they can be bubbled up 378 /// to the DOM. In this case, register for those classes of events using 379 /// this function instead of RequestInputEvents(). Keyboard events must always 380 /// be registered in filtering mode. 381 /// 382 /// Filtering input events requires significantly more overhead than just 383 /// delivering them to the instance. As such, you should only request 384 /// filtering in those cases where it's absolutely necessary. The reason is 385 /// that it requires the browser to stop and block for the instance to handle 386 /// the input event, rather than sending the input event asynchronously. This 387 /// can have significant overhead. 388 /// 389 /// <strong>Example:</strong> 390 /// 391 /// @code 392 /// 393 /// RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); 394 /// RequestFilteringInputEvents( 395 /// PP_INPUTEVENT_CLASS_WHEEL | PP_INPUTEVENT_CLASS_KEYBOARD); 396 /// 397 /// @endcode 398 /// 399 /// @param event_classes A combination of flags from 400 /// <code>PP_InputEvent_Class</code> that identifies the classes of events 401 /// the instance is requesting. The flags are combined by logically ORing 402 /// their values. 403 /// 404 /// @return <code>PP_OK</code> if the operation succeeded, 405 /// <code>PP_ERROR_BADARGUMENT</code> if instance is invalid, or 406 /// <code>PP_ERROR_NOTSUPPORTED</code> if one of the event class bits were 407 /// illegal. In the case of an invalid bit, all valid bits will be applied 408 /// and only the illegal bits will be ignored. 409 int32_t RequestFilteringInputEvents(uint32_t event_classes); 410 411 /// ClearInputEventRequest() requests that input events corresponding to the 412 /// given input classes no longer be delivered to the instance. 413 /// 414 /// By default, no input events are delivered. If you have previously 415 /// requested input events using RequestInputEvents() or 416 /// RequestFilteringInputEvents(), this function will unregister handling 417 /// for the given instance. This will allow greater browser performance for 418 /// those events. 419 /// 420 /// <strong>Note: </strong> You may still get some input events after 421 /// clearing the flag if they were dispatched before the request was cleared. 422 /// For example, if there are 3 mouse move events waiting to be delivered, 423 /// and you clear the mouse event class during the processing of the first 424 /// one, you'll still receive the next two. You just won't get more events 425 /// generated. 426 /// 427 /// @param[in] event_classes A combination of flags from 428 /// <code>PP_InputEvent_Class</code> that identifies the classes of events the 429 /// instance is no longer interested in. 430 void ClearInputEventRequest(uint32_t event_classes); 431 432 /// PostMessage() asynchronously invokes any listeners for message events on 433 /// the DOM element for the given instance. A call to PostMessage() will 434 /// not block while the message is processed. 435 /// 436 /// <strong>Example:</strong> 437 /// 438 /// @code{.html} 439 /// 440 /// <body> 441 /// <object id="plugin" 442 /// type="application/x-ppapi-postMessage-example"/> 443 /// <script type="text/javascript"> 444 /// var plugin = document.getElementById('plugin'); 445 /// plugin.addEventListener("message", 446 /// function(message) { alert(message.data); }, 447 /// false); 448 /// </script> 449 /// </body> 450 /// 451 /// @endcode 452 /// 453 /// The instance then invokes PostMessage() as follows: 454 /// 455 /// @code 456 /// 457 /// PostMessage(pp::Var("Hello world!")); 458 /// 459 /// @endcode 460 /// 461 /// The browser will pop-up an alert saying "Hello world!" 462 /// 463 /// When passing array or dictionary <code>PP_Var</code>s, the entire 464 /// reference graph will be converted and transferred. If the reference graph 465 /// has cycles, the message will not be sent and an error will be logged to 466 /// the console. 467 /// 468 /// Listeners for message events in JavaScript code will receive an object 469 /// conforming to the HTML 5 <code>MessageEvent</code> interface. 470 /// Specifically, the value of message will be contained as a property called 471 /// data in the received <code>MessageEvent</code>. 472 /// 473 /// This messaging system is similar to the system used for listening for 474 /// messages from Web Workers. Refer to 475 /// <code>http://www.whatwg.org/specs/web-workers/current-work/</code> for 476 /// further information. 477 /// 478 /// Refer to HandleMessage() for receiving events from JavaScript. 479 /// 480 /// @param[in] message A <code>Var</code> containing the data to be sent to 481 /// JavaScript. Message can have a numeric, boolean, or string value. 482 /// Array/Dictionary types are supported from Chrome M29 onward. 483 /// All var types are copied when passing them to JavaScript. 484 void PostMessage(const Var& message); 485 486 /// @} 487 488 /// @{ 489 /// @name PPB_Console methods for logging to the console: 490 491 /// Logs the given message to the JavaScript console associated with the 492 /// given plugin instance with the given logging level. The name of the plugin 493 /// issuing the log message will be automatically prepended to the message. 494 /// The value may be any type of Var. 495 void LogToConsole(PP_LogLevel level, const Var& value); 496 497 /// Logs a message to the console with the given source information rather 498 /// than using the internal PPAPI plugin name. The name must be a string var. 499 /// 500 /// The regular log function will automatically prepend the name of your 501 /// plugin to the message as the "source" of the message. Some plugins may 502 /// wish to override this. For example, if your plugin is a Python 503 /// interpreter, you would want log messages to contain the source .py file 504 /// doing the log statement rather than have "python" show up in the console. 505 void LogToConsoleWithSource(PP_LogLevel level, 506 const Var& source, 507 const Var& value); 508 509 /// @} 510 511 /// AddPerInstanceObject() associates an instance with an interface, 512 /// creating an object. 513 /// 514 /// Many optional interfaces are associated with a plugin instance. For 515 /// example, the find in PPP_Find interface receives updates on a per-instance 516 /// basis. This "per-instance" tracking allows such objects to associate 517 /// themselves with an instance as "the" handler for that interface name. 518 /// 519 /// In the case of the find example, the find object registers with its 520 /// associated instance in its constructor and unregisters in its destructor. 521 /// Then whenever it gets updates with a PP_Instance parameter, it can 522 /// map back to the find object corresponding to that given PP_Instance by 523 /// calling GetPerInstanceObject. 524 /// 525 /// This lookup is done on a per-interface-name basis. This means you can 526 /// only have one object of a given interface name associated with an 527 /// instance. 528 /// 529 /// If you are adding a handler for an additional interface, be sure to 530 /// register with the module (AddPluginInterface) for your interface name to 531 /// get the C calls in the first place. 532 /// 533 /// Refer to RemovePerInstanceObject() and GetPerInstanceObject() for further 534 /// information. 535 /// 536 /// @param[in] interface_name The name of the interface to associate with the 537 /// instance 538 /// @param[in] object 539 void AddPerInstanceObject(const std::string& interface_name, void* object); 540 541 // {PENDING: summarize Remove method here} 542 /// 543 /// Refer to AddPerInstanceObject() for further information. 544 /// 545 /// @param[in] interface_name The name of the interface to associate with the 546 /// instance 547 /// @param[in] object 548 void RemovePerInstanceObject(const std::string& interface_name, void* object); 549 550 /// Static version of AddPerInstanceObject that takes an InstanceHandle. As 551 /// with all other instance functions, this must only be called on the main 552 /// thread. 553 static void RemovePerInstanceObject(const InstanceHandle& instance, 554 const std::string& interface_name, 555 void* object); 556 557 /// Look up an object previously associated with an instance. Returns NULL 558 /// if the instance is invalid or there is no object for the given interface 559 /// name on the instance. 560 /// 561 /// Refer to AddPerInstanceObject() for further information. 562 /// 563 /// @param[in] instance 564 /// @param[in] interface_name The name of the interface to associate with the 565 /// instance. 566 static void* GetPerInstanceObject(PP_Instance instance, 567 const std::string& interface_name); 568 569 private: 570 PP_Instance pp_instance_; 571 572 typedef std::map<std::string, void*> InterfaceNameToObjectMap; 573 InterfaceNameToObjectMap interface_name_to_objects_; 574 }; 575 576 } // namespace pp 577 578 #endif // PPAPI_CPP_INSTANCE_H_ 579