manager.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2019 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. #ifndef COMPONENTS_CAST_API_BINDINGS_MANAGER_H_
  5. #define COMPONENTS_CAST_API_BINDINGS_MANAGER_H_
  6. #include <map>
  7. #include <string>
  8. #include "base/callback.h"
  9. #include "base/containers/flat_map.h"
  10. #include "base/strings/string_piece.h"
  11. #include "components/cast/cast_component_export.h"
  12. #include "components/cast/message_port/message_port.h"
  13. namespace cast_api_bindings {
  14. // Allows the caller to specify the JS that should be injected into a container,
  15. // and to register handlers for communication with the content.
  16. class CAST_COMPONENT_EXPORT Manager {
  17. public:
  18. using MessagePortConnectedHandler = base::RepeatingCallback<void(
  19. std::unique_ptr<cast_api_bindings::MessagePort>)>;
  20. Manager();
  21. Manager(const Manager&) = delete;
  22. Manager& operator=(const Manager&) = delete;
  23. virtual ~Manager();
  24. // Registers a |handler| which will receive MessagePorts originating from
  25. // the frame's web content. |port_name| is an alphanumeric string that is
  26. // consistent across JS and native code.
  27. // All handlers must be Unregistered() before |this| is destroyed.
  28. void RegisterPortHandler(base::StringPiece port_name,
  29. MessagePortConnectedHandler handler);
  30. // Unregisters a previously registered handler.
  31. // The owner of Manager is responsible for ensuring that all
  32. // handlers are unregistered before |this| is deleted.
  33. void UnregisterPortHandler(base::StringPiece port_name);
  34. // Registers a |binding_script| for injection in the frame.
  35. // Replaces registered bindings with the same |binding_name|.
  36. virtual void AddBinding(base::StringPiece binding_name,
  37. base::StringPiece binding_script) = 0;
  38. protected:
  39. // Called by platform-specific implementations when the content requests a
  40. // connection to |port_name|.
  41. // Returns |false| if the port was invalid or not registered in advance, at
  42. // which point the matchmaking port should be dropped.
  43. bool OnPortConnected(base::StringPiece port_name,
  44. std::unique_ptr<cast_api_bindings::MessagePort> port);
  45. private:
  46. base::flat_map<std::string, MessagePortConnectedHandler> port_handlers_;
  47. };
  48. } // namespace cast_api_bindings
  49. #endif // COMPONENTS_CAST_API_BINDINGS_MANAGER_H_