File size: 98,863 Bytes
3a7f06a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS.__init__","parameters":"(self, **_)","argument_list":"","return_statement":"","docstring":"Windows initialisations.","docstring_summary":"Windows initialisations.","docstring_tokens":["Windows","initialisations","."],"function":"def __init__(self, **_):\n        # type: (Any) -> None\n        \"\"\" Windows initialisations. \"\"\"\n\n        super().__init__()\n\n        self.user32 = ctypes.WinDLL(\"user32\")\n        self.gdi32 = ctypes.WinDLL(\"gdi32\")\n        self._set_cfunctions()\n        self._set_dpi_awareness()\n\n        self._bbox = {\"height\": 0, \"width\": 0}\n        self._data = ctypes.create_string_buffer(0)  # type: ctypes.Array[ctypes.c_char]\n\n        srcdc = self._get_srcdc()\n        if not MSS.memdc:\n            MSS.memdc = self.gdi32.CreateCompatibleDC(srcdc)\n\n        bmi = BITMAPINFO()\n        bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)\n        bmi.bmiHeader.biPlanes = 1  # Always 1\n        bmi.bmiHeader.biBitCount = 32  # See grab.__doc__ [2]\n        bmi.bmiHeader.biCompression = 0  # 0 = BI_RGB (no compression)\n        bmi.bmiHeader.biClrUsed = 0  # See grab.__doc__ [3]\n        bmi.bmiHeader.biClrImportant = 0  # See grab.__doc__ [3]\n        self._bmi = bmi","function_tokens":["def","__init__","(","self",",","*","*","_",")",":","# type: (Any) -> None","super","(",")",".","__init__","(",")","self",".","user32","=","ctypes",".","WinDLL","(","\"user32\"",")","self",".","gdi32","=","ctypes",".","WinDLL","(","\"gdi32\"",")","self",".","_set_cfunctions","(",")","self",".","_set_dpi_awareness","(",")","self",".","_bbox","=","{","\"height\"",":","0",",","\"width\"",":","0","}","self",".","_data","=","ctypes",".","create_string_buffer","(","0",")","# type: ctypes.Array[ctypes.c_char]","srcdc","=","self",".","_get_srcdc","(",")","if","not","MSS",".","memdc",":","MSS",".","memdc","=","self",".","gdi32",".","CreateCompatibleDC","(","srcdc",")","bmi","=","BITMAPINFO","(",")","bmi",".","bmiHeader",".","biSize","=","ctypes",".","sizeof","(","BITMAPINFOHEADER",")","bmi",".","bmiHeader",".","biPlanes","=","1","# Always 1","bmi",".","bmiHeader",".","biBitCount","=","32","# See grab.__doc__ [2]","bmi",".","bmiHeader",".","biCompression","=","0","# 0 = BI_RGB (no compression)","bmi",".","bmiHeader",".","biClrUsed","=","0","# See grab.__doc__ [3]","bmi",".","bmiHeader",".","biClrImportant","=","0","# See grab.__doc__ [3]","self",".","_bmi","=","bmi"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L111-L136"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._set_cfunctions","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set all ctypes functions and attach them to attributes.","docstring_summary":"Set all ctypes functions and attach them to attributes.","docstring_tokens":["Set","all","ctypes","functions","and","attach","them","to","attributes","."],"function":"def _set_cfunctions(self):\n        \"\"\" Set all ctypes functions and attach them to attributes. \"\"\"\n\n        cfactory = self._cfactory\n        attrs = {\n            \"gdi32\": self.gdi32,\n            \"user32\": self.user32,\n        }\n        for func, (attr, argtypes, restype) in CFUNCTIONS.items():\n            cfactory(\n                attr=attrs[attr],\n                func=func,\n                argtypes=argtypes,\n                restype=restype,\n            )","function_tokens":["def","_set_cfunctions","(","self",")",":","cfactory","=","self",".","_cfactory","attrs","=","{","\"gdi32\"",":","self",".","gdi32",",","\"user32\"",":","self",".","user32",",","}","for","func",",","(","attr",",","argtypes",",","restype",")","in","CFUNCTIONS",".","items","(",")",":","cfactory","(","attr","=","attrs","[","attr","]",",","func","=","func",",","argtypes","=","argtypes",",","restype","=","restype",",",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L138-L152"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._set_dpi_awareness","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set DPI awareness to capture full screen on Hi-DPI monitors.","docstring_summary":"Set DPI awareness to capture full screen on Hi-DPI monitors.","docstring_tokens":["Set","DPI","awareness","to","capture","full","screen","on","Hi","-","DPI","monitors","."],"function":"def _set_dpi_awareness(self):\n        \"\"\" Set DPI awareness to capture full screen on Hi-DPI monitors. \"\"\"\n\n        version = sys.getwindowsversion()[:2]  # pylint: disable=no-member\n        if version >= (6, 3):\n            # Windows 8.1+\n            # Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:\n            #     per monitor DPI aware. This app checks for the DPI when it is\n            #     created and adjusts the scale factor whenever the DPI changes.\n            #     These applications are not automatically scaled by the system.\n            ctypes.windll.shcore.SetProcessDpiAwareness(2)\n        elif (6, 0) <= version < (6, 3):\n            # Windows Vista, 7, 8 and Server 2012\n            self.user32.SetProcessDPIAware()","function_tokens":["def","_set_dpi_awareness","(","self",")",":","version","=","sys",".","getwindowsversion","(",")","[",":","2","]","# pylint: disable=no-member","if","version",">=","(","6",",","3",")",":","# Windows 8.1+","# Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:","#     per monitor DPI aware. This app checks for the DPI when it is","#     created and adjusts the scale factor whenever the DPI changes.","#     These applications are not automatically scaled by the system.","ctypes",".","windll",".","shcore",".","SetProcessDpiAwareness","(","2",")","elif","(","6",",","0",")","<=","version","<","(","6",",","3",")",":","# Windows Vista, 7, 8 and Server 2012","self",".","user32",".","SetProcessDPIAware","(",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L154-L167"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._get_srcdc","parameters":"(self)","argument_list":"","return_statement":"return srcdc","docstring":"Retrieve a thread-safe HDC from GetWindowDC().\n        In multithreading, if the thread that creates *srcdc* is dead, *srcdc* will\n        no longer be valid to grab the screen. The *srcdc* attribute is replaced\n        with *_srcdc_dict* to maintain the *srcdc* values in multithreading.\n        Since the current thread and main thread are always alive, reuse their *srcdc* value first.","docstring_summary":"Retrieve a thread-safe HDC from GetWindowDC().\n        In multithreading, if the thread that creates *srcdc* is dead, *srcdc* will\n        no longer be valid to grab the screen. The *srcdc* attribute is replaced\n        with *_srcdc_dict* to maintain the *srcdc* values in multithreading.\n        Since the current thread and main thread are always alive, reuse their *srcdc* value first.","docstring_tokens":["Retrieve","a","thread","-","safe","HDC","from","GetWindowDC","()",".","In","multithreading","if","the","thread","that","creates","*","srcdc","*","is","dead","*","srcdc","*","will","no","longer","be","valid","to","grab","the","screen",".","The","*","srcdc","*","attribute","is","replaced","with","*","_srcdc_dict","*","to","maintain","the","*","srcdc","*","values","in","multithreading",".","Since","the","current","thread","and","main","thread","are","always","alive","reuse","their","*","srcdc","*","value","first","."],"function":"def _get_srcdc(self):\n        \"\"\"\n        Retrieve a thread-safe HDC from GetWindowDC().\n        In multithreading, if the thread that creates *srcdc* is dead, *srcdc* will\n        no longer be valid to grab the screen. The *srcdc* attribute is replaced\n        with *_srcdc_dict* to maintain the *srcdc* values in multithreading.\n        Since the current thread and main thread are always alive, reuse their *srcdc* value first.\n        \"\"\"\n        cur_thread, main_thread = threading.current_thread(), threading.main_thread()\n        srcdc = MSS._srcdc_dict.get(cur_thread) or MSS._srcdc_dict.get(main_thread)\n        if not srcdc:\n            srcdc = MSS._srcdc_dict[cur_thread] = self.user32.GetWindowDC(0)\n        return srcdc","function_tokens":["def","_get_srcdc","(","self",")",":","cur_thread",",","main_thread","=","threading",".","current_thread","(",")",",","threading",".","main_thread","(",")","srcdc","=","MSS",".","_srcdc_dict",".","get","(","cur_thread",")","or","MSS",".","_srcdc_dict",".","get","(","main_thread",")","if","not","srcdc",":","srcdc","=","MSS",".","_srcdc_dict","[","cur_thread","]","=","self",".","user32",".","GetWindowDC","(","0",")","return","srcdc"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L169-L181"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._monitors_impl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get positions of monitors. It will populate self._monitors.","docstring_summary":"Get positions of monitors. It will populate self._monitors.","docstring_tokens":["Get","positions","of","monitors",".","It","will","populate","self",".","_monitors","."],"function":"def _monitors_impl(self):\n        # type: () -> None\n        \"\"\" Get positions of monitors. It will populate self._monitors. \"\"\"\n\n        int_ = int\n        user32 = self.user32\n        get_system_metrics = user32.GetSystemMetrics\n\n        # All monitors\n        self._monitors.append(\n            {\n                \"left\": int_(get_system_metrics(76)),  # SM_XVIRTUALSCREEN\n                \"top\": int_(get_system_metrics(77)),  # SM_YVIRTUALSCREEN\n                \"width\": int_(get_system_metrics(78)),  # SM_CXVIRTUALSCREEN\n                \"height\": int_(get_system_metrics(79)),  # SM_CYVIRTUALSCREEN\n            }\n        )\n\n        # Each monitor\n        def _callback(monitor, data, rect, dc_):\n            # types: (int, HDC, LPRECT, LPARAM) -> int\n            \"\"\"\n            Callback for monitorenumproc() function, it will return\n            a RECT with appropriate values.\n            \"\"\"\n            # pylint: disable=unused-argument\n\n            rct = rect.contents\n            self._monitors.append(\n                {\n                    \"left\": int_(rct.left),\n                    \"top\": int_(rct.top),\n                    \"width\": int_(rct.right - rct.left),\n                    \"height\": int_(rct.bottom - rct.top),\n                }\n            )\n            return 1\n\n        callback = MONITORNUMPROC(_callback)\n        user32.EnumDisplayMonitors(0, 0, callback, 0)","function_tokens":["def","_monitors_impl","(","self",")",":","# type: () -> None","int_","=","int","user32","=","self",".","user32","get_system_metrics","=","user32",".","GetSystemMetrics","# All monitors","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","get_system_metrics","(","76",")",")",",","# SM_XVIRTUALSCREEN","\"top\"",":","int_","(","get_system_metrics","(","77",")",")",",","# SM_YVIRTUALSCREEN","\"width\"",":","int_","(","get_system_metrics","(","78",")",")",",","# SM_CXVIRTUALSCREEN","\"height\"",":","int_","(","get_system_metrics","(","79",")",")",",","# SM_CYVIRTUALSCREEN","}",")","# Each monitor","def","_callback","(","monitor",",","data",",","rect",",","dc_",")",":","# types: (int, HDC, LPRECT, LPARAM) -> int","\"\"\"\n            Callback for monitorenumproc() function, it will return\n            a RECT with appropriate values.\n            \"\"\"","# pylint: disable=unused-argument","rct","=","rect",".","contents","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","rct",".","left",")",",","\"top\"",":","int_","(","rct",".","top",")",",","\"width\"",":","int_","(","rct",".","right","-","rct",".","left",")",",","\"height\"",":","int_","(","rct",".","bottom","-","rct",".","top",")",",","}",")","return","1","callback","=","MONITORNUMPROC","(","_callback",")","user32",".","EnumDisplayMonitors","(","0",",","0",",","callback",",","0",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L183-L222"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._grab_impl","parameters":"(self, monitor)","argument_list":"","return_statement":"return self.cls_image(bytearray(self._data), monitor)","docstring":"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n        In the code, there are a few interesting things:\n\n        [1] bmi.bmiHeader.biHeight = -height\n\n        A bottom-up DIB is specified by setting the height to a\n        positive number, while a top-down DIB is specified by\n        setting the height to a negative number.\n        https:\/\/msdn.microsoft.com\/en-us\/library\/ms787796.aspx\n        https:\/\/msdn.microsoft.com\/en-us\/library\/dd144879%28v=vs.85%29.aspx\n\n\n        [2] bmi.bmiHeader.biBitCount = 32\n            image_data = create_string_buffer(height * width * 4)\n\n        We grab the image in RGBX mode, so that each word is 32bit\n        and we have no striding.\n        Inspired by https:\/\/github.com\/zoofIO\/flexx\n\n\n        [3] bmi.bmiHeader.biClrUsed = 0\n            bmi.bmiHeader.biClrImportant = 0\n\n        When biClrUsed and biClrImportant are set to zero, there\n        is \"no\" color table, so we can read the pixels of the bitmap\n        retrieved by gdi32.GetDIBits() as a sequence of RGB values.\n        Thanks to http:\/\/stackoverflow.com\/a\/3688682","docstring_summary":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_tokens":["Retrieve","all","pixels","from","a","monitor",".","Pixels","have","to","be","RGB","."],"function":"def _grab_impl(self, monitor):\n        # type: (Monitor) -> ScreenShot\n        \"\"\"\n        Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n        In the code, there are a few interesting things:\n\n        [1] bmi.bmiHeader.biHeight = -height\n\n        A bottom-up DIB is specified by setting the height to a\n        positive number, while a top-down DIB is specified by\n        setting the height to a negative number.\n        https:\/\/msdn.microsoft.com\/en-us\/library\/ms787796.aspx\n        https:\/\/msdn.microsoft.com\/en-us\/library\/dd144879%28v=vs.85%29.aspx\n\n\n        [2] bmi.bmiHeader.biBitCount = 32\n            image_data = create_string_buffer(height * width * 4)\n\n        We grab the image in RGBX mode, so that each word is 32bit\n        and we have no striding.\n        Inspired by https:\/\/github.com\/zoofIO\/flexx\n\n\n        [3] bmi.bmiHeader.biClrUsed = 0\n            bmi.bmiHeader.biClrImportant = 0\n\n        When biClrUsed and biClrImportant are set to zero, there\n        is \"no\" color table, so we can read the pixels of the bitmap\n        retrieved by gdi32.GetDIBits() as a sequence of RGB values.\n        Thanks to http:\/\/stackoverflow.com\/a\/3688682\n        \"\"\"\n\n        srcdc, memdc = self._get_srcdc(), MSS.memdc\n        width, height = monitor[\"width\"], monitor[\"height\"]\n\n        if (self._bbox[\"height\"], self._bbox[\"width\"]) != (height, width):\n            self._bbox = monitor\n            self._bmi.bmiHeader.biWidth = width\n            self._bmi.bmiHeader.biHeight = -height  # Why minus? [1]\n            self._data = ctypes.create_string_buffer(width * height * 4)  # [2]\n            if MSS.bmp:\n                self.gdi32.DeleteObject(MSS.bmp)\n            MSS.bmp = self.gdi32.CreateCompatibleBitmap(srcdc, width, height)\n            self.gdi32.SelectObject(memdc, MSS.bmp)\n\n        self.gdi32.BitBlt(\n            memdc,\n            0,\n            0,\n            width,\n            height,\n            srcdc,\n            monitor[\"left\"],\n            monitor[\"top\"],\n            SRCCOPY | CAPTUREBLT,\n        )\n        bits = self.gdi32.GetDIBits(\n            memdc, MSS.bmp, 0, height, self._data, self._bmi, DIB_RGB_COLORS\n        )\n        if bits != height:\n            raise ScreenShotError(\"gdi32.GetDIBits() failed.\")\n\n        return self.cls_image(bytearray(self._data), monitor)","function_tokens":["def","_grab_impl","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot","srcdc",",","memdc","=","self",".","_get_srcdc","(",")",",","MSS",".","memdc","width",",","height","=","monitor","[","\"width\"","]",",","monitor","[","\"height\"","]","if","(","self",".","_bbox","[","\"height\"","]",",","self",".","_bbox","[","\"width\"","]",")","!=","(","height",",","width",")",":","self",".","_bbox","=","monitor","self",".","_bmi",".","bmiHeader",".","biWidth","=","width","self",".","_bmi",".","bmiHeader",".","biHeight","=","-","height","# Why minus? [1]","self",".","_data","=","ctypes",".","create_string_buffer","(","width","*","height","*","4",")","# [2]","if","MSS",".","bmp",":","self",".","gdi32",".","DeleteObject","(","MSS",".","bmp",")","MSS",".","bmp","=","self",".","gdi32",".","CreateCompatibleBitmap","(","srcdc",",","width",",","height",")","self",".","gdi32",".","SelectObject","(","memdc",",","MSS",".","bmp",")","self",".","gdi32",".","BitBlt","(","memdc",",","0",",","0",",","width",",","height",",","srcdc",",","monitor","[","\"left\"","]",",","monitor","[","\"top\"","]",",","SRCCOPY","|","CAPTUREBLT",",",")","bits","=","self",".","gdi32",".","GetDIBits","(","memdc",",","MSS",".","bmp",",","0",",","height",",","self",".","_data",",","self",".","_bmi",",","DIB_RGB_COLORS",")","if","bits","!=","height",":","raise","ScreenShotError","(","\"gdi32.GetDIBits() failed.\"",")","return","self",".","cls_image","(","bytearray","(","self",".","_data",")",",","monitor",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L224-L287"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.__array_interface__","parameters":"(self)","argument_list":"","return_statement":"return {\n            \"version\": 3,\n            \"shape\": (self.height, self.width, 4),\n            \"typestr\": \"|u1\",\n            \"data\": self.raw,\n        }","docstring":"Numpy array interface support.\n        It uses raw data in BGRA form.\n\n        See https:\/\/docs.scipy.org\/doc\/numpy\/reference\/arrays.interface.html","docstring_summary":"Numpy array interface support.\n        It uses raw data in BGRA form.","docstring_tokens":["Numpy","array","interface","support",".","It","uses","raw","data","in","BGRA","form","."],"function":"def __array_interface__(self):\n        # type: () -> Dict[str, Any]\n        \"\"\"\n        Numpy array interface support.\n        It uses raw data in BGRA form.\n\n        See https:\/\/docs.scipy.org\/doc\/numpy\/reference\/arrays.interface.html\n        \"\"\"\n\n        return {\n            \"version\": 3,\n            \"shape\": (self.height, self.width, 4),\n            \"typestr\": \"|u1\",\n            \"data\": self.raw,\n        }","function_tokens":["def","__array_interface__","(","self",")",":","# type: () -> Dict[str, Any]","return","{","\"version\"",":","3",",","\"shape\"",":","(","self",".","height",",","self",".","width",",","4",")",",","\"typestr\"",":","\"|u1\"",",","\"data\"",":","self",".","raw",",","}"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L54-L68"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.from_size","parameters":"(cls, data, width, height)","argument_list":"","return_statement":"return cls(data, monitor)","docstring":"Instantiate a new class given only screen shot's data and size.","docstring_summary":"Instantiate a new class given only screen shot's data and size.","docstring_tokens":["Instantiate","a","new","class","given","only","screen","shot","s","data","and","size","."],"function":"def from_size(cls, data, width, height):\n        # type: (bytearray, int, int) -> ScreenShot\n        \"\"\" Instantiate a new class given only screen shot's data and size. \"\"\"\n\n        monitor = {\"left\": 0, \"top\": 0, \"width\": width, \"height\": height}\n        return cls(data, monitor)","function_tokens":["def","from_size","(","cls",",","data",",","width",",","height",")",":","# type: (bytearray, int, int) -> ScreenShot","monitor","=","{","\"left\"",":","0",",","\"top\"",":","0",",","\"width\"",":","width",",","\"height\"",":","height","}","return","cls","(","data",",","monitor",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L71-L76"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.bgra","parameters":"(self)","argument_list":"","return_statement":"return bytes(self.raw)","docstring":"BGRA values from the BGRA raw pixels.","docstring_summary":"BGRA values from the BGRA raw pixels.","docstring_tokens":["BGRA","values","from","the","BGRA","raw","pixels","."],"function":"def bgra(self):\n        # type: () -> bytes\n        \"\"\" BGRA values from the BGRA raw pixels. \"\"\"\n        return bytes(self.raw)","function_tokens":["def","bgra","(","self",")",":","# type: () -> bytes","return","bytes","(","self",".","raw",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L79-L82"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.height","parameters":"(self)","argument_list":"","return_statement":"return self.size.height","docstring":"Convenient accessor to the height size.","docstring_summary":"Convenient accessor to the height size.","docstring_tokens":["Convenient","accessor","to","the","height","size","."],"function":"def height(self):\n        # type: () -> int\n        \"\"\" Convenient accessor to the height size. \"\"\"\n        return self.size.height","function_tokens":["def","height","(","self",")",":","# type: () -> int","return","self",".","size",".","height"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L85-L88"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.left","parameters":"(self)","argument_list":"","return_statement":"return self.pos.left","docstring":"Convenient accessor to the left position.","docstring_summary":"Convenient accessor to the left position.","docstring_tokens":["Convenient","accessor","to","the","left","position","."],"function":"def left(self):\n        # type: () -> int\n        \"\"\" Convenient accessor to the left position. \"\"\"\n        return self.pos.left","function_tokens":["def","left","(","self",")",":","# type: () -> int","return","self",".","pos",".","left"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L91-L94"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.pixels","parameters":"(self)","argument_list":"","return_statement":"return self.__pixels","docstring":":return list: RGB tuples.","docstring_summary":":return list: RGB tuples.","docstring_tokens":[":","return","list",":","RGB","tuples","."],"function":"def pixels(self):\n        # type: () -> Pixels\n        \"\"\"\n        :return list: RGB tuples.\n        \"\"\"\n\n        if not self.__pixels:\n            rgb_tuples = zip(\n                self.raw[2::4], self.raw[1::4], self.raw[0::4]\n            )  # type: Iterator[Pixel]\n            self.__pixels = list(zip(*[iter(rgb_tuples)] * self.width))  # type: ignore\n\n        return self.__pixels","function_tokens":["def","pixels","(","self",")",":","# type: () -> Pixels","if","not","self",".","__pixels",":","rgb_tuples","=","zip","(","self",".","raw","[","2",":",":","4","]",",","self",".","raw","[","1",":",":","4","]",",","self",".","raw","[","0",":",":","4","]",")","# type: Iterator[Pixel]","self",".","__pixels","=","list","(","zip","(","*","[","iter","(","rgb_tuples",")","]","*","self",".","width",")",")","# type: ignore","return","self",".","__pixels"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L97-L109"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.rgb","parameters":"(self)","argument_list":"","return_statement":"return self.__rgb","docstring":"Compute RGB values from the BGRA raw pixels.\n\n        :return bytes: RGB pixels.","docstring_summary":"Compute RGB values from the BGRA raw pixels.","docstring_tokens":["Compute","RGB","values","from","the","BGRA","raw","pixels","."],"function":"def rgb(self):\n        # type: () -> bytes\n        \"\"\"\n        Compute RGB values from the BGRA raw pixels.\n\n        :return bytes: RGB pixels.\n        \"\"\"\n\n        if not self.__rgb:\n            rgb = bytearray(self.height * self.width * 3)\n            raw = self.raw\n            rgb[0::3] = raw[2::4]\n            rgb[1::3] = raw[1::4]\n            rgb[2::3] = raw[0::4]\n            self.__rgb = bytes(rgb)\n\n        return self.__rgb","function_tokens":["def","rgb","(","self",")",":","# type: () -> bytes","if","not","self",".","__rgb",":","rgb","=","bytearray","(","self",".","height","*","self",".","width","*","3",")","raw","=","self",".","raw","rgb","[","0",":",":","3","]","=","raw","[","2",":",":","4","]","rgb","[","1",":",":","3","]","=","raw","[","1",":",":","4","]","rgb","[","2",":",":","3","]","=","raw","[","0",":",":","4","]","self",".","__rgb","=","bytes","(","rgb",")","return","self",".","__rgb"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L112-L128"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.top","parameters":"(self)","argument_list":"","return_statement":"return self.pos.top","docstring":"Convenient accessor to the top position.","docstring_summary":"Convenient accessor to the top position.","docstring_tokens":["Convenient","accessor","to","the","top","position","."],"function":"def top(self):\n        # type: () -> int\n        \"\"\" Convenient accessor to the top position. \"\"\"\n        return self.pos.top","function_tokens":["def","top","(","self",")",":","# type: () -> int","return","self",".","pos",".","top"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L131-L134"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.width","parameters":"(self)","argument_list":"","return_statement":"return self.size.width","docstring":"Convenient accessor to the width size.","docstring_summary":"Convenient accessor to the width size.","docstring_tokens":["Convenient","accessor","to","the","width","size","."],"function":"def width(self):\n        # type: () -> int\n        \"\"\" Convenient accessor to the width size. \"\"\"\n        return self.size.width","function_tokens":["def","width","(","self",")",":","# type: () -> int","return","self",".","size",".","width"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L137-L140"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.pixel","parameters":"(self, coord_x, coord_y)","argument_list":"","return_statement":"","docstring":"Returns the pixel value at a given position.\n\n        :param int coord_x: The x coordinate.\n        :param int coord_y: The y coordinate.\n        :return tuple: The pixel value as (R, G, B).","docstring_summary":"Returns the pixel value at a given position.","docstring_tokens":["Returns","the","pixel","value","at","a","given","position","."],"function":"def pixel(self, coord_x, coord_y):\n        # type: (int, int) -> Pixel\n        \"\"\"\n        Returns the pixel value at a given position.\n\n        :param int coord_x: The x coordinate.\n        :param int coord_y: The y coordinate.\n        :return tuple: The pixel value as (R, G, B).\n        \"\"\"\n\n        try:\n            return self.pixels[coord_y][coord_x]  # type: ignore\n        except IndexError:\n            # pylint: disable=raise-missing-from\n            raise ScreenShotError(\n                \"Pixel location ({}, {}) is out of range.\".format(coord_x, coord_y)\n            )","function_tokens":["def","pixel","(","self",",","coord_x",",","coord_y",")",":","# type: (int, int) -> Pixel","try",":","return","self",".","pixels","[","coord_y","]","[","coord_x","]","# type: ignore","except","IndexError",":","# pylint: disable=raise-missing-from","raise","ScreenShotError","(","\"Pixel location ({}, {}) is out of range.\"",".","format","(","coord_x",",","coord_y",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L142-L158"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/factory.py","language":"python","identifier":"mss","parameters":"(**kwargs)","argument_list":"","return_statement":"","docstring":"Factory returning a proper MSS class instance.\n\n        It detects the platform we are running on\n        and chooses the most adapted mss_class to take\n        screenshots.\n\n        It then proxies its arguments to the class for\n        instantiation.","docstring_summary":"Factory returning a proper MSS class instance.","docstring_tokens":["Factory","returning","a","proper","MSS","class","instance","."],"function":"def mss(**kwargs):\n    # type: (Any) -> MSSBase\n    \"\"\" Factory returning a proper MSS class instance.\n\n        It detects the platform we are running on\n        and chooses the most adapted mss_class to take\n        screenshots.\n\n        It then proxies its arguments to the class for\n        instantiation.\n    \"\"\"\n    # pylint: disable=import-outside-toplevel\n\n    os_ = platform.system().lower()\n\n    if os_ == \"darwin\":\n        from . import darwin\n\n        return darwin.MSS(**kwargs)\n\n    if os_ == \"linux\":\n        from . import linux\n\n        return linux.MSS(**kwargs)\n\n    if os_ == \"windows\":\n        from . import windows\n\n        return windows.MSS(**kwargs)\n\n    raise ScreenShotError(\"System {!r} not (yet?) implemented.\".format(os_))","function_tokens":["def","mss","(","*","*","kwargs",")",":","# type: (Any) -> MSSBase","# pylint: disable=import-outside-toplevel","os_","=","platform",".","system","(",")",".","lower","(",")","if","os_","==","\"darwin\"",":","from",".","import","darwin","return","darwin",".","MSS","(","*","*","kwargs",")","if","os_","==","\"linux\"",":","from",".","import","linux","return","linux",".","MSS","(","*","*","kwargs",")","if","os_","==","\"windows\"",":","from",".","import","windows","return","windows",".","MSS","(","*","*","kwargs",")","raise","ScreenShotError","(","\"System {!r} not (yet?) implemented.\"",".","format","(","os_",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/factory.py#L18-L48"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.__enter__","parameters":"(self)","argument_list":"","return_statement":"return self","docstring":"For the cool call `with MSS() as mss:`.","docstring_summary":"For the cool call `with MSS() as mss:`.","docstring_tokens":["For","the","cool","call","with","MSS","()","as","mss",":","."],"function":"def __enter__(self):\n        # type: () -> MSSBase\n        \"\"\" For the cool call `with MSS() as mss:`. \"\"\"\n\n        return self","function_tokens":["def","__enter__","(","self",")",":","# type: () -> MSSBase","return","self"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L35-L39"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.__exit__","parameters":"(self, *_)","argument_list":"","return_statement":"","docstring":"For the cool call `with MSS() as mss:`.","docstring_summary":"For the cool call `with MSS() as mss:`.","docstring_tokens":["For","the","cool","call","with","MSS","()","as","mss",":","."],"function":"def __exit__(self, *_):\n        \"\"\" For the cool call `with MSS() as mss:`. \"\"\"\n\n        self.close()","function_tokens":["def","__exit__","(","self",",","*","_",")",":","self",".","close","(",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L41-L44"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase._grab_impl","parameters":"(self, monitor)","argument_list":"","return_statement":"","docstring":"Retrieve all pixels from a monitor. Pixels have to be RGB.\n        That method has to be run using a threading lock.","docstring_summary":"Retrieve all pixels from a monitor. Pixels have to be RGB.\n        That method has to be run using a threading lock.","docstring_tokens":["Retrieve","all","pixels","from","a","monitor",".","Pixels","have","to","be","RGB",".","That","method","has","to","be","run","using","a","threading","lock","."],"function":"def _grab_impl(self, monitor):\n        # type: (Monitor) -> ScreenShot\n        \"\"\"\n        Retrieve all pixels from a monitor. Pixels have to be RGB.\n        That method has to be run using a threading lock.\n        \"\"\"","function_tokens":["def","_grab_impl","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L47-L52"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase._monitors_impl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get positions of monitors (has to be run using a threading lock).\n        It must populate self._monitors.","docstring_summary":"Get positions of monitors (has to be run using a threading lock).\n        It must populate self._monitors.","docstring_tokens":["Get","positions","of","monitors","(","has","to","be","run","using","a","threading","lock",")",".","It","must","populate","self",".","_monitors","."],"function":"def _monitors_impl(self):\n        # type: () -> None\n        \"\"\"\n        Get positions of monitors (has to be run using a threading lock).\n        It must populate self._monitors.\n        \"\"\"","function_tokens":["def","_monitors_impl","(","self",")",":","# type: () -> None"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L55-L60"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Clean-up.","docstring_summary":"Clean-up.","docstring_tokens":["Clean","-","up","."],"function":"def close(self):\n        # type: () -> None\n        \"\"\" Clean-up. \"\"\"","function_tokens":["def","close","(","self",")",":","# type: () -> None"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L62-L64"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.grab","parameters":"(self, monitor)","argument_list":"","return_statement":"","docstring":"Retrieve screen pixels for a given monitor.\n\n        Note: *monitor* can be a tuple like the one PIL.Image.grab() accepts.\n\n        :param monitor: The coordinates and size of the box to capture.\n                        See :meth:`monitors <monitors>` for object details.\n        :return :class:`ScreenShot <ScreenShot>`.","docstring_summary":"Retrieve screen pixels for a given monitor.","docstring_tokens":["Retrieve","screen","pixels","for","a","given","monitor","."],"function":"def grab(self, monitor):\n        # type: (Monitor) -> ScreenShot\n        \"\"\"\n        Retrieve screen pixels for a given monitor.\n\n        Note: *monitor* can be a tuple like the one PIL.Image.grab() accepts.\n\n        :param monitor: The coordinates and size of the box to capture.\n                        See :meth:`monitors <monitors>` for object details.\n        :return :class:`ScreenShot <ScreenShot>`.\n        \"\"\"\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        with lock:\n            return self._grab_impl(monitor)","function_tokens":["def","grab","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot","# Convert PIL bbox style","if","isinstance","(","monitor",",","tuple",")",":","monitor","=","{","\"left\"",":","monitor","[","0","]",",","\"top\"",":","monitor","[","1","]",",","\"width\"",":","monitor","[","2","]","-","monitor","[","0","]",",","\"height\"",":","monitor","[","3","]","-","monitor","[","1","]",",","}","with","lock",":","return","self",".","_grab_impl","(","monitor",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L66-L88"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.monitors","parameters":"(self)","argument_list":"","return_statement":"return self._monitors","docstring":"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            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        }","docstring_summary":"Get positions of all monitors.\n        If the monitor has rotation, you have to deal with it\n        inside this method.","docstring_tokens":["Get","positions","of","all","monitors",".","If","the","monitor","has","rotation","you","have","to","deal","with","it","inside","this","method","."],"function":"def monitors(self):\n        # type: () -> Monitors\n        \"\"\"\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            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        }\n        \"\"\"\n\n        if not self._monitors:\n            with lock:\n                self._monitors_impl()\n\n        return self._monitors","function_tokens":["def","monitors","(","self",")",":","# type: () -> Monitors","if","not","self",".","_monitors",":","with","lock",":","self",".","_monitors_impl","(",")","return","self",".","_monitors"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L91-L116"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.save","parameters":"(self, mon=0, output=\"monitor-{mon}.png\", callback=None)","argument_list":"","return_statement":"","docstring":"Grab a screen shot and save it to a file.\n\n        :param int mon: The monitor to screen shot (default=0).\n                        -1: grab one screen shot of all monitors\n                         0: grab one screen shot by monitor\n                        N: grab the screen shot of the monitor N\n\n        :param str output: The output filename.\n\n            It can take several keywords to customize the filename:\n            - `{mon}`: the monitor number\n            - `{top}`: the screen shot y-coordinate of the upper-left corner\n            - `{left}`: the screen shot x-coordinate of the upper-left corner\n            - `{width}`: the screen shot's width\n            - `{height}`: the screen shot's height\n            - `{date}`: the current date using the default formatter\n\n            As it is using the `format()` function, you can specify\n            formatting options like `{date:%Y-%m-%s}`.\n\n        :param callable callback: Callback called before saving the\n            screen shot to a file.  Take the `output` argument as parameter.\n\n        :return generator: Created file(s).","docstring_summary":"Grab a screen shot and save it to a file.","docstring_tokens":["Grab","a","screen","shot","and","save","it","to","a","file","."],"function":"def save(self, mon=0, output=\"monitor-{mon}.png\", callback=None):\n        # type: (int, str, Callable[[str], None]) -> Iterator[str]\n        \"\"\"\n        Grab a screen shot and save it to a file.\n\n        :param int mon: The monitor to screen shot (default=0).\n                        -1: grab one screen shot of all monitors\n                         0: grab one screen shot by monitor\n                        N: grab the screen shot of the monitor N\n\n        :param str output: The output filename.\n\n            It can take several keywords to customize the filename:\n            - `{mon}`: the monitor number\n            - `{top}`: the screen shot y-coordinate of the upper-left corner\n            - `{left}`: the screen shot x-coordinate of the upper-left corner\n            - `{width}`: the screen shot's width\n            - `{height}`: the screen shot's height\n            - `{date}`: the current date using the default formatter\n\n            As it is using the `format()` function, you can specify\n            formatting options like `{date:%Y-%m-%s}`.\n\n        :param callable callback: Callback called before saving the\n            screen shot to a file.  Take the `output` argument as parameter.\n\n        :return generator: Created file(s).\n        \"\"\"\n\n        monitors = self.monitors\n        if not monitors:\n            raise ScreenShotError(\"No monitor found.\")\n\n        if mon == 0:\n            # One screen shot by monitor\n            for idx, monitor in enumerate(monitors[1:], 1):\n                fname = output.format(mon=idx, date=datetime.now(), **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 screen shot of all monitors together or\n            # a screen shot of the monitor N.\n            mon = 0 if mon == -1 else mon\n            try:\n                monitor = monitors[mon]\n            except IndexError:\n                # pylint: disable=raise-missing-from\n                raise ScreenShotError(\"Monitor {!r} does not exist.\".format(mon))\n\n            output = output.format(mon=mon, date=datetime.now(), **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","function_tokens":["def","save","(","self",",","mon","=","0",",","output","=","\"monitor-{mon}.png\"",",","callback","=","None",")",":","# type: (int, str, Callable[[str], None]) -> Iterator[str]","monitors","=","self",".","monitors","if","not","monitors",":","raise","ScreenShotError","(","\"No monitor found.\"",")","if","mon","==","0",":","# One screen shot by monitor","for","idx",",","monitor","in","enumerate","(","monitors","[","1",":","]",",","1",")",":","fname","=","output",".","format","(","mon","=","idx",",","date","=","datetime",".","now","(",")",",","*","*","monitor",")","if","callable","(","callback",")",":","callback","(","fname",")","sct","=","self",".","grab","(","monitor",")","to_png","(","sct",".","rgb",",","sct",".","size",",","level","=","self",".","compression_level",",","output","=","fname",")","yield","fname","else",":","# A screen shot of all monitors together or","# a screen shot of the monitor N.","mon","=","0","if","mon","==","-","1","else","mon","try",":","monitor","=","monitors","[","mon","]","except","IndexError",":","# pylint: disable=raise-missing-from","raise","ScreenShotError","(","\"Monitor {!r} does not exist.\"",".","format","(","mon",")",")","output","=","output",".","format","(","mon","=","mon",",","date","=","datetime",".","now","(",")",",","*","*","monitor",")","if","callable","(","callback",")",":","callback","(","output",")","sct","=","self",".","grab","(","monitor",")","to_png","(","sct",".","rgb",",","sct",".","size",",","level","=","self",".","compression_level",",","output","=","output",")","yield","output"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L118-L175"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.shot","parameters":"(self, **kwargs)","argument_list":"","return_statement":"return next(self.save(**kwargs))","docstring":"Helper to save the screen shot of the 1st monitor, by default.\n        You can pass the same arguments as for ``save``.","docstring_summary":"Helper to save the screen shot of the 1st monitor, by default.\n        You can pass the same arguments as for ``save``.","docstring_tokens":["Helper","to","save","the","screen","shot","of","the","1st","monitor","by","default",".","You","can","pass","the","same","arguments","as","for","save","."],"function":"def shot(self, **kwargs):\n        # type: (Any) -> str\n        \"\"\"\n        Helper to save the screen shot of the 1st monitor, by default.\n        You can pass the same arguments as for ``save``.\n        \"\"\"\n\n        kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n        return next(self.save(**kwargs))","function_tokens":["def","shot","(","self",",","*","*","kwargs",")",":","# type: (Any) -> str","kwargs","[","\"mon\"","]","=","kwargs",".","get","(","\"mon\"",",","1",")","return","next","(","self",".","save","(","*","*","kwargs",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L177-L185"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase._cfactory","parameters":"(attr, func, argtypes, restype, errcheck=None)","argument_list":"","return_statement":"","docstring":"Factory to create a ctypes function and automatically manage errors.","docstring_summary":"Factory to create a ctypes function and automatically manage errors.","docstring_tokens":["Factory","to","create","a","ctypes","function","and","automatically","manage","errors","."],"function":"def _cfactory(attr, func, argtypes, restype, errcheck=None):\n        # type: (Any, str, List[Any], Any, Optional[Callable]) -> None\n        \"\"\" Factory to create a ctypes function and automatically manage errors. \"\"\"\n\n        meth = getattr(attr, func)\n        meth.argtypes = argtypes\n        meth.restype = restype\n        if errcheck:\n            meth.errcheck = errcheck","function_tokens":["def","_cfactory","(","attr",",","func",",","argtypes",",","restype",",","errcheck","=","None",")",":","# type: (Any, str, List[Any], Any, Optional[Callable]) -> None","meth","=","getattr","(","attr",",","func",")","meth",".","argtypes","=","argtypes","meth",".","restype","=","restype","if","errcheck",":","meth",".","errcheck","=","errcheck"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L188-L196"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"cgfloat","parameters":"()","argument_list":"","return_statement":"return c_double if sys.maxsize > 2 ** 32 else c_float","docstring":"Get the appropriate value for a float.","docstring_summary":"Get the appropriate value for a float.","docstring_tokens":["Get","the","appropriate","value","for","a","float","."],"function":"def cgfloat():\n    # type: () -> Union[Type[c_double], Type[c_float]]\n    \"\"\" Get the appropriate value for a float. \"\"\"\n\n    return c_double if sys.maxsize > 2 ** 32 else c_float","function_tokens":["def","cgfloat","(",")",":","# type: () -> Union[Type[c_double], Type[c_float]]","return","c_double","if","sys",".","maxsize",">","2","**","32","else","c_float"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L36-L40"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS.__init__","parameters":"(self, **_)","argument_list":"","return_statement":"","docstring":"macOS initialisations.","docstring_summary":"macOS initialisations.","docstring_tokens":["macOS","initialisations","."],"function":"def __init__(self, **_):\n        \"\"\" macOS initialisations. \"\"\"\n\n        super().__init__()\n\n        self.max_displays = 32\n\n        self._init_library()\n        self._set_cfunctions()","function_tokens":["def","__init__","(","self",",","*","*","_",")",":","super","(",")",".","__init__","(",")","self",".","max_displays","=","32","self",".","_init_library","(",")","self",".","_set_cfunctions","(",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L116-L124"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS._init_library","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Load the CoreGraphics library.","docstring_summary":"Load the CoreGraphics library.","docstring_tokens":["Load","the","CoreGraphics","library","."],"function":"def _init_library(self):\n        \"\"\" Load the CoreGraphics library. \"\"\"\n        version = float(\".\".join(mac_ver()[0].split(\".\")[:2]))\n        if version < 10.16:\n            coregraphics = ctypes.util.find_library(\"CoreGraphics\")\n        else:\n            # macOS Big Sur and newer\n            # pylint: disable=line-too-long\n            coregraphics = \"\/System\/Library\/Frameworks\/CoreGraphics.framework\/Versions\/Current\/CoreGraphics\"\n\n        if not coregraphics:\n            raise ScreenShotError(\"No CoreGraphics library found.\")\n        self.core = ctypes.cdll.LoadLibrary(coregraphics)","function_tokens":["def","_init_library","(","self",")",":","version","=","float","(","\".\"",".","join","(","mac_ver","(",")","[","0","]",".","split","(","\".\"",")","[",":","2","]",")",")","if","version","<","10.16",":","coregraphics","=","ctypes",".","util",".","find_library","(","\"CoreGraphics\"",")","else",":","# macOS Big Sur and newer","# pylint: disable=line-too-long","coregraphics","=","\"\/System\/Library\/Frameworks\/CoreGraphics.framework\/Versions\/Current\/CoreGraphics\"","if","not","coregraphics",":","raise","ScreenShotError","(","\"No CoreGraphics library found.\"",")","self",".","core","=","ctypes",".","cdll",".","LoadLibrary","(","coregraphics",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L126-L138"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS._set_cfunctions","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set all ctypes functions and attach them to attributes.","docstring_summary":"Set all ctypes functions and attach them to attributes.","docstring_tokens":["Set","all","ctypes","functions","and","attach","them","to","attributes","."],"function":"def _set_cfunctions(self):\n        # type: () -> None\n        \"\"\" Set all ctypes functions and attach them to attributes. \"\"\"\n\n        cfactory = self._cfactory\n        attrs = {\"core\": self.core}\n        for func, (attr, argtypes, restype) in CFUNCTIONS.items():\n            cfactory(\n                attr=attrs[attr],\n                func=func,\n                argtypes=argtypes,  # type: ignore\n                restype=restype,\n            )","function_tokens":["def","_set_cfunctions","(","self",")",":","# type: () -> None","cfactory","=","self",".","_cfactory","attrs","=","{","\"core\"",":","self",".","core","}","for","func",",","(","attr",",","argtypes",",","restype",")","in","CFUNCTIONS",".","items","(",")",":","cfactory","(","attr","=","attrs","[","attr","]",",","func","=","func",",","argtypes","=","argtypes",",","# type: ignore","restype","=","restype",",",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L140-L152"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS._monitors_impl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get positions of monitors. It will populate self._monitors.","docstring_summary":"Get positions of monitors. It will populate self._monitors.","docstring_tokens":["Get","positions","of","monitors",".","It","will","populate","self",".","_monitors","."],"function":"def _monitors_impl(self):\n        # type: () -> None\n        \"\"\" Get positions of monitors. It will populate self._monitors. \"\"\"\n\n        int_ = int\n        core = self.core\n\n        # All monitors\n        # We need to update the value with every single monitor found\n        # using CGRectUnion.  Else we will end with infinite values.\n        all_monitors = CGRect()\n        self._monitors.append({})\n\n        # Each monitor\n        display_count = c_uint32(0)\n        active_displays = (c_uint32 * self.max_displays)()\n        core.CGGetActiveDisplayList(\n            self.max_displays, active_displays, ctypes.byref(display_count)\n        )\n        rotations = {0.0: \"normal\", 90.0: \"right\", -90.0: \"left\"}\n        for idx in range(display_count.value):\n            display = active_displays[idx]\n            rect = core.CGDisplayBounds(display)\n            rect = core.CGRectStandardize(rect)\n            width, height = rect.size.width, rect.size.height\n            rot = core.CGDisplayRotation(display)\n            if rotations[rot] in [\"left\", \"right\"]:\n                width, height = height, width\n            self._monitors.append(\n                {\n                    \"left\": int_(rect.origin.x),\n                    \"top\": int_(rect.origin.y),\n                    \"width\": int_(width),\n                    \"height\": int_(height),\n                }\n            )\n\n            # Update AiO monitor's values\n            all_monitors = core.CGRectUnion(all_monitors, rect)\n\n        # Set the AiO monitor's values\n        self._monitors[0] = {\n            \"left\": int_(all_monitors.origin.x),\n            \"top\": int_(all_monitors.origin.y),\n            \"width\": int_(all_monitors.size.width),\n            \"height\": int_(all_monitors.size.height),\n        }","function_tokens":["def","_monitors_impl","(","self",")",":","# type: () -> None","int_","=","int","core","=","self",".","core","# All monitors","# We need to update the value with every single monitor found","# using CGRectUnion.  Else we will end with infinite values.","all_monitors","=","CGRect","(",")","self",".","_monitors",".","append","(","{","}",")","# Each monitor","display_count","=","c_uint32","(","0",")","active_displays","=","(","c_uint32","*","self",".","max_displays",")","(",")","core",".","CGGetActiveDisplayList","(","self",".","max_displays",",","active_displays",",","ctypes",".","byref","(","display_count",")",")","rotations","=","{","0.0",":","\"normal\"",",","90.0",":","\"right\"",",","-","90.0",":","\"left\"","}","for","idx","in","range","(","display_count",".","value",")",":","display","=","active_displays","[","idx","]","rect","=","core",".","CGDisplayBounds","(","display",")","rect","=","core",".","CGRectStandardize","(","rect",")","width",",","height","=","rect",".","size",".","width",",","rect",".","size",".","height","rot","=","core",".","CGDisplayRotation","(","display",")","if","rotations","[","rot","]","in","[","\"left\"",",","\"right\"","]",":","width",",","height","=","height",",","width","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","rect",".","origin",".","x",")",",","\"top\"",":","int_","(","rect",".","origin",".","y",")",",","\"width\"",":","int_","(","width",")",",","\"height\"",":","int_","(","height",")",",","}",")","# Update AiO monitor's values","all_monitors","=","core",".","CGRectUnion","(","all_monitors",",","rect",")","# Set the AiO monitor's values","self",".","_monitors","[","0","]","=","{","\"left\"",":","int_","(","all_monitors",".","origin",".","x",")",",","\"top\"",":","int_","(","all_monitors",".","origin",".","y",")",",","\"width\"",":","int_","(","all_monitors",".","size",".","width",")",",","\"height\"",":","int_","(","all_monitors",".","size",".","height",")",",","}"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L154-L200"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS._grab_impl","parameters":"(self, monitor)","argument_list":"","return_statement":"return self.cls_image(data, monitor, size=Size(width, height))","docstring":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_summary":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_tokens":["Retrieve","all","pixels","from","a","monitor",".","Pixels","have","to","be","RGB","."],"function":"def _grab_impl(self, monitor):\n        # type: (Monitor) -> ScreenShot\n        \"\"\" Retrieve all pixels from a monitor. Pixels have to be RGB. \"\"\"\n\n        # pylint: disable=too-many-locals\n\n        core = self.core\n        rect = CGRect(\n            (monitor[\"left\"], monitor[\"top\"]), (monitor[\"width\"], monitor[\"height\"])\n        )\n\n        image_ref = core.CGWindowListCreateImage(rect, 1, 0, 0)\n        if not image_ref:\n            raise ScreenShotError(\"CoreGraphics.CGWindowListCreateImage() failed.\")\n\n        width = core.CGImageGetWidth(image_ref)\n        height = core.CGImageGetHeight(image_ref)\n        prov = copy_data = None\n        try:\n            prov = core.CGImageGetDataProvider(image_ref)\n            copy_data = core.CGDataProviderCopyData(prov)\n            data_ref = core.CFDataGetBytePtr(copy_data)\n            buf_len = core.CFDataGetLength(copy_data)\n            raw = ctypes.cast(data_ref, POINTER(c_ubyte * buf_len))\n            data = bytearray(raw.contents)\n\n            # Remove padding per row\n            bytes_per_row = core.CGImageGetBytesPerRow(image_ref)\n            bytes_per_pixel = core.CGImageGetBitsPerPixel(image_ref)\n            bytes_per_pixel = (bytes_per_pixel + 7) \/\/ 8\n\n            if bytes_per_pixel * width != bytes_per_row:\n                cropped = bytearray()\n                for row in range(height):\n                    start = row * bytes_per_row\n                    end = start + width * bytes_per_pixel\n                    cropped.extend(data[start:end])\n                data = cropped\n        finally:\n            if prov:\n                core.CGDataProviderRelease(prov)\n            if copy_data:\n                core.CFRelease(copy_data)\n\n        return self.cls_image(data, monitor, size=Size(width, height))","function_tokens":["def","_grab_impl","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot","# pylint: disable=too-many-locals","core","=","self",".","core","rect","=","CGRect","(","(","monitor","[","\"left\"","]",",","monitor","[","\"top\"","]",")",",","(","monitor","[","\"width\"","]",",","monitor","[","\"height\"","]",")",")","image_ref","=","core",".","CGWindowListCreateImage","(","rect",",","1",",","0",",","0",")","if","not","image_ref",":","raise","ScreenShotError","(","\"CoreGraphics.CGWindowListCreateImage() failed.\"",")","width","=","core",".","CGImageGetWidth","(","image_ref",")","height","=","core",".","CGImageGetHeight","(","image_ref",")","prov","=","copy_data","=","None","try",":","prov","=","core",".","CGImageGetDataProvider","(","image_ref",")","copy_data","=","core",".","CGDataProviderCopyData","(","prov",")","data_ref","=","core",".","CFDataGetBytePtr","(","copy_data",")","buf_len","=","core",".","CFDataGetLength","(","copy_data",")","raw","=","ctypes",".","cast","(","data_ref",",","POINTER","(","c_ubyte","*","buf_len",")",")","data","=","bytearray","(","raw",".","contents",")","# Remove padding per row","bytes_per_row","=","core",".","CGImageGetBytesPerRow","(","image_ref",")","bytes_per_pixel","=","core",".","CGImageGetBitsPerPixel","(","image_ref",")","bytes_per_pixel","=","(","bytes_per_pixel","+","7",")","\/\/","8","if","bytes_per_pixel","*","width","!=","bytes_per_row",":","cropped","=","bytearray","(",")","for","row","in","range","(","height",")",":","start","=","row","*","bytes_per_row","end","=","start","+","width","*","bytes_per_pixel","cropped",".","extend","(","data","[","start",":","end","]",")","data","=","cropped","finally",":","if","prov",":","core",".","CGDataProviderRelease","(","prov",")","if","copy_data",":","core",".","CFRelease","(","copy_data",")","return","self",".","cls_image","(","data",",","monitor",",","size","=","Size","(","width",",","height",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L202-L246"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/__main__.py","language":"python","identifier":"main","parameters":"(args=None)","argument_list":"","return_statement":"","docstring":"Main logic.","docstring_summary":"Main logic.","docstring_tokens":["Main","logic","."],"function":"def main(args=None):\n    # type: (Optional[List[str]]) -> int\n    \"\"\" Main logic. \"\"\"\n\n    cli_args = ArgumentParser()\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(\n        \"-m\", \"--monitor\", default=0, type=int, help=\"the monitor to screen shot\"\n    )\n    cli_args.add_argument(\n        \"-o\", \"--output\", default=\"monitor-{mon}.png\", help=\"the output file name\"\n    )\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(\"-v\", \"--version\", action=\"version\", version=__version__)\n\n    options = cli_args.parse_args(args)\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() 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        return 1","function_tokens":["def","main","(","args","=","None",")",":","# type: (Optional[List[str]]) -> int","cli_args","=","ArgumentParser","(",")","cli_args",".","add_argument","(","\"-c\"",",","\"--coordinates\"",",","default","=","\"\"",",","type","=","str",",","help","=","\"the part of the screen to capture: top, left, width, height\"",",",")","cli_args",".","add_argument","(","\"-l\"",",","\"--level\"",",","default","=","6",",","type","=","int",",","choices","=","list","(","range","(","10",")",")",",","help","=","\"the PNG compression level\"",",",")","cli_args",".","add_argument","(","\"-m\"",",","\"--monitor\"",",","default","=","0",",","type","=","int",",","help","=","\"the monitor to screen shot\"",")","cli_args",".","add_argument","(","\"-o\"",",","\"--output\"",",","default","=","\"monitor-{mon}.png\"",",","help","=","\"the output file name\"",")","cli_args",".","add_argument","(","\"-q\"",",","\"--quiet\"",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"do not print created files\"",",",")","cli_args",".","add_argument","(","\"-v\"",",","\"--version\"",",","action","=","\"version\"",",","version","=","__version__",")","options","=","cli_args",".","parse_args","(","args",")","kwargs","=","{","\"mon\"",":","options",".","monitor",",","\"output\"",":","options",".","output","}","if","options",".","coordinates",":","try",":","top",",","left",",","width",",","height","=","options",".","coordinates",".","split","(","\",\"",")","except","ValueError",":","print","(","\"Coordinates syntax: top, left, width, height\"",")","return","2","kwargs","[","\"mon\"","]","=","{","\"top\"",":","int","(","top",")",",","\"left\"",":","int","(","left",")",",","\"width\"",":","int","(","width",")",",","\"height\"",":","int","(","height",")",",","}","if","options",".","output","==","\"monitor-{mon}.png\"",":","kwargs","[","\"output\"","]","=","\"sct-{top}x{left}_{width}x{height}.png\"","try",":","with","mss","(",")","as","sct",":","if","options",".","coordinates",":","output","=","kwargs","[","\"output\"","]",".","format","(","*","*","kwargs","[","\"mon\"","]",")","sct_img","=","sct",".","grab","(","kwargs","[","\"mon\"","]",")","to_png","(","sct_img",".","rgb",",","sct_img",".","size",",","level","=","options",".","level",",","output","=","output",")","if","not","options",".","quiet",":","print","(","os",".","path",".","realpath","(","output",")",")","else",":","for","file_name","in","sct",".","save","(","*","*","kwargs",")",":","if","not","options",".","quiet",":","print","(","os",".","path",".","realpath","(","file_name",")",")","return","0","except","ScreenShotError",":","return","1"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/__main__.py#L20-L87"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"error_handler","parameters":"(_, event)","argument_list":"","return_statement":"return 0","docstring":"Specifies the program's supplied error handler.","docstring_summary":"Specifies the program's supplied error handler.","docstring_tokens":["Specifies","the","program","s","supplied","error","handler","."],"function":"def error_handler(_, event):\n    # type: (Any, Any) -> int\n    \"\"\" Specifies the program's supplied error handler. \"\"\"\n\n    evt = event.contents\n    ERROR.details = {\n        \"type\": evt.type,\n        \"serial\": evt.serial,\n        \"error_code\": evt.error_code,\n        \"request_code\": evt.request_code,\n        \"minor_code\": evt.minor_code,\n    }\n    return 0","function_tokens":["def","error_handler","(","_",",","event",")",":","# type: (Any, Any) -> int","evt","=","event",".","contents","ERROR",".","details","=","{","\"type\"",":","evt",".","type",",","\"serial\"",":","evt",".","serial",",","\"error_code\"",":","evt",".","error_code",",","\"request_code\"",":","evt",".","request_code",",","\"minor_code\"",":","evt",".","minor_code",",","}","return","0"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L167-L179"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"validate","parameters":"(retval, func, args)","argument_list":"","return_statement":"","docstring":"Validate the returned value of a Xlib or XRANDR function.","docstring_summary":"Validate the returned value of a Xlib or XRANDR function.","docstring_tokens":["Validate","the","returned","value","of","a","Xlib","or","XRANDR","function","."],"function":"def validate(retval, func, args):\n    # type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]]\n    \"\"\" Validate the returned value of a Xlib or XRANDR function. \"\"\"\n\n    if retval != 0 and not ERROR.details:\n        return args\n\n    err = \"{}() failed\".format(func.__name__)\n    details = {\"retval\": retval, \"args\": args}\n    raise ScreenShotError(err, details=details)","function_tokens":["def","validate","(","retval",",","func",",","args",")",":","# type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]]","if","retval","!=","0","and","not","ERROR",".","details",":","return","args","err","=","\"{}() failed\"",".","format","(","func",".","__name__",")","details","=","{","\"retval\"",":","retval",",","\"args\"",":","args","}","raise","ScreenShotError","(","err",",","details","=","details",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L182-L191"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS.__init__","parameters":"(self, display=None)","argument_list":"","return_statement":"","docstring":"GNU\/Linux initialisations.","docstring_summary":"GNU\/Linux initialisations.","docstring_tokens":["GNU","\/","Linux","initialisations","."],"function":"def __init__(self, display=None):\n        # type: (Optional[Union[bytes, str]]) -> None\n        \"\"\" GNU\/Linux initialisations. \"\"\"\n\n        super().__init__()\n\n        if not display:\n            try:\n                display = os.environ[\"DISPLAY\"].encode(\"utf-8\")\n            except KeyError:\n                # pylint: disable=raise-missing-from\n                raise ScreenShotError(\"$DISPLAY not set.\")\n\n        if not isinstance(display, bytes):\n            display = display.encode(\"utf-8\")\n\n        if b\":\" not in display:\n            raise ScreenShotError(\"Bad display value: {!r}.\".format(display))\n\n        x11 = ctypes.util.find_library(\"X11\")\n        if not x11:\n            raise ScreenShotError(\"No X11 library found.\")\n        self.xlib = ctypes.cdll.LoadLibrary(x11)\n\n        # Install the error handler to prevent interpreter crashes:\n        # any error will raise a ScreenShotError exception.\n        self.xlib.XSetErrorHandler(error_handler)\n\n        xrandr = ctypes.util.find_library(\"Xrandr\")\n        if not xrandr:\n            raise ScreenShotError(\"No Xrandr extension found.\")\n        self.xrandr = ctypes.cdll.LoadLibrary(xrandr)\n\n        self._set_cfunctions()\n\n        self.root = self.xlib.XDefaultRootWindow(self._get_display(display))\n\n        if not self.has_extension(\"RANDR\"):\n            raise ScreenShotError(\"No Xrandr extension found.\")\n\n        # Fix for XRRGetScreenResources and XGetImage:\n        #     expected LP_Display instance instead of LP_XWindowAttributes\n        self.drawable = ctypes.cast(self.root, POINTER(Display))","function_tokens":["def","__init__","(","self",",","display","=","None",")",":","# type: (Optional[Union[bytes, str]]) -> None","super","(",")",".","__init__","(",")","if","not","display",":","try",":","display","=","os",".","environ","[","\"DISPLAY\"","]",".","encode","(","\"utf-8\"",")","except","KeyError",":","# pylint: disable=raise-missing-from","raise","ScreenShotError","(","\"$DISPLAY not set.\"",")","if","not","isinstance","(","display",",","bytes",")",":","display","=","display",".","encode","(","\"utf-8\"",")","if","b\":\"","not","in","display",":","raise","ScreenShotError","(","\"Bad display value: {!r}.\"",".","format","(","display",")",")","x11","=","ctypes",".","util",".","find_library","(","\"X11\"",")","if","not","x11",":","raise","ScreenShotError","(","\"No X11 library found.\"",")","self",".","xlib","=","ctypes",".","cdll",".","LoadLibrary","(","x11",")","# Install the error handler to prevent interpreter crashes:","# any error will raise a ScreenShotError exception.","self",".","xlib",".","XSetErrorHandler","(","error_handler",")","xrandr","=","ctypes",".","util",".","find_library","(","\"Xrandr\"",")","if","not","xrandr",":","raise","ScreenShotError","(","\"No Xrandr extension found.\"",")","self",".","xrandr","=","ctypes",".","cdll",".","LoadLibrary","(","xrandr",")","self",".","_set_cfunctions","(",")","self",".","root","=","self",".","xlib",".","XDefaultRootWindow","(","self",".","_get_display","(","display",")",")","if","not","self",".","has_extension","(","\"RANDR\"",")",":","raise","ScreenShotError","(","\"No Xrandr extension found.\"",")","# Fix for XRRGetScreenResources and XGetImage:","#     expected LP_Display instance instead of LP_XWindowAttributes","self",".","drawable","=","ctypes",".","cast","(","self",".","root",",","POINTER","(","Display",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L270-L312"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS.has_extension","parameters":"(self, extension)","argument_list":"","return_statement":"","docstring":"Return True if the given *extension* is part of the extensions list of the server.","docstring_summary":"Return True if the given *extension* is part of the extensions list of the server.","docstring_tokens":["Return","True","if","the","given","*","extension","*","is","part","of","the","extensions","list","of","the","server","."],"function":"def has_extension(self, extension):\n        # type: (str) -> bool\n        \"\"\"Return True if the given *extension* is part of the extensions list of the server.\"\"\"\n        with lock:\n            major_opcode_return = c_int()\n            first_event_return = c_int()\n            first_error_return = c_int()\n\n            try:\n                self.xlib.XQueryExtension(\n                    self._get_display(),\n                    extension.encode(\"latin1\"),\n                    ctypes.byref(major_opcode_return),\n                    ctypes.byref(first_event_return),\n                    ctypes.byref(first_error_return),\n                )\n            except ScreenShotError:\n                return False\n            else:\n                return True","function_tokens":["def","has_extension","(","self",",","extension",")",":","# type: (str) -> bool","with","lock",":","major_opcode_return","=","c_int","(",")","first_event_return","=","c_int","(",")","first_error_return","=","c_int","(",")","try",":","self",".","xlib",".","XQueryExtension","(","self",".","_get_display","(",")",",","extension",".","encode","(","\"latin1\"",")",",","ctypes",".","byref","(","major_opcode_return",")",",","ctypes",".","byref","(","first_event_return",")",",","ctypes",".","byref","(","first_error_return",")",",",")","except","ScreenShotError",":","return","False","else",":","return","True"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L314-L333"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS._get_display","parameters":"(self, disp=None)","argument_list":"","return_statement":"return display","docstring":"Retrieve a thread-safe display from XOpenDisplay().\n        In multithreading, if the thread that creates *display* is dead, *display* will\n        no longer be valid to grab the screen. The *display* attribute is replaced\n        with *_display_dict* to maintain the *display* values in multithreading.\n        Since the current thread and main thread are always alive, reuse their\n        *display* value first.","docstring_summary":"Retrieve a thread-safe display from XOpenDisplay().\n        In multithreading, if the thread that creates *display* is dead, *display* will\n        no longer be valid to grab the screen. The *display* attribute is replaced\n        with *_display_dict* to maintain the *display* values in multithreading.\n        Since the current thread and main thread are always alive, reuse their\n        *display* value first.","docstring_tokens":["Retrieve","a","thread","-","safe","display","from","XOpenDisplay","()",".","In","multithreading","if","the","thread","that","creates","*","display","*","is","dead","*","display","*","will","no","longer","be","valid","to","grab","the","screen",".","The","*","display","*","attribute","is","replaced","with","*","_display_dict","*","to","maintain","the","*","display","*","values","in","multithreading",".","Since","the","current","thread","and","main","thread","are","always","alive","reuse","their","*","display","*","value","first","."],"function":"def _get_display(self, disp=None):\n        \"\"\"\n        Retrieve a thread-safe display from XOpenDisplay().\n        In multithreading, if the thread that creates *display* is dead, *display* will\n        no longer be valid to grab the screen. The *display* attribute is replaced\n        with *_display_dict* to maintain the *display* values in multithreading.\n        Since the current thread and main thread are always alive, reuse their\n        *display* value first.\n        \"\"\"\n        cur_thread, main_thread = threading.current_thread(), threading.main_thread()\n        display = MSS._display_dict.get(cur_thread) or MSS._display_dict.get(\n            main_thread\n        )\n        if not display:\n            display = MSS._display_dict[cur_thread] = self.xlib.XOpenDisplay(disp)\n        return display","function_tokens":["def","_get_display","(","self",",","disp","=","None",")",":","cur_thread",",","main_thread","=","threading",".","current_thread","(",")",",","threading",".","main_thread","(",")","display","=","MSS",".","_display_dict",".","get","(","cur_thread",")","or","MSS",".","_display_dict",".","get","(","main_thread",")","if","not","display",":","display","=","MSS",".","_display_dict","[","cur_thread","]","=","self",".","xlib",".","XOpenDisplay","(","disp",")","return","display"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L335-L350"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS._set_cfunctions","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set all ctypes functions and attach them to attributes.","docstring_summary":"Set all ctypes functions and attach them to attributes.","docstring_tokens":["Set","all","ctypes","functions","and","attach","them","to","attributes","."],"function":"def _set_cfunctions(self):\n        \"\"\" Set all ctypes functions and attach them to attributes. \"\"\"\n\n        cfactory = self._cfactory\n        attrs = {\n            \"xlib\": self.xlib,\n            \"xrandr\": self.xrandr,\n        }\n        for func, (attr, argtypes, restype) in CFUNCTIONS.items():\n            try:\n                cfactory(\n                    attr=attrs[attr],\n                    errcheck=validate,\n                    func=func,\n                    argtypes=argtypes,\n                    restype=restype,\n                )  # type: ignore\n            except AttributeError:\n                pass","function_tokens":["def","_set_cfunctions","(","self",")",":","cfactory","=","self",".","_cfactory","attrs","=","{","\"xlib\"",":","self",".","xlib",",","\"xrandr\"",":","self",".","xrandr",",","}","for","func",",","(","attr",",","argtypes",",","restype",")","in","CFUNCTIONS",".","items","(",")",":","try",":","cfactory","(","attr","=","attrs","[","attr","]",",","errcheck","=","validate",",","func","=","func",",","argtypes","=","argtypes",",","restype","=","restype",",",")","# type: ignore","except","AttributeError",":","pass"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L352-L370"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS.get_error_details","parameters":"(self)","argument_list":"","return_statement":"return details","docstring":"Get more information about the latest X server error.","docstring_summary":"Get more information about the latest X server error.","docstring_tokens":["Get","more","information","about","the","latest","X","server","error","."],"function":"def get_error_details(self):\n        # type: () -> Optional[Dict[str, Any]]\n        \"\"\" Get more information about the latest X server error. \"\"\"\n\n        details = {}  # type: Dict[str, Any]\n\n        if ERROR.details:\n            details = {\"xerror_details\": ERROR.details}\n            ERROR.details = None\n            xserver_error = ctypes.create_string_buffer(1024)\n            self.xlib.XGetErrorText(\n                self._get_display(),\n                details.get(\"xerror_details\", {}).get(\"error_code\", 0),\n                xserver_error,\n                len(xserver_error),\n            )\n            xerror = xserver_error.value.decode(\"utf-8\")\n            if xerror != \"0\":\n                details[\"xerror\"] = xerror\n\n        return details","function_tokens":["def","get_error_details","(","self",")",":","# type: () -> Optional[Dict[str, Any]]","details","=","{","}","# type: Dict[str, Any]","if","ERROR",".","details",":","details","=","{","\"xerror_details\"",":","ERROR",".","details","}","ERROR",".","details","=","None","xserver_error","=","ctypes",".","create_string_buffer","(","1024",")","self",".","xlib",".","XGetErrorText","(","self",".","_get_display","(",")",",","details",".","get","(","\"xerror_details\"",",","{","}",")",".","get","(","\"error_code\"",",","0",")",",","xserver_error",",","len","(","xserver_error",")",",",")","xerror","=","xserver_error",".","value",".","decode","(","\"utf-8\"",")","if","xerror","!=","\"0\"",":","details","[","\"xerror\"","]","=","xerror","return","details"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L372-L392"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS._monitors_impl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get positions of monitors. It will populate self._monitors.","docstring_summary":"Get positions of monitors. It will populate self._monitors.","docstring_tokens":["Get","positions","of","monitors",".","It","will","populate","self",".","_monitors","."],"function":"def _monitors_impl(self):\n        # type: () -> None\n        \"\"\" Get positions of monitors. It will populate self._monitors. \"\"\"\n\n        display = self._get_display()\n        int_ = int\n        xrandr = self.xrandr\n\n        # All monitors\n        gwa = XWindowAttributes()\n        self.xlib.XGetWindowAttributes(display, self.root, ctypes.byref(gwa))\n        self._monitors.append(\n            {\n                \"left\": int_(gwa.x),\n                \"top\": int_(gwa.y),\n                \"width\": int_(gwa.width),\n                \"height\": int_(gwa.height),\n            }\n        )\n\n        # Each monitor\n        # A simple benchmark calling 10 times those 2 functions:\n        # XRRGetScreenResources():        0.1755971429956844 s\n        # XRRGetScreenResourcesCurrent(): 0.0039125580078689 s\n        # The second is faster by a factor of 44! So try to use it first.\n        try:\n            mon = xrandr.XRRGetScreenResourcesCurrent(display, self.drawable).contents\n        except AttributeError:\n            mon = xrandr.XRRGetScreenResources(display, self.drawable).contents\n\n        crtcs = mon.crtcs\n        for idx in range(mon.ncrtc):\n            crtc = xrandr.XRRGetCrtcInfo(display, mon, crtcs[idx]).contents\n            if crtc.noutput == 0:\n                xrandr.XRRFreeCrtcInfo(crtc)\n                continue\n\n            self._monitors.append(\n                {\n                    \"left\": int_(crtc.x),\n                    \"top\": int_(crtc.y),\n                    \"width\": int_(crtc.width),\n                    \"height\": int_(crtc.height),\n                }\n            )\n            xrandr.XRRFreeCrtcInfo(crtc)\n        xrandr.XRRFreeScreenResources(mon)","function_tokens":["def","_monitors_impl","(","self",")",":","# type: () -> None","display","=","self",".","_get_display","(",")","int_","=","int","xrandr","=","self",".","xrandr","# All monitors","gwa","=","XWindowAttributes","(",")","self",".","xlib",".","XGetWindowAttributes","(","display",",","self",".","root",",","ctypes",".","byref","(","gwa",")",")","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","gwa",".","x",")",",","\"top\"",":","int_","(","gwa",".","y",")",",","\"width\"",":","int_","(","gwa",".","width",")",",","\"height\"",":","int_","(","gwa",".","height",")",",","}",")","# Each monitor","# A simple benchmark calling 10 times those 2 functions:","# XRRGetScreenResources():        0.1755971429956844 s","# XRRGetScreenResourcesCurrent(): 0.0039125580078689 s","# The second is faster by a factor of 44! So try to use it first.","try",":","mon","=","xrandr",".","XRRGetScreenResourcesCurrent","(","display",",","self",".","drawable",")",".","contents","except","AttributeError",":","mon","=","xrandr",".","XRRGetScreenResources","(","display",",","self",".","drawable",")",".","contents","crtcs","=","mon",".","crtcs","for","idx","in","range","(","mon",".","ncrtc",")",":","crtc","=","xrandr",".","XRRGetCrtcInfo","(","display",",","mon",",","crtcs","[","idx","]",")",".","contents","if","crtc",".","noutput","==","0",":","xrandr",".","XRRFreeCrtcInfo","(","crtc",")","continue","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","crtc",".","x",")",",","\"top\"",":","int_","(","crtc",".","y",")",",","\"width\"",":","int_","(","crtc",".","width",")",",","\"height\"",":","int_","(","crtc",".","height",")",",","}",")","xrandr",".","XRRFreeCrtcInfo","(","crtc",")","xrandr",".","XRRFreeScreenResources","(","mon",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L394-L440"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS._grab_impl","parameters":"(self, monitor)","argument_list":"","return_statement":"return self.cls_image(data, monitor)","docstring":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_summary":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_tokens":["Retrieve","all","pixels","from","a","monitor",".","Pixels","have","to","be","RGB","."],"function":"def _grab_impl(self, monitor):\n        # type: (Monitor) -> ScreenShot\n        \"\"\" Retrieve all pixels from a monitor. Pixels have to be RGB. \"\"\"\n\n        ximage = self.xlib.XGetImage(\n            self._get_display(),\n            self.drawable,\n            monitor[\"left\"],\n            monitor[\"top\"],\n            monitor[\"width\"],\n            monitor[\"height\"],\n            PLAINMASK,\n            ZPIXMAP,\n        )\n\n        try:\n            bits_per_pixel = ximage.contents.bits_per_pixel\n            if bits_per_pixel != 32:\n                raise ScreenShotError(\n                    \"[XImage] bits per pixel value not (yet?) implemented: {}.\".format(\n                        bits_per_pixel\n                    )\n                )\n\n            raw_data = ctypes.cast(\n                ximage.contents.data,\n                POINTER(c_ubyte * monitor[\"height\"] * monitor[\"width\"] * 4),\n            )\n            data = bytearray(raw_data.contents)\n        finally:\n            # Free\n            self.xlib.XDestroyImage(ximage)\n\n        return self.cls_image(data, monitor)","function_tokens":["def","_grab_impl","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot","ximage","=","self",".","xlib",".","XGetImage","(","self",".","_get_display","(",")",",","self",".","drawable",",","monitor","[","\"left\"","]",",","monitor","[","\"top\"","]",",","monitor","[","\"width\"","]",",","monitor","[","\"height\"","]",",","PLAINMASK",",","ZPIXMAP",",",")","try",":","bits_per_pixel","=","ximage",".","contents",".","bits_per_pixel","if","bits_per_pixel","!=","32",":","raise","ScreenShotError","(","\"[XImage] bits per pixel value not (yet?) implemented: {}.\"",".","format","(","bits_per_pixel",")",")","raw_data","=","ctypes",".","cast","(","ximage",".","contents",".","data",",","POINTER","(","c_ubyte","*","monitor","[","\"height\"","]","*","monitor","[","\"width\"","]","*","4",")",",",")","data","=","bytearray","(","raw_data",".","contents",")","finally",":","# Free","self",".","xlib",".","XDestroyImage","(","ximage",")","return","self",".","cls_image","(","data",",","monitor",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L442-L475"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/tools.py","language":"python","identifier":"to_png","parameters":"(data, size, level=6, output=None)","argument_list":"","return_statement":"return None","docstring":"Dump data to a PNG file.  If `output` is `None`, create no file but return\n    the whole PNG data.\n\n    :param bytes data: RGBRGB...RGB data.\n    :param tuple size: The (width, height) pair.\n    :param int level: PNG compression level.\n    :param str output: Output file name.","docstring_summary":"Dump data to a PNG file.  If `output` is `None`, create no file but return\n    the whole PNG data.","docstring_tokens":["Dump","data","to","a","PNG","file",".","If","output","is","None","create","no","file","but","return","the","whole","PNG","data","."],"function":"def to_png(data, size, level=6, output=None):\n    # type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]\n    \"\"\"\n    Dump data to a PNG file.  If `output` is `None`, create no file but return\n    the whole PNG data.\n\n    :param bytes data: RGBRGB...RGB data.\n    :param tuple size: The (width, height) pair.\n    :param int level: PNG compression level.\n    :param str output: Output file name.\n    \"\"\"\n    # pylint: disable=too-many-locals\n\n    pack = struct.pack\n    crc32 = zlib.crc32\n\n    width, height = size\n    line = width * 3\n    png_filter = pack(\">B\", 0)\n    scanlines = b\"\".join(\n        [png_filter + data[y * line : y * line + line] for y in range(height)]\n    )\n\n    magic = pack(\">8B\", 137, 80, 78, 71, 13, 10, 26, 10)\n\n    # Header: size, marker, data, CRC32\n    ihdr = [b\"\", b\"IHDR\", b\"\", b\"\"]\n    ihdr[2] = pack(\">2I5B\", width, height, 8, 2, 0, 0, 0)\n    ihdr[3] = pack(\">I\", crc32(b\"\".join(ihdr[1:3])) & 0xFFFFFFFF)\n    ihdr[0] = pack(\">I\", len(ihdr[2]))\n\n    # Data: size, marker, data, CRC32\n    idat = [b\"\", b\"IDAT\", zlib.compress(scanlines, level), b\"\"]\n    idat[3] = pack(\">I\", crc32(b\"\".join(idat[1:3])) & 0xFFFFFFFF)\n    idat[0] = pack(\">I\", len(idat[2]))\n\n    # Footer: size, marker, None, CRC32\n    iend = [b\"\", b\"IEND\", b\"\", b\"\"]\n    iend[3] = pack(\">I\", crc32(iend[1]) & 0xFFFFFFFF)\n    iend[0] = pack(\">I\", len(iend[2]))\n\n    if not output:\n        # Returns raw bytes of the whole PNG data\n        return magic + b\"\".join(ihdr + idat + iend)\n\n    with open(output, \"wb\") as fileh:\n        fileh.write(magic)\n        fileh.write(b\"\".join(ihdr))\n        fileh.write(b\"\".join(idat))\n        fileh.write(b\"\".join(iend))\n\n        # Force write of file to disk\n        fileh.flush()\n        os.fsync(fileh.fileno())\n\n    return None","function_tokens":["def","to_png","(","data",",","size",",","level","=","6",",","output","=","None",")",":","# type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]","# pylint: disable=too-many-locals","pack","=","struct",".","pack","crc32","=","zlib",".","crc32","width",",","height","=","size","line","=","width","*","3","png_filter","=","pack","(","\">B\"",",","0",")","scanlines","=","b\"\"",".","join","(","[","png_filter","+","data","[","y","*","line",":","y","*","line","+","line","]","for","y","in","range","(","height",")","]",")","magic","=","pack","(","\">8B\"",",","137",",","80",",","78",",","71",",","13",",","10",",","26",",","10",")","# Header: size, marker, data, CRC32","ihdr","=","[","b\"\"",",","b\"IHDR\"",",","b\"\"",",","b\"\"","]","ihdr","[","2","]","=","pack","(","\">2I5B\"",",","width",",","height",",","8",",","2",",","0",",","0",",","0",")","ihdr","[","3","]","=","pack","(","\">I\"",",","crc32","(","b\"\"",".","join","(","ihdr","[","1",":","3","]",")",")","&","0xFFFFFFFF",")","ihdr","[","0","]","=","pack","(","\">I\"",",","len","(","ihdr","[","2","]",")",")","# Data: size, marker, data, CRC32","idat","=","[","b\"\"",",","b\"IDAT\"",",","zlib",".","compress","(","scanlines",",","level",")",",","b\"\"","]","idat","[","3","]","=","pack","(","\">I\"",",","crc32","(","b\"\"",".","join","(","idat","[","1",":","3","]",")",")","&","0xFFFFFFFF",")","idat","[","0","]","=","pack","(","\">I\"",",","len","(","idat","[","2","]",")",")","# Footer: size, marker, None, CRC32","iend","=","[","b\"\"",",","b\"IEND\"",",","b\"\"",",","b\"\"","]","iend","[","3","]","=","pack","(","\">I\"",",","crc32","(","iend","[","1","]",")","&","0xFFFFFFFF",")","iend","[","0","]","=","pack","(","\">I\"",",","len","(","iend","[","2","]",")",")","if","not","output",":","# Returns raw bytes of the whole PNG data","return","magic","+","b\"\"",".","join","(","ihdr","+","idat","+","iend",")","with","open","(","output",",","\"wb\"",")","as","fileh",":","fileh",".","write","(","magic",")","fileh",".","write","(","b\"\"",".","join","(","ihdr",")",")","fileh",".","write","(","b\"\"",".","join","(","idat",")",")","fileh",".","write","(","b\"\"",".","join","(","iend",")",")","# Force write of file to disk","fileh",".","flush","(",")","os",".","fsync","(","fileh",".","fileno","(",")",")","return","None"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/tools.py#L15-L70"}
{"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"docs\/source\/examples\/callback.py","language":"python","identifier":"on_exists","parameters":"(fname)","argument_list":"","return_statement":"","docstring":"Callback example when we try to overwrite an existing screenshot.","docstring_summary":"Callback example when we try to overwrite an existing screenshot.","docstring_tokens":["Callback","example","when","we","try","to","overwrite","an","existing","screenshot","."],"function":"def on_exists(fname):\n    # type: (str) -> None\n    \"\"\"\n    Callback example when we try to overwrite an existing screenshot.\n    \"\"\"\n\n    if os.path.isfile(fname):\n        newfile = fname + \".old\"\n        print(\"{} -> {}\".format(fname, newfile))\n        os.rename(fname, newfile)","function_tokens":["def","on_exists","(","fname",")",":","# type: (str) -> None","if","os",".","path",".","isfile","(","fname",")",":","newfile","=","fname","+","\".old\"","print","(","\"{} -> {}\"",".","format","(","fname",",","newfile",")",")","os",".","rename","(","fname",",","newfile",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/docs\/source\/examples\/callback.py#L14-L23"}