{"repo": "BoboTiG/python-mss", "n_pairs": 81, "version": "v2_function_scoped", "contexts": {"src/tests/test_xcb.py::334": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["Callable", "ScreenShotError", "pytest", "xcb", "xgetimage"], "enclosing_function": "test_xgetimage_visual_validation_failures", "extracted_code": "# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}\n\n\n# Source: src/mss/linux/__init__.py\nfrom mss.exception import ScreenShotError\n\nBACKENDS = [\"default\", \"xlib\", \"xgetimage\", \"xshmgetimage\"]\n\n\ndef mss(backend: str = \"default\", **kwargs: Any) -> MSSBase:\n \"\"\"Return a backend-specific MSS implementation for GNU/Linux.\n\n Selects and instantiates the appropriate X11 backend based on the\n ``backend`` parameter.\n\n :param backend: Backend selector. Valid values:\n\n using XShmGetImage with automatic fallback to XGetImage when MIT-SHM\n is unavailable; see :py:class:`mss.linux.xshmgetimage.MSS`.\n - ``\"xgetimage\"``: XCB-based backend using XGetImage;\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n\n is unavailable; see :py:class:`mss.linux.xshmgetimage.MSS`.\n - ``\"xgetimage\"``: XCB-based backend using XGetImage;\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n\n\n return xlib.MSS(**kwargs)\n if backend == \"xgetimage\":\n from . import xgetimage # noqa: PLC0415\n\n # Note that the xshmgetimage backend will automatically fall back to XGetImage calls if XShmGetImage isn't\n # available. The only reason to use the xgetimage backend is if the user already knows that XShmGetImage\n # isn't going to be supported.\n return xgetimage.MSS(**kwargs)\n if backend in {\"default\", \"xshmgetimage\"}:\n from . import xshmgetimage # noqa: PLC0415\n\n\n return xlib.MSS(**kwargs)\n if backend == \"xgetimage\":\n from . import xgetimage # noqa: PLC0415\n\n # Note that the xshmgetimage backend will automatically fall back to XGetImage calls if XShmGetImage isn't\n # available. The only reason to use the xgetimage backend is if the user already knows that XShmGetImage\n # isn't going to be supported.\n return xgetimage.MSS(**kwargs)\n if backend in {\"default\", \"xshmgetimage\"}:\n from . import xshmgetimage # noqa: PLC0415\n\n return xshmgetimage.MSS(**kwargs)", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 3442}, "src/tests/test_find_monitors.py::18": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase"], "enclosing_function": "test_keys_aio", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_gnu_linux.py::191": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["linux", "mss", "pytest", "xlib"], "enclosing_function": "test_fast_function_for_monitor_details_retrieval", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/linux/__init__.py\n - ``\"default\"`` or ``\"xshmgetimage\"`` (default): XCB-based backend\n using XShmGetImage with automatic fallback to XGetImage when MIT-SHM\n is unavailable; see :py:class:`mss.linux.xshmgetimage.MSS`.\n - ``\"xgetimage\"``: XCB-based backend using XGetImage;\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n\n is unavailable; see :py:class:`mss.linux.xshmgetimage.MSS`.\n - ``\"xgetimage\"``: XCB-based backend using XGetImage;\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n variable :envvar:`DISPLAY`.\n :type display: str | bytes | None\n\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n variable :envvar:`DISPLAY`.\n :type display: str | bytes | None\n :param kwargs: Additional keyword arguments passed to the backend class.\n :returns: An MSS backend implementation.\n\n\n\n .. versionadded:: 10.2.0 Prior to this version, this didn't exist:\n the :func:`mss.linux.MSS` was a class equivalent to the current\n :class:`mss.linux.xlib.MSS` implementation.\n \"\"\"\n backend = backend.lower()\n if backend == \"xlib\":\n from . import xlib # noqa: PLC0415\n\n return xlib.MSS(**kwargs)\n if backend == \"xgetimage\":\n from . import xgetimage # noqa: PLC0415\n\n\n# Source: src/mss/linux/xlib.py\nclass XID(c_ulong):\n \"\"\"X11 generic resource ID\n https://tronche.com/gui/x/xlib/introduction/generic.html\n https://gitlab.freedesktop.org/xorg/proto/xorgproto/-/blob/master/include/X11/X.h#L66\n \"\"\"\n\n\nclass XStatus(c_int):\n \"\"\"Xlib common return code type\n This is Status in Xlib, but XStatus here to prevent ambiguity.\n Zero is an error, non-zero is success.\n https://tronche.com/gui/x/xlib/introduction/errors.html\n\n This is Status in Xlib, but XStatus here to prevent ambiguity.\n Zero is an error, non-zero is success.\n https://tronche.com/gui/x/xlib/introduction/errors.html\n https://gitlab.freedesktop.org/xorg/lib/libx11/-/blob/master/include/X11/Xlib.h#L79\n \"\"\"\n\n\nclass XBool(c_int):\n \"\"\"Xlib boolean type\n This is Bool in Xlib, but XBool here to prevent ambiguity.\n 0 is False, 1 is True.\n https://tronche.com/gui/x/xlib/introduction/generic.html\n\n This is Bool in Xlib, but XBool here to prevent ambiguity.\n 0 is False, 1 is True.\n https://tronche.com/gui/x/xlib/introduction/generic.html\n https://gitlab.freedesktop.org/xorg/lib/libx11/-/blob/master/include/X11/Xlib.h#L78\n \"\"\"\n\n\nclass Display(Structure):\n \"\"\"Structure that serves as the connection to the X server\n and that contains all the information about that X server.\n The contents of this structure are implementation dependent.\n A Display should be treated as opaque by application code.\n\n The contents of this structure are implementation dependent.\n A Display should be treated as opaque by application code.\n https://tronche.com/gui/x/xlib/display/display-macros.html\n https://gitlab.freedesktop.org/xorg/lib/libx11/-/blob/master/include/X11/Xlib.h#L477\n https://github.com/garrybodsworth/pyxlib-ctypes/blob/master/pyxlib/xlib.py#L831.\n \"\"\"\n\n # Opaque data\n\n\nclass Visual(Structure):\n \"\"\"Visual structure; contains information about colormapping possible.\n\n https://tronche.com/gui/x/xlib/display/display-macros.html\n https://gitlab.freedesktop.org/xorg/lib/libx11/-/blob/master/include/X11/Xlib.h#L477\n https://github.com/garrybodsworth/pyxlib-ctypes/blob/master/pyxlib/xlib.py#L831.\n \"\"\"\n\n # Opaque data\n\n\nclass Visual(Structure):\n \"\"\"Visual structure; contains information about colormapping possible.\n https://tronche.com/gui/x/xlib/window/visual-types.html\n https://gitlab.freedesktop.org/xorg/lib/libx11/-/blob/master/include/X11/Xlib.hheads#L220", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 6427}, "src/tests/test_xcb.py::143": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["Any", "Mock", "POINTER", "array_from_xcb", "cast", "finalize"], "enclosing_function": "test_array_from_xcb_keeps_parent_alive_until_array_gone", "extracted_code": "# Source: src/mss/linux/xcbhelpers.py\ndef array_from_xcb(pointer_func: Callable, length_func: Callable, parent: Structure | _Pointer) -> Array:\n pointer = pointer_func(parent)\n length = length_func(parent)\n if length and not pointer:\n msg = \"XCB returned a NULL pointer for non-zero data length\"\n raise ScreenShotError(msg)\n array_ptr = cast(pointer, POINTER(pointer._type_ * length))\n array = array_ptr.contents\n depends_on(array, parent)\n return array", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 488}, "src/tests/test_implementation.py::209": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["ScreenShotError", "main", "patch", "pytest", "sys"], "enclosing_function": "test_entry_point_error", "extracted_code": "# Source: src/mss/__main__.py\ndef main(*args: str) -> int:\n \"\"\"Main logic.\"\"\"\n backend_choices = _backend_cli_choices()\n\n cli_args = ArgumentParser(prog=\"mss\", exit_on_error=False)\n cli_args.add_argument(\n \"-c\",\n \"--coordinates\",\n default=\"\",\n type=str,\n help=\"the part of the screen to capture: top, left, width, height\",\n )\n cli_args.add_argument(\n \"-l\",\n \"--level\",\n default=6,\n type=int,\n choices=list(range(10)),\n help=\"the PNG compression level\",\n )\n cli_args.add_argument(\"-m\", \"--monitor\", default=0, type=int, help=\"the monitor to screenshot\")\n cli_args.add_argument(\"-o\", \"--output\", default=\"monitor-{mon}.png\", help=\"the output file name\")\n cli_args.add_argument(\"--with-cursor\", default=False, action=\"store_true\", help=\"include the cursor\")\n cli_args.add_argument(\n \"-q\",\n \"--quiet\",\n default=False,\n action=\"store_true\",\n help=\"do not print created files\",\n )\n cli_args.add_argument(\n \"-b\", \"--backend\", default=\"default\", choices=backend_choices, help=\"platform-specific backend to use\"\n )\n cli_args.add_argument(\"-v\", \"--version\", action=\"version\", version=__version__)\n\n try:\n options = cli_args.parse_args(args or None)\n except ArgumentError as e:\n # By default, parse_args will print and the error and exit. We\n # return instead of exiting, to make unit testing easier.\n cli_args.print_usage(sys.stderr)\n print(f\"{cli_args.prog}: error: {e}\", file=sys.stderr)\n return 2\n kwargs = {\"mon\": options.monitor, \"output\": options.output}\n if options.coordinates:\n try:\n top, left, width, height = options.coordinates.split(\",\")\n except ValueError:\n print(\"Coordinates syntax: top, left, width, height\")\n return 2\n\n kwargs[\"mon\"] = {\n \"top\": int(top),\n \"left\": int(left),\n \"width\": int(width),\n \"height\": int(height),\n }\n if options.output == \"monitor-{mon}.png\":\n kwargs[\"output\"] = \"sct-{top}x{left}_{width}x{height}.png\"\n\n try:\n with mss(with_cursor=options.with_cursor, backend=options.backend) as sct:\n if options.coordinates:\n output = kwargs[\"output\"].format(**kwargs[\"mon\"])\n sct_img = sct.grab(kwargs[\"mon\"])\n to_png(sct_img.rgb, sct_img.size, level=options.level, output=output)\n if not options.quiet:\n print(os.path.realpath(output))\n else:\n for file_name in sct.save(**kwargs):\n if not options.quiet:\n print(os.path.realpath(file_name))\n return 0\n except ScreenShotError:\n if options.quiet:\n return 1\n raise\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 3524}, "src/tests/test_get_pixels.py::29": {"resolved_imports": ["src/mss/base.py", "src/mss/exception.py"], "used_names": ["Callable", "MSSBase", "itertools"], "enclosing_function": "test_grab_part_of_screen", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 12022}, "src/tests/test_tools.py::132": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_manufacture_year_only", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/test_tools.py::153": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_serial_number_integer", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/test_gnu_linux.py::263": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["mss"], "enclosing_function": "test_with_cursor", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 1102}, "src/tests/test_xcb.py::299": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["addressof", "xcb"], "enclosing_function": "test_atom_cache_lifecycle", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 0}, "src/tests/test_implementation.py::135": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["Path", "pytest"], "enclosing_function": "test_monitor_option_and_quiet", "extracted_code": "", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 0}, "src/tests/test_gnu_linux.py::318": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["linux", "mss"], "enclosing_function": "test_shm_fallback", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/linux/__init__.py\n - ``\"default\"`` or ``\"xshmgetimage\"`` (default): XCB-based backend\n using XShmGetImage with automatic fallback to XGetImage when MIT-SHM\n is unavailable; see :py:class:`mss.linux.xshmgetimage.MSS`.\n - ``\"xgetimage\"``: XCB-based backend using XGetImage;\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n\n is unavailable; see :py:class:`mss.linux.xshmgetimage.MSS`.\n - ``\"xgetimage\"``: XCB-based backend using XGetImage;\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n variable :envvar:`DISPLAY`.\n :type display: str | bytes | None\n\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n variable :envvar:`DISPLAY`.\n :type display: str | bytes | None\n :param kwargs: Additional keyword arguments passed to the backend class.\n :returns: An MSS backend implementation.\n\n\n\n .. versionadded:: 10.2.0 Prior to this version, this didn't exist:\n the :func:`mss.linux.MSS` was a class equivalent to the current\n :class:`mss.linux.xlib.MSS` implementation.\n \"\"\"\n backend = backend.lower()\n if backend == \"xlib\":\n from . import xlib # noqa: PLC0415\n\n return xlib.MSS(**kwargs)\n if backend == \"xgetimage\":\n from . import xgetimage # noqa: PLC0415", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 3942}, "src/tests/test_implementation.py::230": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["Mock", "patch", "pytest", "sys"], "enclosing_function": "test_entry_point_with_no_argument", "extracted_code": "", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 0}, "src/tests/third_party/test_numpy.py::18": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase"], "enclosing_function": "test_numpy", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_macos.py::63": {"resolved_imports": ["src/mss/__init__.py", "src/mss/exception.py", "src/mss/darwin.py"], "used_names": ["ScreenShotError", "darwin", "mss", "platform", "pytest", "util"], "enclosing_function": "test_implementation", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 1746}, "src/tests/test_xcb.py::298": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["addressof", "xcb"], "enclosing_function": "test_atom_cache_lifecycle", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 0}, "src/tests/test_implementation.py::251": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["MSSBase"], "enclosing_function": "test_grab_with_tuple", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 12022}, "src/tests/test_tools.py::146": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_model_year", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/test_get_pixels.py::38": {"resolved_imports": ["src/mss/base.py", "src/mss/exception.py"], "used_names": ["ScreenShot", "ScreenShotError", "pytest"], "enclosing_function": "test_get_pixel", "extracted_code": "# Source: src/mss/base.py\nfrom typing import TYPE_CHECKING, Any\n\nfrom mss.exception import ScreenShotError\nfrom mss.screenshot import ScreenShot\nfrom mss.tools import to_png\n\nif TYPE_CHECKING: # pragma: nocover\n from collections.abc import Callable, Iterator\n\n from mss.models import Monitor, Monitors\n\n # Prior to 3.11, Python didn't have the Self type. typing_extensions does, but we don't want to depend on it.\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.screenshot import ScreenShot\nfrom mss.tools import to_png\n\nif TYPE_CHECKING: # pragma: nocover\n from collections.abc import Callable, Iterator\n\n from mss.models import Monitor, Monitors\n\n # Prior to 3.11, Python didn't have the Self type. typing_extensions does, but we don't want to depend on it.\n try:\n\n\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2992}, "src/tests/test_get_pixels.py::32": {"resolved_imports": ["src/mss/base.py", "src/mss/exception.py"], "used_names": ["Callable", "MSSBase", "itertools"], "enclosing_function": "test_grab_part_of_screen", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 12022}, "src/tests/test_save.py::55": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase", "Path"], "enclosing_function": "test_output_format_simple", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_tools.py::140": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_manufacture_week_and_year", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/test_xcb.py::284": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["pytest", "xcb"], "enclosing_function": "test_raises_when_missing_and_not_only_if_exists", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 0}, "src/tests/test_macos.py::33": {"resolved_imports": ["src/mss/__init__.py", "src/mss/exception.py", "src/mss/darwin.py"], "used_names": ["darwin", "mss"], "enclosing_function": "test_repr", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 1102}, "src/tests/test_find_monitors.py::27": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase"], "enclosing_function": "test_keys_monitor_1", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_windows.py::38": {"resolved_imports": ["src/mss/__init__.py"], "used_names": ["mss"], "enclosing_function": "test_region_caching", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1102}, "src/tests/test_xcb.py::302": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["addressof", "xcb"], "enclosing_function": "test_atom_cache_lifecycle", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 0}, "src/tests/test_save.py::63": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase", "Path"], "enclosing_function": "test_output_format_positions_and_sizes", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_primary_monitor.py::31": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase"], "enclosing_function": "test_primary_monitor", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_implementation.py::316": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["threading", "time"], "enclosing_function": "run_test", "extracted_code": "", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 0}, "src/tests/test_tools.py::168": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_descriptor_display_name", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/third_party/test_pil.py::23": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase", "Path", "itertools"], "enclosing_function": "test_pil", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_implementation.py::61": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["MSSBase", "pytest"], "enclosing_function": "test_incomplete_class", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 12022}, "src/tests/test_windows.py::55": {"resolved_imports": ["src/mss/__init__.py"], "used_names": ["mss"], "enclosing_function": "test_region_not_caching", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1102}, "src/tests/conftest.py::69": {"resolved_imports": ["src/mss/__init__.py", "src/mss/base.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py"], "used_names": ["Path", "ZipFile", "pytest", "sha256"], "enclosing_function": "raw", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 5, "n_chars_extracted": 0}, "src/tests/test_implementation.py::76": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["MSSBase", "ScreenShot"], "enclosing_function": "test_repr", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck\n\n\n# Source: src/mss/screenshot.py\nclass ScreenShot:\n \"\"\"Screenshot object.\n\n .. note::\n\n A better name would have been *Image*, but to prevent collisions\n with PIL.Image, it has been decided to use *ScreenShot*.\n \"\"\"\n\n __slots__ = {\"__pixels\", \"__rgb\", \"pos\", \"raw\", \"size\"}\n\n def __init__(self, data: bytearray, monitor: Monitor, /, *, size: Size | None = None) -> None:\n self.__pixels: Pixels | None = None\n self.__rgb: bytes | None = None\n\n #: Bytearray of the raw BGRA pixels retrieved by ctypes\n #: OS independent implementations.\n self.raw: bytearray = data\n\n #: NamedTuple of the screenshot coordinates.\n self.pos: Pos = Pos(monitor[\"left\"], monitor[\"top\"])\n\n #: NamedTuple of the screenshot size.\n self.size: Size = Size(monitor[\"width\"], monitor[\"height\"]) if size is None else size\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__} pos={self.left},{self.top} size={self.width}x{self.height}>\"\n\n @property\n def __array_interface__(self) -> dict[str, Any]:\n \"\"\"NumPy array interface support.\n\n This is used by NumPy, many SciPy projects, CuPy, PyTorch (via\n ``torch.from_numpy``), TensorFlow (via ``tf.convert_to_tensor``),\n JAX (via ``jax.numpy.asarray``), Pandas, scikit-learn, Matplotlib,\n some OpenCV functions, and others. This allows you to pass a\n :class:`ScreenShot` instance directly to these libraries without\n needing to convert it first.\n\n This is in HWC order, with 4 channels (BGRA).\n\n .. seealso::\n\n https://numpy.org/doc/stable/reference/arrays.interface.html\n The NumPy array interface protocol specification\n \"\"\"\n return {\n \"version\": 3,\n \"shape\": (self.height, self.width, 4),\n \"typestr\": \"|u1\",\n \"data\": self.raw,\n }\n\n @classmethod\n def from_size(cls: type[ScreenShot], data: bytearray, width: int, height: int, /) -> ScreenShot:\n \"\"\"Instantiate a new class given only screenshot's data and size.\"\"\"\n monitor = {\"left\": 0, \"top\": 0, \"width\": width, \"height\": height}\n return cls(data, monitor)\n\n @property\n def bgra(self) -> bytes:\n \"\"\"BGRx values from the BGRx raw pixels.\n\n The format is a bytes object with BGRxBGRx... sequence. A specific\n pixel can be accessed as\n ``bgra[(y * width + x) * 4:(y * width + x) * 4 + 4].``\n\n .. note::\n While the name is ``bgra``, the alpha channel may or may not be\n valid.\n \"\"\"\n return bytes(self.raw)\n\n @property\n def pixels(self) -> Pixels:\n \"\"\"RGB tuples.\n\n The format is a list of rows. Each row is a list of pixels.\n Each pixel is a tuple of (R, G, B).\n \"\"\"\n if not self.__pixels:\n rgb_tuples: Iterator[Pixel] = zip(self.raw[2::4], self.raw[1::4], self.raw[::4])\n self.__pixels = list(zip(*[iter(rgb_tuples)] * self.width))\n\n return self.__pixels\n\n def pixel(self, coord_x: int, coord_y: int) -> Pixel:\n \"\"\"Return the pixel value at a given position.\n\n :returns: A tuple of (R, G, B) values.\n \"\"\"\n try:\n return self.pixels[coord_y][coord_x]\n except IndexError as exc:\n msg = f\"Pixel location ({coord_x}, {coord_y}) is out of range.\"\n raise ScreenShotError(msg) from exc\n\n @property\n def rgb(self) -> bytes:\n \"\"\"Compute RGB values from the BGRA raw pixels.\n\n The format is a bytes object with BGRBGR... sequence. A specific\n pixel can be accessed as\n ``rgb[(y * width + x) * 3:(y * width + x) * 3 + 3]``.\n \"\"\"\n if not self.__rgb:\n rgb = bytearray(self.height * self.width * 3)\n raw = self.raw\n rgb[::3] = raw[2::4]\n rgb[1::3] = raw[1::4]\n rgb[2::3] = raw[::4]\n self.__rgb = bytes(rgb)\n\n return self.__rgb\n\n @property\n def top(self) -> int:\n \"\"\"Convenient accessor to the top position.\"\"\"\n return self.pos.top\n\n @property\n def left(self) -> int:\n \"\"\"Convenient accessor to the left position.\"\"\"\n return self.pos.left\n\n @property\n def width(self) -> int:\n \"\"\"Convenient accessor to the width size.\"\"\"\n return self.size.width\n\n @property\n def height(self) -> int:\n \"\"\"Convenient accessor to the height size.\"\"\"\n return self.size.height", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 16548}, "src/tests/test_xcb.py::265": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["addressof", "pytest", "xcb"], "enclosing_function": "test_cache_miss_calls_xcb_and_caches_result", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 0}, "src/tests/test_macos.py::64": {"resolved_imports": ["src/mss/__init__.py", "src/mss/exception.py", "src/mss/darwin.py"], "used_names": ["ScreenShotError", "darwin", "mss", "platform", "pytest", "util"], "enclosing_function": "test_implementation", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 1746}, "src/tests/test_xcb.py::109": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["Mock", "finalize", "list_from_xcb"], "enclosing_function": "test_list_from_xcb_keeps_parent_alive_until_items_drop", "extracted_code": "# Source: src/mss/linux/xcbhelpers.py\ndef list_from_xcb(iterator_factory: Callable, next_func: Callable, parent: Structure | _Pointer) -> list:\n iterator = iterator_factory(parent)\n items: list = []\n while iterator.rem != 0:\n current = iterator.data.contents\n # Keep the parent reply alive until consumers drop this entry.\n depends_on(current, parent)\n items.append(current)\n next_func(iterator)\n return items", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 456}, "src/tests/test_get_pixels.py::31": {"resolved_imports": ["src/mss/base.py", "src/mss/exception.py"], "used_names": ["Callable", "MSSBase", "itertools"], "enclosing_function": "test_grab_part_of_screen", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 12022}, "src/tests/test_xcb.py::279": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["xcb"], "enclosing_function": "test_only_if_exists_returns_none_when_missing", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 0}, "src/tests/test_gnu_linux.py::297": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["linux", "mss"], "enclosing_function": "test_shm_available", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/linux/__init__.py\n - ``\"default\"`` or ``\"xshmgetimage\"`` (default): XCB-based backend\n using XShmGetImage with automatic fallback to XGetImage when MIT-SHM\n is unavailable; see :py:class:`mss.linux.xshmgetimage.MSS`.\n - ``\"xgetimage\"``: XCB-based backend using XGetImage;\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n\n is unavailable; see :py:class:`mss.linux.xshmgetimage.MSS`.\n - ``\"xgetimage\"``: XCB-based backend using XGetImage;\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n\n see :py:class:`mss.linux.xgetimage.MSS`.\n - ``\"xlib\"``: Legacy Xlib-based backend retained for environments\n without working XCB libraries; see :py:class:`mss.linux.xlib.MSS`.\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n variable :envvar:`DISPLAY`.\n :type display: str | bytes | None\n\n\n .. versionadded:: 10.2.0 Prior to this version, the\n :class:`mss.linux.xlib.MSS` implementation was the only available\n backend.\n\n :param display: Optional keyword argument. Specifies an X11 display\n string to connect to. The default is taken from the environment\n variable :envvar:`DISPLAY`.\n :type display: str | bytes | None\n :param kwargs: Additional keyword arguments passed to the backend class.\n :returns: An MSS backend implementation.\n\n\n\n .. versionadded:: 10.2.0 Prior to this version, this didn't exist:\n the :func:`mss.linux.MSS` was a class equivalent to the current\n :class:`mss.linux.xlib.MSS` implementation.\n \"\"\"\n backend = backend.lower()\n if backend == \"xlib\":\n from . import xlib # noqa: PLC0415\n\n return xlib.MSS(**kwargs)\n if backend == \"xgetimage\":\n from . import xgetimage # noqa: PLC0415", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 3942}, "src/tests/test_save.py::82": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase", "Path", "datetime"], "enclosing_function": "test_output_format_date_custom", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_xcb.py::258": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["pytest", "xcb"], "enclosing_function": "test_predefined_atom_skips_xcb", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 0}, "src/tests/test_gnu_linux.py::90": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["MSSBase", "ScreenShotError", "mss", "platform", "pytest"], "enclosing_function": "test_factory_systems", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 13771}, "src/tests/test_tools.py::173": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_descriptor_string_serial_overrides_integer", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/test_get_pixels.py::43": {"resolved_imports": ["src/mss/base.py", "src/mss/exception.py"], "used_names": ["ScreenShot", "ScreenShotError", "pytest"], "enclosing_function": "test_get_pixel", "extracted_code": "# Source: src/mss/base.py\nfrom typing import TYPE_CHECKING, Any\n\nfrom mss.exception import ScreenShotError\nfrom mss.screenshot import ScreenShot\nfrom mss.tools import to_png\n\nif TYPE_CHECKING: # pragma: nocover\n from collections.abc import Callable, Iterator\n\n from mss.models import Monitor, Monitors\n\n # Prior to 3.11, Python didn't have the Self type. typing_extensions does, but we don't want to depend on it.\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.screenshot import ScreenShot\nfrom mss.tools import to_png\n\nif TYPE_CHECKING: # pragma: nocover\n from collections.abc import Callable, Iterator\n\n from mss.models import Monitor, Monitors\n\n # Prior to 3.11, Python didn't have the Self type. typing_extensions does, but we don't want to depend on it.\n try:\n\n\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2992}, "src/tests/test_xcb.py::61": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["depends_on", "finalize"], "enclosing_function": "test_depends_on_defers_parent_teardown_until_child_collected", "extracted_code": "# Source: src/mss/linux/xcbhelpers.py\ndef depends_on(subobject: Any, superobject: Any) -> None:\n \"\"\"Make sure that superobject is not GC'd before subobject.\n\n In XCB, a structure often is allocated with additional trailing\n data following it, with special accessors to get pointers to that\n extra data.\n\n In ctypes, if you access a structure field, a pointer value, etc.,\n then the outer object won't be garbage collected until after the\n inner object. (This uses the ctypes _b_base_ mechanism.)\n\n However, when using the XCB accessor functions, you don't get that\n guarantee automatically. Once all references to the outer\n structure have dropped, then we will free the memory for it (the\n response structures XCB returns have to be freed by us), including\n the trailing data. If there are live references to the trailing\n data, then those will become invalid.\n\n To prevent this, we use depends_on to make sure that the\n outer structure is not released before all the references to the\n inner objects have been cleared.\n \"\"\"\n # The implementation is quite simple. We create a finalizer on the inner object, with a callback that references\n # the outer object. That ensures that there are live references to the outer object until the references to the\n # inner object have been gc'd. We can't just create a ref, though; it seems that their callbacks will only run if\n # the ref itself is still referenced. We need the extra machinery that finalize provides, which uses an internal\n # registry to keep the refs alive.\n finalize(subobject, id, superobject)", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 1631}, "src/tests/third_party/test_pil.py::24": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase", "Path", "itertools"], "enclosing_function": "test_pil", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_find_monitors.py::36": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase"], "enclosing_function": "test_dimensions", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_implementation.py::91": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["ScreenShotError", "mss", "platform", "pytest"], "enclosing_function": "test_factory_unknown_system", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 1746}, "src/tests/test_gnu_linux.py::168": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["ScreenShotError", "mss", "pytest"], "enclosing_function": "test_unsupported_depth", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 1746}, "src/tests/test_tools.py::133": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_manufacture_year_only", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/test_bgra_to_rgb.py::13": {"resolved_imports": ["src/mss/base.py"], "used_names": ["ScreenShot", "pytest"], "enclosing_function": "test_bad_length", "extracted_code": "# Source: src/mss/base.py\nfrom typing import TYPE_CHECKING, Any\n\nfrom mss.exception import ScreenShotError\nfrom mss.screenshot import ScreenShot\nfrom mss.tools import to_png\n\nif TYPE_CHECKING: # pragma: nocover\n from collections.abc import Callable, Iterator\n\n from mss.models import Monitor, Monitors\n\n # Prior to 3.11, Python didn't have the Self type. typing_extensions does, but we don't want to depend on it.\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.screenshot import ScreenShot\nfrom mss.tools import to_png\n\nif TYPE_CHECKING: # pragma: nocover\n from collections.abc import Callable, Iterator\n\n from mss.models import Monitor, Monitors\n\n # Prior to 3.11, Python didn't have the Self type. typing_extensions does, but we don't want to depend on it.\n try:\n\n\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 2348}, "src/tests/test_implementation.py::226": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["Mock", "patch", "pytest", "sys"], "enclosing_function": "test_entry_point_with_no_argument", "extracted_code": "", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 0}, "src/tests/test_gnu_linux.py::343": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["Any", "builtins", "mss", "pytest"], "enclosing_function": "test_exception_while_holding_memoryview", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 1102}, "src/tests/test_macos.py::42": {"resolved_imports": ["src/mss/__init__.py", "src/mss/exception.py", "src/mss/darwin.py"], "used_names": ["darwin", "mss"], "enclosing_function": "test_repr", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 1102}, "src/tests/test_macos.py::80": {"resolved_imports": ["src/mss/__init__.py", "src/mss/exception.py", "src/mss/darwin.py"], "used_names": ["darwin", "mss", "patch"], "enclosing_function": "test_scaling_on", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 1102}, "src/tests/test_tools.py::127": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_basic", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/third_party/test_pil.py::27": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase", "Path", "itertools"], "enclosing_function": "test_pil", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_primary_monitor.py::21": {"resolved_imports": ["src/mss/base.py"], "used_names": ["Callable", "MSSBase"], "enclosing_function": "test_primary_monitor", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 12022}, "src/tests/test_leaks.py::125": {"resolved_imports": ["src/mss/__init__.py"], "used_names": ["Callable", "pytest"], "enclosing_function": "test_resource_leaks", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 0}, "src/tests/test_gnu_linux.py::96": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["MSSBase", "ScreenShotError", "mss", "platform", "pytest"], "enclosing_function": "test_factory_systems", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 13771}, "src/tests/test_implementation.py::113": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": [], "enclosing_function": "_run_main", "extracted_code": "", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 0}, "src/tests/test_macos.py::84": {"resolved_imports": ["src/mss/__init__.py", "src/mss/exception.py", "src/mss/darwin.py"], "used_names": ["darwin", "mss", "patch"], "enclosing_function": "test_scaling_on", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 1102}, "src/tests/test_gnu_linux.py::106": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["ScreenShotError", "mss", "pytest"], "enclosing_function": "test_arg_display", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 1746}, "src/tests/test_implementation.py::250": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["MSSBase"], "enclosing_function": "test_grab_with_tuple", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 12022}, "src/tests/test_implementation.py::245": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["MSSBase"], "enclosing_function": "test_grab_with_tuple", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 12022}, "src/tests/test_implementation.py::196": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["pytest"], "enclosing_function": "test_invalid_backend_option", "extracted_code": "", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 0}, "src/tests/test_setup.py::29": {"resolved_imports": ["src/mss/__init__.py"], "used_names": ["STDOUT", "__version__", "check_call", "check_output", "tarfile"], "enclosing_function": "test_sdist", "extracted_code": "# Source: src/mss/__init__.py\n__version__ = \"10.2.0.dev0\"", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 57}, "src/tests/test_xcb.py::57": {"resolved_imports": ["src/mss/exception.py", "src/mss/linux/__init__.py", "src/mss/linux/base.py", "src/mss/linux/xcb.py", "src/mss/linux/xgetimage.py", "src/mss/linux/xcbhelpers.py"], "used_names": ["depends_on", "finalize"], "enclosing_function": "test_depends_on_defers_parent_teardown_until_child_collected", "extracted_code": "# Source: src/mss/linux/xcbhelpers.py\ndef depends_on(subobject: Any, superobject: Any) -> None:\n \"\"\"Make sure that superobject is not GC'd before subobject.\n\n In XCB, a structure often is allocated with additional trailing\n data following it, with special accessors to get pointers to that\n extra data.\n\n In ctypes, if you access a structure field, a pointer value, etc.,\n then the outer object won't be garbage collected until after the\n inner object. (This uses the ctypes _b_base_ mechanism.)\n\n However, when using the XCB accessor functions, you don't get that\n guarantee automatically. Once all references to the outer\n structure have dropped, then we will free the memory for it (the\n response structures XCB returns have to be freed by us), including\n the trailing data. If there are live references to the trailing\n data, then those will become invalid.\n\n To prevent this, we use depends_on to make sure that the\n outer structure is not released before all the references to the\n inner objects have been cleared.\n \"\"\"\n # The implementation is quite simple. We create a finalizer on the inner object, with a callback that references\n # the outer object. That ensures that there are live references to the outer object until the references to the\n # inner object have been gc'd. We can't just create a ref, though; it seems that their callbacks will only run if\n # the ref itself is still referenced. We need the extra machinery that finalize provides, which uses an internal\n # registry to keep the refs alive.\n finalize(subobject, id, superobject)", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 1631}, "src/tests/test_tools.py::163": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_descriptor_serial_number", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/test_implementation.py::223": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["Mock", "patch", "pytest", "sys"], "enclosing_function": "test_entry_point_with_no_argument", "extracted_code": "", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 0}, "src/tests/test_primary_monitor.py::45": {"resolved_imports": ["src/mss/base.py", "src/mss/__init__.py"], "used_names": ["mss", "platform", "pytest"], "enclosing_function": "test_primary_monitor_coordinates_windows", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1102}, "src/tests/test_macos.py::26": {"resolved_imports": ["src/mss/__init__.py", "src/mss/exception.py", "src/mss/darwin.py"], "used_names": ["darwin", "mss"], "enclosing_function": "test_repr", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 1102}, "src/tests/test_setup.py::28": {"resolved_imports": ["src/mss/__init__.py"], "used_names": ["STDOUT", "__version__", "check_call", "check_output", "tarfile"], "enclosing_function": "test_sdist", "extracted_code": "# Source: src/mss/__init__.py\n__version__ = \"10.2.0.dev0\"", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 57}, "src/tests/test_implementation.py::252": {"resolved_imports": ["src/mss/__init__.py", "src/mss/__main__.py", "src/mss/base.py", "src/mss/exception.py", "src/mss/screenshot.py"], "used_names": ["MSSBase"], "enclosing_function": "test_grab_with_tuple", "extracted_code": "# Source: src/mss/base.py\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n \"\"\"\n\n __slots__ = {\"_closed\", \"_lock\", \"_monitors\", \"cls_image\", \"compression_level\", \"with_cursor\"}\n\n def __init__(\n self,\n /,\n *,\n backend: str = \"default\",\n compression_level: int = 6,\n with_cursor: bool = False,\n # Linux only\n display: bytes | str | None = None, # noqa: ARG002\n # Mac only\n max_displays: int = 32, # noqa: ARG002\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n #: In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically\n #: change this to False when the object is created.\n #:\n #: This should not be changed after creating the object.\n #:\n #: .. versionadded:: 8.0.0\n self.with_cursor = with_cursor\n\n # The attributes below are protected by self._lock. The attributes above are user-visible, so we don't\n # control when they're modified. Currently, we only make sure that they're safe to modify while locked, or\n # document that the user shouldn't change them. We could also use properties protect them against changes, or\n # change them under the lock.\n self._lock = Lock()\n self._monitors: Monitors = []\n self._closed = False\n\n # If there isn't a factory that removed the \"backend\" argument, make sure that it was set to \"default\".\n # Factories that do backend-specific dispatch should remove that argument.\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n @abstractmethod\n def _cursor_impl(self) -> ScreenShot | None:\n \"\"\"Retrieve all cursor data. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _grab_impl(self, monitor: Monitor, /) -> ScreenShot:\n \"\"\"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n @abstractmethod\n def _monitors_impl(self) -> None:\n \"\"\"Get positions of monitors.\n\n It must populate self._monitors.\n\n The object lock will be held when this method is called.\n \"\"\"\n\n def _close_impl(self) -> None: # noqa:B027\n \"\"\"Clean up.\n\n This will be called at most once.\n\n The object lock will be held when this method is called.\n \"\"\"\n # It's not necessary for subclasses to implement this if they have nothing to clean up.\n\n def close(self) -> None:\n \"\"\"Clean up.\n\n This releases resources that MSS may be using. Once the MSS\n object is closed, it may not be used again.\n\n It is safe to call this multiple times; multiple calls have no\n effect.\n\n Rather than use :py:meth:`close` explicitly, we recommend you\n use the MSS object as a context manager::\n\n with mss.mss() as sct:\n ...\n \"\"\"\n with self._lock:\n if self._closed:\n return\n self._close_impl()\n self._closed = True\n\n def grab(self, monitor: Monitor | tuple[int, int, int, int], /) -> ScreenShot:\n \"\"\"Retrieve screen pixels for a given monitor.\n\n Note: ``monitor`` can be a tuple like the one\n :py:meth:`PIL.ImageGrab.grab` accepts: ``(left, top, right, bottom)``\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors ` for object details.\n :returns: Screenshot of the requested region.\n \"\"\"\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n if monitor[\"width\"] <= 0 or monitor[\"height\"] <= 0:\n msg = f\"Region has zero or negative size: {monitor!r}\"\n raise ScreenShotError(msg)\n\n with self._lock:\n screenshot = self._grab_impl(monitor)\n if self.with_cursor and (cursor := self._cursor_impl()):\n return self._merge(screenshot, cursor)\n return screenshot\n\n @property\n def monitors(self) -> Monitors:\n \"\"\"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill ``self._monitors`` with all information\n and use it as a cache:\n\n - ``self._monitors[0]`` is a dict of all monitors together\n - ``self._monitors[N]`` is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n\n - ``left``: the x-coordinate of the upper-left corner\n - ``top``: the y-coordinate of the upper-left corner\n - ``width``: the width\n - ``height``: the height\n - ``is_primary``: (optional) true if this is the primary monitor\n - ``name``: (optional) human-readable device name\n - ``unique_id``: (optional) platform-specific stable identifier for the monitor\n - ``output``: (optional, Linux only) monitor output name, compatible with xrandr\n \"\"\"\n with self._lock:\n if not self._monitors:\n self._monitors_impl()\n return self._monitors\n\n @property\n def primary_monitor(self) -> Monitor:\n \"\"\"Get the primary monitor.\n\n Returns the monitor marked as primary. If no monitor is marked as primary\n (or the platform doesn't support primary monitor detection), returns the\n first monitor (at index 1).\n\n :raises ScreenShotError: If no monitors are available.\n\n .. versionadded:: 10.2.0\n \"\"\"\n monitors = self.monitors\n if len(monitors) <= 1: # Only the \"all monitors\" entry or empty\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n for monitor in monitors[1:]: # Skip the \"all monitors\" entry at index 0\n if monitor.get(\"is_primary\", False):\n return monitor\n # Fallback to the first monitor if no primary is found\n return monitors[1]\n\n def save(\n self,\n /,\n *,\n mon: int = 0,\n output: str = \"monitor-{mon}.png\",\n callback: Callable[[str], None] | None = None,\n ) -> Iterator[str]:\n \"\"\"Grab a screenshot and save it to a file.\n\n :param int mon: The monitor to screenshot (default=0). ``-1`` grabs all\n monitors, ``0`` grabs each monitor, and ``N`` grabs monitor ``N``.\n :param str output: The output filename. Keywords: ``{mon}``, ``{top}``,\n ``{left}``, ``{width}``, ``{height}``, ``{date}``.\n :param callable callback: Called before saving the screenshot; receives\n the ``output`` argument.\n :return: Created file(s).\n \"\"\"\n monitors = self.monitors\n if not monitors:\n msg = \"No monitor found.\"\n raise ScreenShotError(msg)\n\n if mon == 0:\n # One screenshot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screenshot of all monitors together or\n # a screenshot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError as exc:\n msg = f\"Monitor {mon!r} does not exist.\"\n raise ScreenShotError(msg) from exc\n\n output = output.format(mon=mon, date=datetime.now(UTC) if \"{date\" in output else None, **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output\n\n def shot(self, /, **kwargs: Any) -> str:\n \"\"\"Helper to save the screenshot of the 1st monitor, by default.\n You can pass the same arguments as for :meth:`save`.\n \"\"\"\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))\n\n @staticmethod\n def _merge(screenshot: ScreenShot, cursor: ScreenShot, /) -> ScreenShot:\n \"\"\"Create composite image by blending screenshot and mouse cursor.\n\n The cursor image should be in straight (not premultiplied) alpha.\n \"\"\"\n (cx, cy), (cw, ch) = cursor.pos, cursor.size\n (x, y), (w, h) = screenshot.pos, screenshot.size\n\n cx2, cy2 = cx + cw, cy + ch\n x2, y2 = x + w, y + h\n\n overlap = cx < x2 and cx2 > x and cy < y2 and cy2 > y\n if not overlap:\n return screenshot\n\n screen_raw = screenshot.raw\n cursor_raw = cursor.raw\n\n cy, cy2 = (cy - y) * 4, (cy2 - y2) * 4\n cx, cx2 = (cx - x) * 4, (cx2 - x2) * 4\n start_count_y = -cy if cy < 0 else 0\n start_count_x = -cx if cx < 0 else 0\n stop_count_y = ch * 4 - max(cy2, 0)\n stop_count_x = cw * 4 - max(cx2, 0)\n rgb = range(3)\n\n for count_y in range(start_count_y, stop_count_y, 4):\n pos_s = (count_y + cy) * w + cx\n pos_c = count_y * cw\n\n for count_x in range(start_count_x, stop_count_x, 4):\n spos = pos_s + count_x\n cpos = pos_c + count_x\n alpha = cursor_raw[cpos + 3]\n\n if not alpha:\n continue\n\n if alpha == OPAQUE:\n screen_raw[spos : spos + 3] = cursor_raw[cpos : cpos + 3]\n else:\n alpha2 = alpha / 255\n for i in rgb:\n screen_raw[spos + i] = int(cursor_raw[cpos + i] * alpha2 + screen_raw[spos + i] * (1 - alpha2))\n\n return screenshot\n\n @staticmethod\n def _cfactory(\n attr: Any,\n func: str,\n argtypes: list[Any],\n restype: Any,\n /,\n errcheck: Callable | None = None,\n ) -> None:\n \"\"\"Factory to create a ctypes function and automatically manage errors.\"\"\"\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 12022}, "src/tests/test_macos.py::51": {"resolved_imports": ["src/mss/__init__.py", "src/mss/exception.py", "src/mss/darwin.py"], "used_names": ["ScreenShotError", "darwin", "mss", "platform", "pytest", "util"], "enclosing_function": "test_implementation", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 1746}, "src/tests/test_gnu_linux.py::160": {"resolved_imports": ["src/mss/__init__.py", "src/mss/linux/__init__.py", "src/mss/linux/xcb.py", "src/mss/linux/xlib.py", "src/mss/base.py", "src/mss/exception.py"], "used_names": ["ScreenShotError", "mss", "pytest"], "enclosing_function": "test_unsupported_depth", "extracted_code": "# Source: src/mss/__init__.py\n#\n# You can always get the latest version of this module at:\n# https://github.com/BoboTiG/python-mss\n# If that URL should fail, try contacting the author.\n\"\"\"An ultra fast cross-platform multiple screenshots module in pure python\nusing ctypes.\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n\n\"\"\"\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.factory import mss\n\n__version__ = \"10.2.0.dev0\"\n__author__ = \"Mickaël Schoentgen\"\n__date__ = \"2013-2025\"\n__copyright__ = f\"\"\"\nCopyright (c) {__date__}, {__author__}\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee or royalty is hereby\n\nmodifications, that you make.\n\"\"\"\n__all__ = (\"ScreenShotError\", \"mss\")\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 14, "n_files_resolved": 6, "n_chars_extracted": 1746}, "src/tests/test_tools.py::109": {"resolved_imports": ["src/mss/tools.py"], "used_names": ["parse_edid"], "enclosing_function": "test_parse_edid_too_short", "extracted_code": "# Source: src/mss/tools.py\ndef parse_edid(edid_data: bytes) -> dict:\n \"\"\"Parse a monitor's EDID block.\n\n Many fields are currently ignored, but may be added in the future.\n\n If the EDID block cannot be parsed, this returns an empty dict.\n\n The dict defines the following fields. Any of these may be\n missing, if the EDID block does not define them.\n\n - id_legacy (str): The legacy monitor ID, used in a number of\n APIs. This is simply f\"{manufacturer}{product_code:04X}\".\n Those subfields are not part of the returned dict, but are\n nominally described as:\n\n - manufacturer (str): A three-letter, all-uppercase code\n specifying the manufacturer's legacy PnP ID. The registry is\n managed by UEFI forum.\n - product_code (int): A 16-bit product code. This is typically\n displayed as four hex digits if rendered to a string.\n\n - serial_number (str | int): Serial number of the monitor. EDID\n block may provide this as an int, string, or both; the string\n version is preferred.\n - manufacture_week (int): The week, 1-54, of manufacture. This\n may not be populated, even if the year is. (The way the weeks\n are numbered is up to the manufacturer.)\n - manufacture_year (int): The year, 1990 or later, of manufacture.\n - model_year (int): The year, 1990 or later, that the model was\n released. This is used if the manufacturer doesn't want to\n update their EDID block each year; the manufacture_year field is\n more common.\n - display_name (str): The monitor's model. This is the preferred\n value for display. If this field is not present, then id_legacy\n is a distant second.\n\n Currently, the serial_number and name fields are always in ASCII.\n This function doesn't currently try to implement the\n internationalization extensions defined in the VESA LS-EXT\n standard. However, we may in the future.\n\n We also don't currently inspect the extension blocks. The name\n and serial number can be in CTA-861 extension blocks; I'll need to\n see how common that is.\n \"\"\"\n # See also https://glenwing.github.io/docs/ for a lot of the relevant specs.\n\n if len(edid_data) < _EDID_BLOCK_LEN:\n # Too short\n return {}\n\n # Get the basic identification information from the start of the\n # header. This has been part of EDID for a very long time.\n block0 = edid_data[:_EDID_BLOCK_LEN]\n if sum(block0) % 256 != 0:\n # Checksum failure\n return {}\n\n (\n header,\n id_manufacturer_msb,\n id_manufacturer_lsb,\n id_product_code,\n id_serial_number,\n manufacture_week,\n manufacture_year,\n _edid_version,\n _edid_revision,\n _ext_count,\n ) = struct.unpack(\"<8s2BHIBBBB106xBx\", block0)\n\n if header != b\"\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\x00\":\n # Header incorrect\n return {}\n id_manufacturer_packed = id_manufacturer_msb << 8 | id_manufacturer_lsb\n id_manufacturer = (\n chr(((id_manufacturer_packed >> 10) % 32) + 64)\n + chr(((id_manufacturer_packed >> 5) % 32) + 64)\n + chr((id_manufacturer_packed % 32) + 64)\n )\n rv: dict[str, int | str] = {\n \"id_legacy\": f\"{id_manufacturer}{id_product_code:04X}\",\n }\n if id_serial_number != _EDID_SERIAL_NUMBER_NOT_SET:\n rv[\"serial_number\"] = id_serial_number\n if manufacture_week == _EDID_MANUFACTURE_WEEK_YEAR_IS_MODEL:\n rv[\"model_year\"] = manufacture_year + _EDID_YEAR_BASE\n else:\n if manufacture_week != _EDID_MANUFACTURE_WEEK_UNKNOWN:\n rv[\"manufacture_week\"] = manufacture_week\n rv[\"manufacture_year\"] = manufacture_year + _EDID_YEAR_BASE\n\n # Read the display descriptor definitions, which can have more useful information.\n for descr_offset in _EDID_DESCR_OFFSETS:\n descr = block0[descr_offset : descr_offset + _EDID_DESCR_LEN]\n if any(descr[field_offset] != 0 for field_offset in _EDID_DESCR_ZERO_LOCS):\n # Not a display descriptor definition\n continue\n # Check the tag in descr[3].\n # These strings are in ASCII, optionally terminated by \\x0A then right-padded with \\x20. In case a\n # manufacturer got it a little wrong, we ignore everything after \\x0A, and we also strip trailing \\x20. (The\n # spec requires the \\x0A, but some manufacturers don't follow that.)\n if descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_SN: # Serial number\n sn = descr[_EDID_DESCR_STR_LOC]\n sn, _, _ = sn.partition(b\"\\x0a\")\n sn = sn.rstrip(b\" \")\n rv[\"serial_number\"] = sn.decode(\"ascii\", errors=\"replace\")\n elif descr[_EDID_DESCR_TAG_LOC] == _EDID_DESCR_TAG_NAME: # Name\n name = descr[_EDID_DESCR_STR_LOC]\n name, _, _ = name.partition(b\"\\x0a\")\n name = name.rstrip(b\" \")\n rv[\"display_name\"] = name.decode(\"ascii\", errors=\"replace\")\n\n return rv", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 4986}, "src/tests/test_get_pixels.py::37": {"resolved_imports": ["src/mss/base.py", "src/mss/exception.py"], "used_names": ["ScreenShot", "ScreenShotError", "pytest"], "enclosing_function": "test_get_pixel", "extracted_code": "# Source: src/mss/base.py\nfrom typing import TYPE_CHECKING, Any\n\nfrom mss.exception import ScreenShotError\nfrom mss.screenshot import ScreenShot\nfrom mss.tools import to_png\n\nif TYPE_CHECKING: # pragma: nocover\n from collections.abc import Callable, Iterator\n\n from mss.models import Monitor, Monitors\n\n # Prior to 3.11, Python didn't have the Self type. typing_extensions does, but we don't want to depend on it.\n\n\nfrom mss.exception import ScreenShotError\nfrom mss.screenshot import ScreenShot\nfrom mss.tools import to_png\n\nif TYPE_CHECKING: # pragma: nocover\n from collections.abc import Callable, Iterator\n\n from mss.models import Monitor, Monitors\n\n # Prior to 3.11, Python didn't have the Self type. typing_extensions does, but we don't want to depend on it.\n try:\n\n\nclass MSSBase(metaclass=ABCMeta):\n \"\"\"Base class for all Multiple ScreenShots implementations.\n\n :param backend: Backend selector, for platforms with multiple backends.\n :param compression_level: PNG compression level.\n :param with_cursor: Include the mouse cursor in screenshots.\n :param display: X11 display name (GNU/Linux only).\n :param max_displays: Maximum number of displays to enumerate (macOS only).\n\n .. versionadded:: 8.0.0\n ``compression_level``, ``display``, ``max_displays``, and ``with_cursor`` keyword arguments.\n\n ) -> None:\n # The cls_image is only used atomically, so does not require locking.\n self.cls_image: type[ScreenShot] = ScreenShot\n # The compression level is only used atomically, so does not require locking.\n #: PNG compression level used when saving the screenshot data into a file\n #: (see :py:func:`zlib.compress()` for details).\n #:\n #: .. versionadded:: 3.2.0\n self.compression_level = compression_level\n # The with_cursor attribute is not meant to be changed after initialization.\n #: Include the mouse cursor in screenshots.\n #:\n\n if backend != \"default\":\n msg = 'The only valid backend on this platform is \"default\".'\n raise ScreenShotError(msg)\n\n def __enter__(self) -> Self:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n return self\n\n def __exit__(self, *_: object) -> None:\n \"\"\"For the cool call `with MSS() as mss:`.\"\"\"\n self.close()\n\n\n\n# Source: src/mss/exception.py\nclass ScreenShotError(Exception):\n \"\"\"Error handling class.\"\"\"\n\n def __init__(self, message: str, /, *, details: dict[str, Any] | None = None) -> None:\n super().__init__(message)\n #: On GNU/Linux, and if the error comes from the XServer, it contains XError details.\n #: This is an empty dict by default.\n #:\n #: For XErrors, you can find information on\n #: `Using the Default Error Handlers `_.\n #:\n #: .. versionadded:: 3.3.0\n self.details = details or {}", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2992}}}