o
    'hx                  
   @   s>  U d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZ ddlmZ ddlmZ ddlm Z ddlmZ ed	d
 edD ZdZeed< zddlZddlZdZW n	 eyn   Y nw ejd dkZdZejdkrddlZzejj !  W n	 e"y   Y nw zddl#Z#W n ey   dZY nw dZdZ$dZ%dZ&zej'drej(ddgej)ej)dZ*e*+ dkZ&W n e,y Z- ze-jej.krn W Y dZ-[-ndZ-[-ww dZ/zej'drej(ddgej)ej)dZ*e*+ dkZ/W n e,y Z- ze-jej.krn W Y dZ-[-ndZ-[-ww ej'drLdZ0dZ1ej23ddkr4dZ0dZ1nej23ddkrBdZ1dZ0n
dej2v rLdZ1dZ0ejdkr_ddlmZ e
dYddZ4e5ddZ6e5dd Z7e5d!d"Z8G d#d$ d$e9Z:G d%d& d&e:Z;d'd( Z<dZd)d*Z=d[d.d/Z>d\d0d1Z?d2d3 Z@dYd4d5ZAd6d7 ZBd8d9 ZCd:d; ZDd<d= ZEe<d>d? ZFe<d@dA ZGd]dDdEZHd^dFdGZId_dHdIZJd_dJdKZKdLdM ZLdNdO ZMdPdQ ZNdYdRdSZOdTdU ZPejdVkreJZQnejdkreIZQnej'dreKZQneRdWej e?ZSere>ZSesej dXk re?ZSdS dS dS dS )`z1.0.1    N)contextmanager)Image)ImageOps)	ImageDraw)__version__)	ImageGrabc                 C      g | ]}t |qS  int).0xr	   r	   i/Users/merlin/projects/employee-monitoring-system/venv/lib/python3.10/site-packages/pyscreeze/__init__.py
<listcomp>       r   .F
_useOpenCVT   win32linuxwhichgnome-screenshot)stdoutstderrscrotZXDG_SESSION_TYPEZx11ZwaylandZWAYLAND_DISPLAY)windllc              
   c   s    t j| }|dkrtdz|V  W tjtjgt jj_t j| |dkr*tddS tjtjgt jj_t j| |dkrBtdw )a   
        A context manager for handling calling GetDC() and ReleaseDC().

        This is used for win32 API calls, used by the pixel() function
        on Windows.

        Args:
            hWnd (int): The handle for the window to get a device context
        of, defaults to 0
        r   z(windll.user32.GetDC failed : return NULLz)windll.user32.ReleaseDC failed : return 0N)r   user32ZGetDCWindowsErrorctypesZ	c_ssize_tZ	ReleaseDCargtypes)ZhWndZhDCr	   r	   r   __win32_openDCn   s   
r    Boxzleft top width heightPointzx yRGBzred green bluec                   @      e Zd ZdZdS )PyScreezeExceptionzPyScreezeException is a generic exception class raised when a
    PyScreeze-related error happens. If a PyScreeze function raises an
    exception that isn't PyScreezeException or a subclass, assume it is
    a bug in PyScreeze.N__name__
__module____qualname____doc__r	   r	   r	   r   r%          r%   c                   @   r$   )ImageNotFoundExceptionzImageNotFoundException is an exception class raised when the
    locate functions fail to locate an image. You must set
    pyscreeze.USE_IMAGE_NOT_FOUND_EXCEPTION to True to enable this feature.
    Otherwise, the locate functions will return None.Nr&   r	   r	   r	   r   r,      r+   r,   c                    s   t   fdd}|S )z
    A decorator that marks a function as requiring PyGetWindow to be installed.
    This raises PyScreezeException if Pillow wasn't imported.
    c                     s   t rtd | i |S )Nz9The PyGetWindow package is required to use this function.)_PYGETWINDOW_UNAVAILABLEr%   )argskwargswrappedFunctionr	   r   wrapper   s   z$requiresPyGetWindow.<locals>.wrapper)	functoolswraps)r1   r2   r	   r0   r   requiresPyGetWindow   s   r5   c                 C   s   |du rt }t| tr(|rt| tj}nt| tj}|du r&td|  |S t| tj	rD|r@t
| jdkr@t| tj}|S | }|S t| drlt| d}|dddddddf  }|rjt|tj}|S td)
    TODO
    NzkFailed to read %s because file is missing, has improper permissions, or is an unsupported or invalid format   convertr#   z<expected an image filename, OpenCV numpy array, or PIL image)GRAYSCALE_DEFAULT
isinstancestrcv2ZimreadZIMREAD_GRAYSCALEZIMREAD_COLORIOErrornumpyZndarraylenshapeZcvtColorZCOLOR_BGR2GRAYhasattrarrayr8   copy	TypeError)Zimg	grayscaleZimg_cvZ	img_arrayr	   r	   r   	_load_cv2   s4   	
	
 rG   '     +?c                 c   s   |du rt }t|}t| |} | jdd \}}t||}|r;||d |d |d  |d |d |d  f }nd}|jd | jd k sQ|jd | jd k rUtd|dkrv|d9 }| dd|dd|f } |dd|dd|f }nd}t|| tj}	t	|	j
|	|k  }
t|
d| |	j}t|d dkrtrtd	|	  dS |d | |d  }|d | |d  }t||D ]\}}t||||V  qdS )
a  
    TODO - rewrite this
        faster but more memory-intensive than pure python
        step 2 skips every other row and column = ~3x faster but prone to miss;
            to compensate, the algorithm automatically reduces the confidence
            threshold by 5% (which helps but will not avoid all misses).
        limitations:
          - OpenCV 3.x & python 3.x not tested
          - RGBA images are treated as RBG (ignores alpha channel)
    Nr   rI   r7   r   r   r   zBneedle dimension(s) exceed the haystack image or region dimensionsgffffff?z6Could not locate the image (highest confidence = %.3f))r:   floatrG   rA   
ValueErrorr=   ZmatchTemplateZTM_CCOEFF_NORMEDr?   ZarangesizeflattenZunravel_indexr@   USE_IMAGE_NOT_FOUND_EXCEPTIONr,   maxzipr!   )needleImagehaystackImagerF   limitregionstep
confidenceneedleHeightneedleWidthresultZmatch_indicesmatchesmatchxZmatchyr   yr	   r	   r   _locateAll_opencv   s:   

6(r_   c                 #   s   |dur	t d|du rt}d}t| tr t| d}t|} d}t|tr1t|d}t|}|durO||d |d |d |d  |d |d  f}nd}|r^t| } t|}n| j	d	krh| 
d
} |j	d	krr|
d
}| j\}	|j\}
}t|   t| } fddt|	D }|d }t|ksJ ddd |D g|	 ksJ dd}d}|dkrt}nt}t|D ]x}|||||
 |d |
  |D ]e}d}td|	|D ]#}|| |
 | } | |d   |||  krd} nq|r:|d7 }t||d  ||d  |	V  |dur:||kr:|dur-|  |dur6|    dS qq|durE|  |durN|  |dkr\trZtddS dS )r6   NzIThe confidence keyword argument is only available if OpenCV is installed.rbr   rI   r   r7   rK   ZRGBAr#   c                    s$   g | ]} | |d    qS )rI   r	   )r   r^   ZneedleImageDatarZ   r	   r   r   9  s    z%_locateAll_pillow.<locals>.<listcomp>z`The calculated width of first row of the needle image is not the same as the width of the image.c                 S   r   r	   )r@   )r   rowr	   r	   r   r   A  r   z?The needleImageRows aren't the same size as the original image.TFCould not locate the image.)NotImplementedErrorr:   r;   r<   openr   cropr   rF   moder8   rN   tupleZgetdataranger@   _kmp_steppingFindr!   closerP   r,   )rS   rT   rF   rU   rV   rW   rX   ZneedleFileObjZhaystackFileObjrY   ZhaystackWidthZhaystackHeightZhaystackImageDataZneedleImageRowsZneedleImageFirstRowZnumMatchesFoundZfirstFindFuncr^   r]   
foundMatchZsearchyZhaystackStartr	   ra   r   _locateAll_pillow  s   





4






 




rn   c                 K   sB   d|d< t t| |fi |}t|dkr|d S trtddS )r6   rI   rU   r   rc   N)rh   	locateAllr@   rP   r,   )rS   rT   r/   Zpointsr	   r	   r   locatex  s   rp   c                 K   s   t   }	 z.tdd}t| |fi |}z|j  W n	 ty$   Y nw |s/t   | |kr2|W S W n tyJ   t   | |krHtrE Y dS Y nw q)zTODO - rewrite this
    minSearchTime - amount of time in seconds to repeat taking
    screenshots and trying to locate a match.  The default of 0 performs
    a single search.
    TNrV   )time
screenshotrp   fprl   AttributeErrorr,   rP   )imageZminSearchTimer/   startscreenshotImretValr	   r	   r   locateOnScreen  s*   
rz   c                 K   sB   t dd}t| |fi |}z|j  W |S  ty    Y |S w )r6   Nrq   )rs   ro   rt   rl   ru   )rv   r/   rx   ry   r	   r	   r   locateAllOnScreen  s   
r{   c                 K   s$   t | fi |}|du rdS t|S r6   N)rz   center)rv   r/   coordsr	   r	   r   locateCenterOnScreen  s   r   c                 C   s|   t t| }g }d}|D ]-}t|\}}t|| }	t|| }
||	|	 |
|
   |d || k r9t|d }q|| S )r6   r   r9   rI   )listr{   r}   absappendr@   )rv   r   r^   ZfoundMatchesBoxesZdistancesSquaredZshortestDistanceIndexZfoundMatchesBoxZfoundMatchXZfoundMatchYZ	xDistanceZ	yDistancer	   r	   r   locateOnScreenNear  s   r   c                 K   s(   t | ||fi |}|du rdS t|S r|   )r   r}   )rv   r   r^   r/   r~   r	   r	   r   locateCenterOnScreenNear  s   r   c                 K   s|   t |}t|dkrtd| t|dkr$td|dd |D f |d }|  t| fd|j|j|j|j	fi|S )r6   r   z,Could not find a window with %s in the titlerI   z/Found multiple windows with %s in the title: %sc                 S   r   r	   )r<   )r   winr	   r	   r   r     r   z"locateOnWindow.<locals>.<listcomp>rV   )
pygetwindowZgetWindowsWithTitler@   r%   activaterz   lefttopwidthheight)rv   titler/   ZmatchingWindowsr   r	   r	   r   locateOnWindow  s   
$r   c                 C   s   dS r|   r	   )r   r	   r	   r   screenshotWindow  s   r   red_showRegionOnScreen.pngc                 C   sX   t  }t|}| d | d | d | d  | d | d  f} |j| |d || dS )r6   r   rI   r   r7   )outlineN)rs   r   ZDrawZ	rectanglesave)rV   ZoutlineColorfilenamerx   Zdrawr	   r	   r   showRegionOnScreen  s   
r   c                 C   s   t j|d}|durMt|dksJ dt|d tr0t|d tr0t|d tr0t|d ts4J d||d |d |d |d  |d |d  f}| durV||  |S )	r6   )Zall_screensN   ,region argument must be a tuple of four intsr   rI   r   r7   )r   grabr@   r;   r   rf   r   )imageFilenamerV   Z
allScreensimr	   r	   r   _screenshot_win32  s   @2
r   c                 C   sR  t dk r| du rdtj d }n| }tdd|g t|}|durtt|dks0J dt	|d	 t
rLt	|d
 t
rLt	|d t
rLt	|d t
sPJ d||d	 |d
 |d |d	  |d |d
  f}t| || n|  | du rt| |S |durtj|d	 |d
 |d |d	  |d |d
  fd}|S t }|S )r6   )   r   rI   Nzscreenshot%s.png%Y-%m%d_%H-%M-%S-%fZscreencapturez-xr   r   r   rI   r   r7   )Zbbox)PILLOW_VERSIONdatetimenowstrftime
subprocesscallr   re   r@   r;   r   rf   osunlinkr   loadr   r   r   rV   ZtmpFilenamer   r	   r	   r   _screenshot_osx$  s*   
@2

4r   c                 C   s  | du rdt j  d }n| }tdkrotrot }| dur$||  |du r*|S t|dks4J dt	|d t
rPt	|d t
rPt	|d	 t
rPt	|d
 t
sTJ d||d |d |d	 |d  |d
 |d  f}|S tr|tr|tdd|g ntrtdd|g ntrtrtstdtdt|}|durt|dksJ dt	|d t
rt	|d t
rt	|d	 t
rt	|d
 t
sJ d||d |d |d	 |d  |d
 |d  f}t| || n|  | du rt| |S )r6   Nz.screenshot%s.pngr   )	   r   r   r   r   r   rI   r   r7   r   z-zr   z-fzYour computer uses the Wayland window system. Scrot works on the X11 window system but not Wayland. You must install gnome-screenshot by running `sudo apt install gnome-screenshot`zTo take screenshots, you must install Pillow version 9.2.0 or greater and gnome-screenshot by running `sudo apt install gnome-screenshot`)r   r   r   r   GNOMESCREENSHOT_EXISTSr   r   r   r@   r;   r   rf   RUNNING_X11SCROT_EXISTSr   r   RUNNING_WAYLANDr%   	Exceptionr   re   r   r   r   r   r	   r	   r   _screenshot_linuxJ  sF   
@2
@2

r   c           	      c   s   dgt | d  }d}tt | D ],}||kr8| | | ||  kr8||||  7 }||kr8| | | ||  ks"|||d < qd}d}|D ];}|t | ksW|dkrs| | |krs||| 7 }||| 8 }|t | ksW|dkrs| | |ksW|d7 }|t | kr|V  qEdS )r6   rI   r   N)r@   ri   )	needlehaystackZ_dummyZshiftsshiftposstartPosmatchLencr	   r	   r   rj     s(     rj   c                 c   sf    t dt|t|  d D ]"}d}t dt| |D ]}|||  | | kr*d} nq|r0|V  qdS )r6   r   rI   TFN)ri   r@   )r   r   rW   r   rm   r   r	   r	   r   rk     s   rk   c                 C   s2   t | d t| d d  | d t| d d  S )am  
    Returns a `Point` object with the x and y set to an integer determined by the format of `coords`.

    The `coords` argument is a 4-integer tuple of (left, top, width, height).

    For example:

    >>> center((10, 10, 6, 8))
    Point(x=13, y=14)
    >>> center((10, 10, 7, 9))
    Point(x=13, y=14)
    >>> center((10, 10, 8, 10))
    Point(x=14, y=15)
    r   r   rI   r7   )r"   r   )r~   r	   r	   r   r}     s   2r}   c                 C   s   t | tjjrt| dkrtdt| |}t|dks"t|dkrL|dd \}}}|dd \}}	}
t|| |koKt||	 |koKt||
 |kS t|dkrt|dkr|\}}}}|\}}	}
}t|| |kot||	 |kot||
 |kot|| |kS J dt|t|f )z
    Return True if the pixel at x, y is matches the expected color of the RGB
    tuple, each color represented from 0 to 255, within an optional tolerance.
    r   zpixelMatchesColor() has updated and no longer accepts a tuple of (x, y) values for the first argument. Pass these arguments as two separate arguments instead: pixelMatchesColor(x, y, rgb) instead of pixelMatchesColor((x, y), rgb)r7   Nr   FzrColor mode was expected to be length 3 (RGB) or 4 (RGBA), but pixel is length %s and expectedRGBColor is length %s)r;   collectionsabcSequencer@   rE   pixelr   )r   r^   ZexpectedRGBColorZ	toleranceZpixrgbZexRZexGZexBaZexAr	   r	   r   pixelMatchesColor  s,   
0r   c                    s   t | tjjrt| dkrtdtjdkrXt 5}t	j
|| |}|dk r-td|d|  fddtdd	dD \}}}|||fW  d
   S 1 sQw   Y  d
S tt | |fd
d  S )zn
    Returns the color of the screen pixel at x, y as an RGB tuple, each color represented from 0 to 255.
    r   zpixel() has updated and no longer accepts a tuple of (x, y) values for the first argument. Pass these arguments as two separate arguments instead: pixel(x, y) instead of pixel((x, y))r   r   z(windll.gdi32.GetPixel failed : return {}z{:0>6x}c                 3   s&    | ]}t  ||d   dV  qdS )r      Nr
   )r   iZbbggrrr	   r   	<genexpr>  s   $ zpixel.<locals>.<genexpr>r   Nr7   )r;   r   r   r   r@   rE   sysplatformr    r   Zgdi32ZGetPixelr   formatri   r#   rs   Zgetpixel)r   r^   Zhdccolorr   r   r   r	   r   r   r     s   

 $r   darwinz'PyScreeze is not supported on platform 3)r   )N)NrH   NrI   rJ   )NNNrI   N)r   r   )NNF)NN)Tr   r   r   r3   r   r   r   rr   errno
contextlibr   ZPILr   r   r   ZPIL__version__r   rh   splitr   r   bool__annotations__r=   r?   ImportErrorversion_infoZRUNNING_PYTHON_2r-   r   r   r   r   ZSetProcessDPIAwareru   r   r:   rP   r   
startswithPopenPIPEZ	whichProcwaitOSErrorexENOENTr   r   r   environgetr    
namedtupler!   r"   r#   r   r%   r,   r5   rG   r_   rn   rp   rz   r{   r   r   r   r   r   r   r   r   r   rj   rk   r}   r   r   rs   rd   ro   r	   r	   r	   r   <module>   s   
			

,
5l






&?
#