_screencast.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. # Copyright (c) Microsoft Corporation.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import base64
  15. from pathlib import Path
  16. from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union
  17. from playwright._impl._api_structures import ScreencastFrame
  18. from playwright._impl._artifact import Artifact
  19. from playwright._impl._connection import from_nullable_channel
  20. from playwright._impl._disposable import DisposableStub
  21. from playwright._impl._errors import Error
  22. from playwright._impl._helper import locals_to_params
  23. if TYPE_CHECKING: # pragma: no cover
  24. from playwright._impl._page import Page
  25. ScreencastFrameCallback = Callable[[ScreencastFrame], Any]
  26. ScreencastPosition = Literal[
  27. "bottom",
  28. "bottom-left",
  29. "bottom-right",
  30. "top",
  31. "top-left",
  32. "top-right",
  33. ]
  34. class Screencast:
  35. def __init__(self, page: "Page") -> None:
  36. self._page = page
  37. self._loop = page._loop
  38. self._dispatcher_fiber = page._dispatcher_fiber
  39. self._started = False
  40. self._save_path: Optional[Union[str, Path]] = None
  41. self._on_frame: Optional[ScreencastFrameCallback] = None
  42. self._artifact: Optional[Artifact] = None
  43. page._channel.on("screencastFrame", lambda params: self._dispatch_frame(params))
  44. def _dispatch_frame(self, params: dict) -> None:
  45. if not self._on_frame:
  46. return
  47. data = params["data"]
  48. if isinstance(data, str):
  49. data = base64.b64decode(data)
  50. result = self._on_frame(
  51. {
  52. "data": data,
  53. "viewportWidth": params["viewportWidth"],
  54. "viewportHeight": params["viewportHeight"],
  55. }
  56. )
  57. if hasattr(result, "__await__"):
  58. self._page._loop.create_task(result)
  59. async def start(
  60. self,
  61. onFrame: ScreencastFrameCallback = None,
  62. path: Union[str, Path] = None,
  63. quality: int = None,
  64. ) -> DisposableStub:
  65. if self._started:
  66. raise Error("Screencast is already started")
  67. self._started = True
  68. self._on_frame = onFrame
  69. result = await self._page._channel.send_return_as_dict(
  70. "screencastStart",
  71. None,
  72. {
  73. "quality": quality,
  74. "sendFrames": bool(onFrame),
  75. "record": bool(path),
  76. },
  77. )
  78. artifact_channel = (result or {}).get("artifact")
  79. if artifact_channel:
  80. self._artifact = from_nullable_channel(artifact_channel)
  81. self._save_path = path
  82. return DisposableStub(lambda: self.stop(), self._page)
  83. async def stop(self) -> None:
  84. self._started = False
  85. self._on_frame = None
  86. await self._page._channel.send("screencastStop", None)
  87. if self._save_path and self._artifact:
  88. await self._artifact.save_as(self._save_path)
  89. self._artifact = None
  90. self._save_path = None
  91. async def show_actions(
  92. self,
  93. duration: float = None,
  94. position: ScreencastPosition = None,
  95. fontSize: int = None,
  96. ) -> DisposableStub:
  97. await self._page._channel.send(
  98. "screencastShowActions", None, locals_to_params(locals())
  99. )
  100. return DisposableStub(lambda: self.hide_actions(), self._page)
  101. async def hide_actions(self) -> None:
  102. await self._page._channel.send("screencastHideActions", None)
  103. async def show_overlay(self, html: str, duration: float = None) -> DisposableStub:
  104. result = await self._page._channel.send_return_as_dict(
  105. "screencastShowOverlay", None, locals_to_params(locals())
  106. )
  107. overlay_id = (result or {}).get("id")
  108. return DisposableStub(
  109. lambda: self._page._channel.send(
  110. "screencastRemoveOverlay", None, {"id": overlay_id}
  111. ),
  112. self._page,
  113. )
  114. async def show_chapter(
  115. self,
  116. title: str,
  117. description: str = None,
  118. duration: float = None,
  119. ) -> None:
  120. await self._page._channel.send(
  121. "screencastChapter", None, locals_to_params(locals())
  122. )
  123. async def show_overlays(self) -> None:
  124. await self._page._channel.send(
  125. "screencastSetOverlayVisible", None, {"visible": True}
  126. )
  127. async def hide_overlays(self) -> None:
  128. await self._page._channel.send(
  129. "screencastSetOverlayVisible", None, {"visible": False}
  130. )