a
    #©b­X  ã                   @   sæ   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ZdZ	dZ
dd	d
dddœZdd„ Zdd„ ZG dd„ dejƒZG dd„ deƒZG dd„ dƒZd$dd„Zdd„ ZG dd„ dƒZG dd„ dƒZG d d!„ d!eƒZG d"d#„ d#eƒZdS )%é    Né   )ÚImage)ÚisPathi   i   Fzimage buffer overrun errorzdecoding errorzunknown errorzbad configurationzout of memory error)éÿÿÿÿéþÿÿÿéýÿÿÿéøÿÿÿi÷ÿÿÿc                 C   sL   zt j | ¡}W n ty,   t | ¡}Y n0 |s<d| › �}t|d ƒ‚d S )Nzdecoder error z when reading image file)r   ÚcoreZgetcodecstatusÚAttributeErrorÚERRORSÚgetÚOSError)ÚerrorÚmessage© r   úV/home/yuhw/wc/wire-cell-python-pr-11/pr11/lib/python3.9/site-packages/PIL/ImageFile.pyÚraise_oserror@   s    
r   c                 C   s   | d S )Né   r   )Útr   r   r   Ú	_tilesortJ   s    r   c                       sR   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
‡  ZS )Ú	ImageFilez*Base class for image file format handlers.Nc                    s  t ƒ  ¡  d| _d | _d | _d| _d| _t| _t	|ƒrPt
|dƒ| _|| _d| _n|| _|| _d | _zvz|  ¡  W n: tttttjfyª } zt|ƒ|‚W Y d }~n
d }~0 0 | jrÎ| jd dksÎ| jd dkrÖtdƒ‚W n$ tyü   | jrö| j ¡  ‚ Y n0 d S )Nr   r   r   ÚrbTznot identified by this driver)ÚsuperÚ__init__Ú
_min_frameÚcustom_mimetypeÚtileÚreadonlyÚdecoderconfigÚMAXBLOCKÚdecodermaxblockr   ÚopenÚfpÚfilenameÚ_exclusive_fpÚ_openÚ
IndexErrorÚ	TypeErrorÚKeyErrorÚEOFErrorÚstructr   ÚSyntaxErrorÚmodeÚsizeÚBaseExceptionÚclose)Úselfr"   r#   Úv©Ú	__class__r   r   r   W   s>    
û "
zImageFile.__init__c                 C   s,   | j r| j S | jd ur(tj | j ¡ ¡S d S ©N)r   Úformatr   ZMIMEr   Úupper©r0   r   r   r   Úget_format_mimetype†   s    
zImageFile.get_format_mimetypec                 C   s   | j r| j ¡  d| _dS )zCheck file integrityN)r$   r"   r/   r7   r   r   r   ÚverifyŒ   s    
zImageFile.verifyc                 C   s–  | j du rtdƒ‚tj | ¡}| j s(|S d| _| jo@t| j ƒdk}|oPttdƒ }d}z| j	}d}W n t
y~   | jj}Y n0 z| j}d}W n t
y¨   | jj}Y n0 |�rš| j d \}}}}	|dk�ršt|	ƒdk�rš|	d | jk�rš|	d tjv �ršz~ddl}
t| jƒ�(}|
j| ¡ d|
jd	�| _W d  ƒ n1 �s>0    Y  tj | j| j|||	¡| _d}| j�rvd| j_W n  t
ttf�y˜   d| _Y n0 |  ¡  d
}| j�s6| j jtd� z
| j}W n t
�yÞ   d}Y n0 dd„ t  !| j dd„ ¡D ƒ| _ | j D �].\}}}}	||ƒ t "| j||	| j#¡}zø| $| j|¡ |j%�rb| &| j¡ | 'd¡d }nº|}z|| j(ƒ}W nL t)t*j+f�yÀ } z,t,�r¢W Y d}~�qn
tdƒ|‚W Y d}~n
d}~0 0 |�sèt,�rÔ�qntdt|ƒ› d�ƒ‚|| }| '|¡\}}|dk �r�q||d… }�qfW | -¡  n
| -¡  0 �qg | _ || _.|  /¡  | j0�rd| j1�rd| j 2¡  d| _| j�sŠt,�sŠ|dk �rŠt3|ƒ tj | ¡S )z"Load image data based on tile listNzcannot load this imager   Úpypy_version_infor   FÚrawé   )Úaccessr   ©Úkeyó    c                 S   s   g | ]\}}t |ƒd  ‘qS )r   )Úlist)Ú.0Ú_Ztilesr   r   r   Ú
<listcomp>Û   s   ÿz"ImageFile.load.<locals>.<listcomp>c                 S   s   | d | d | d fS )Nr   r   r<   r   )r   r   r   r   Ú<lambda>Þ   r@   z ImageFile.load.<locals>.<lambda>zimage file is truncatedzimage file is truncated (z bytes not processed))4r   r   r   ÚloadÚmapr#   ÚlenÚhasattrÚsysÚ	load_readr
   r"   ÚreadÚ	load_seekÚseekr,   Z	_MAPMODESÚmmapr!   ÚfilenoZACCESS_READr	   Z
map_bufferr-   ÚimZpaletteZdirtyÚImportErrorÚload_prepareÚsortr   Ztile_prefixÚ	itertoolsÚgroupbyÚ_getdecoderr   ÚsetimageÚpulls_fdÚsetfdÚdecoder    r&   r*   r   ÚLOAD_TRUNCATED_IMAGESÚcleanupr   Úload_endr$   Z!_close_exclusive_fp_after_loadingr/   r   )r0   ZpixelZuse_mmapr   rL   rN   Zdecoder_nameÚextentsÚoffsetÚargsrO   r"   Zerr_codeÚprefixÚdecoderÚbÚsÚeÚnr   r   r   rF   •   s¼    
ÿ
þýü8ÿ


ÿþÿ ÿÿ

zImageFile.loadc                 C   sP   | j r"| j j| jks"| j j| jkr6tj | j| j¡| _ | jdkrLtj | ¡ d S )NÚP)rQ   r,   r-   r   r	   ÚnewrF   r7   r   r   r   rS     s    "
zImageFile.load_preparec                 C   s   d S r4   r   r7   r   r   r   r^      s    zImageFile.load_endc                 C   sB   || j k s.t| dƒr| jd u s6|| j| j  kr6tdƒ‚|  ¡ |kS )NÚ	_n_framesz attempt to seek outside sequence)r   rI   rj   Zn_framesr)   Útell)r0   Úframer   r   r   Ú_seek_check,  s    ÿûûú	zImageFile._seek_check)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r8   r9   rF   rS   r^   rm   Ú__classcell__r   r   r2   r   r   T   s   /	 r   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	ÚStubImageFilez±
    Base class for stub image loaders.

    A stub loader is an image loader that can identify files of a
    certain format, but relies on external code to load the file.
    c                 C   s   t dƒ‚d S )Nz+StubImageFile subclass must implement _open©ÚNotImplementedErrorr7   r   r   r   r%   C  s    zStubImageFile._openc                 C   sP   |   ¡ }|d u r"td| j› d�ƒ‚| | ¡}|d us8J ‚|j| _|j| _| ¡ S )Nzcannot find loader for this z file)Ú_loadr   r5   rF   r3   Ú__dict__)r0   ÚloaderÚimager   r   r   rF   F  s    
zStubImageFile.loadc                 C   s   t dƒ‚dS )z (Hook) Find actual image loader.z+StubImageFile subclass must implement _loadNrt   r7   r   r   r   rv   Q  s    zStubImageFile._loadN)rn   ro   rp   rq   r%   rF   rv   r   r   r   r   rs   ;  s   rs   c                   @   sP   e Zd ZdZdZdZdZdZdZdZ	dd„ Z
dd„ Zdd	„ Zd
d„ Zdd„ ZdS )ÚParserzj
    Incremental image parser.  This class implements the standard
    feed/close consumer interface.
    Nr   c                 C   s   | j du sJ dƒ‚dS )zµ
        (Consumer) Reset the parser.  Note that you can only call this
        method immediately after you've created a parser; parser
        instances cannot be reused.
        Nzcannot reuse parsers)Údatar7   r   r   r   Úresetc  s    zParser.resetc                 C   sà  | j r
dS | jdu r|| _n| j| | _| jrÐ| jdkrztt| jƒ| jƒ}| j|d… | _| j| | _| jdksv| jszdS | j | j¡\}}|dk r¼d| _d| _ |dk r¸d| _t|ƒ ndS | j|d… | _�n| jrÚ�nz<t	 
| j¡�}t |¡}W d  ƒ n1 �s
0    Y  W n t�y*   Y n²0 t|dƒ�p@t|dƒ}|�sXt|jƒdk�r`d| _nv| ¡  |jd \}}}	}
g |_t |j||
|j¡| _| j |j|¡ |	| _| jt| jƒk�rÖ| j| jd… | _d| _|| _dS )z¦
        (Consumer) Feed data to the parser.

        :param data: A string buffer.
        :exception OSError: If the parser failed to parse the image file.
        Nr   r   rM   rK   )Úfinishedr{   rc   r`   ÚminrH   r[   ry   r   ÚioÚBytesIOr   r!   r   rI   r   rS   rW   r,   r   rX   rQ   )r0   r{   Úskiprg   rf   r"   rQ   ÚflagÚdÚoÚar   r   r   Úfeedk  sR    	


.zParser.feedc                 C   s   | S r4   r   r7   r   r   r   Ú	__enter__»  s    zParser.__enter__c                 G   s   |   ¡  d S r4   )r/   ©r0   ra   r   r   r   Ú__exit__¾  s    zParser.__exit__c              	   C   s˜   | j r*|  d¡ d | _| _ | js*tdƒ‚| js8tdƒ‚| jr’t | j¡�8}zt 	|¡| _W | j 
¡  n| j 
¡  0 W d  ƒ n1 sˆ0    Y  | jS )a  
        (Consumer) Close the stream.

        :returns: An image object.
        :exception OSError: If the parser failed to parse the image file either
                            because it cannot be identified or cannot be
                            decoded.
        r@   Nzimage was incompletezcannot parse this image)rc   r†   r{   r}   r   ry   r   r€   r   r!   rF   )r0   r"   r   r   r   r/   Á  s    

6zParser.close)rn   ro   rp   rq   Úincrementalry   r{   rc   r`   r}   r|   r†   r‡   r‰   r/   r   r   r   r   rz   V  s   Prz   c              
   C   sj  |   ¡  t| dƒsd| _|jtd� tt|| jd d ƒ}z| ¡ }| 	¡  d}W n. t
tjfy€ } z|}W Y d}~n
d}~0 0 |D ]Ê\}}}}	|dkr¤| |¡ t | j||	| j¡}
zŒ|
 | j|¡ |
jræ|
 |¡ |
 ¡ \}}n8|�r|
 |¡\}}}| |¡ |rì�qqìn|
 ||¡}|dk �r:td|› d�ƒ|‚W |
 ¡  q†|
 ¡  0 q†t|d	ƒ�rf| 	¡  dS )
z«Helper to save image based on tile list

    :param im: Image object.
    :param fp: File object.
    :param tile: Tile list.
    :param bufsize: Optional buffer size
    Úencoderconfigr   r>   r   é   Nzencoder error z when writing image fileÚflush)rF   rI   r‹   rT   r   Úmaxr   r-   rP   r�   r
   r   ÚUnsupportedOperationrN   r   Z_getencoderr,   rX   rQ   Ú	pushes_fdrZ   Úencode_to_pyfdÚencodeÚwriteÚencode_to_filer   r]   )rQ   r"   r   ÚbufsizeÚfhÚexcrf   rd   r„   r…   ÚencoderÚlre   rƒ   r   r   r   Ú_saveá  s>    	




rš   c                 C   sœ   |dkrdS |t kr6|  |¡}t|ƒ|k r2tdƒ‚|S g }|}|dkrt|  t|t ƒ¡}|s\qt| |¡ |t|ƒ8 }q>tdd„ |D ƒƒ|k r’tdƒ‚d |¡S )a»  
    Reads large blocks in a safe way.  Unlike fp.read(n), this function
    doesn't trust the user.  If the requested size is larger than
    SAFEBLOCK, the file is read block by block.

    :param fp: File handle.  Must implement a <b>read</b> method.
    :param size: Number of bytes to read.
    :returns: A string containing <i>size</i> bytes of data.

    Raises an OSError if the file is truncated and the read cannot be completed

    r   r@   zTruncated File Readc                 s   s   | ]}t |ƒV  qd S r4   )rH   )rB   rƒ   r   r   r   Ú	<genexpr>1  r@   z_safe_read.<locals>.<genexpr>)Ú	SAFEBLOCKrL   rH   r   r~   ÚappendÚsumÚjoin)r"   r-   r{   Zremaining_sizeÚblockr   r   r   Ú
_safe_read  s$    

r¡   c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚPyCodecStatec                 C   s   d| _ d| _d| _d| _d S )Nr   )ÚxsizeÚysizeÚxoffÚyoffr7   r   r   r   r   7  s    zPyCodecState.__init__c                 C   s    | j | j| j | j | j| j fS r4   )r¥   r¦   r£   r¤   r7   r   r   r   r_   =  s    zPyCodecState.extentsN)rn   ro   rp   r   r_   r   r   r   r   r¢   6  s   r¢   c                   @   s6   e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zdd
d„Zd	S )ÚPyCodecc                 G   s(   d | _ tƒ | _d | _|| _|  |¡ d S r4   )rQ   r¢   ÚstateÚfdr,   Úinit)r0   r,   ra   r   r   r   r   B  s
    zPyCodec.__init__c                 C   s
   || _ dS )z˜
        Override to perform codec specific initialization

        :param args: Array of args items from the tile entry
        :returns: None
        N)ra   rˆ   r   r   r   rª   I  s    zPyCodec.initc                 C   s   dS )zT
        Override to perform codec specific cleanup

        :returns: None
        Nr   r7   r   r   r   r]   R  s    zPyCodec.cleanupc                 C   s
   || _ dS )z�
        Called from ImageFile to set the Python file-like object

        :param fd: A Python file-like object
        :returns: None
        N)r©   )r0   r©   r   r   r   rZ   Z  s    zPyCodec.setfdNc                 C   sÖ   || _ |r|\}}}}nd\}}}}|dkrJ|dkrJ| j j\| j_| j_n(|| j_|| j_|| | j_|| | j_| jjdksŠ| jjdkr’tdƒ‚| jj| jj | j jd ksÊ| jj| jj | j jd krÒtdƒ‚dS )zø
        Called from ImageFile to set the core output image for the codec

        :param im: A core image object
        :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
            for this tile
        :returns: None
        )r   r   r   r   r   zSize cannot be negativer   z Tile cannot extend outside imageN)rQ   r-   r¨   r£   r¤   r¥   r¦   Ú
ValueError)r0   rQ   r_   Zx0Zy0Úx1Úy1r   r   r   rX   c  s"    ÿþzPyCodec.setimage)N)rn   ro   rp   r   rª   r]   rZ   rX   r   r   r   r   r§   A  s
   		r§   c                   @   s2   e Zd ZdZdZedd„ ƒZdd„ Zd
dd	„ZdS )Ú	PyDecoderzË
    Python implementation of a format decoder. Override this class and
    add the decoding logic in the :meth:`decode` method.

    See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
    Fc                 C   s   | j S r4   )Ú	_pulls_fdr7   r   r   r   rY   ‘  s    zPyDecoder.pulls_fdc                 C   s
   t ƒ ‚dS )a=  
        Override to perform the decoding process.

        :param buffer: A bytes object with the data to be decoded.
        :returns: A tuple of ``(bytes consumed, errcode)``.
            If finished with decoding return -1 for the bytes consumed.
            Err codes are from :data:`.ImageFile.ERRORS`.
        Nrt   )r0   Úbufferr   r   r   r[   •  s    	zPyDecoder.decodeNc                 C   sd   |s
| j }t | j d|¡}| | j| j ¡ ¡ | |¡}|d dkrLtdƒ‚|d dkr`tdƒ‚dS )a  
        Convenience method to set the internal image from a stream of raw data

        :param data: Bytes to be set
        :param rawmode: The rawmode to be used for the decoder.
            If not specified, it will default to the mode of the image
        :returns: None
        r;   r   znot enough image datar   zcannot decode image dataN)	r,   r   rW   rX   rQ   r¨   r_   r[   r«   )r0   r{   Úrawmoderƒ   re   r   r   r   Ú
set_as_raw   s    

zPyDecoder.set_as_raw)N)	rn   ro   rp   rq   r¯   ÚpropertyrY   r[   r²   r   r   r   r   r®   ‡  s   
r®   c                   @   s8   e Zd ZdZdZedd„ ƒZdd„ Zdd„ Zd	d
„ Z	dS )Ú	PyEncoderzË
    Python implementation of a format encoder. Override this class and
    add the decoding logic in the :meth:`encode` method.

    See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
    Fc                 C   s   | j S r4   )Ú
_pushes_fdr7   r   r   r   r�   À  s    zPyEncoder.pushes_fdc                 C   s
   t ƒ ‚dS )a   
        Override to perform the encoding process.

        :param bufsize: Buffer size.
        :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
            If finished with encoding return 1 for the error code.
            Err codes are from :data:`.ImageFile.ERRORS`.
        Nrt   )r0   r•   r   r   r   r’   Ä  s    	zPyEncoder.encodec                 C   s2   | j s
dS |  d¡\}}}|r*| j |¡ ||fS )zø
        If ``pushes_fd`` is ``True``, then this method will be used,
        and ``encode()`` will only be called once.

        :returns: A tuple of ``(bytes consumed, errcode)``.
            Err codes are from :data:`.ImageFile.ERRORS`.
        )r   r   r   )r�   r’   r©   r“   )r0   Zbytes_consumedÚerrcoder{   r   r   r   r‘   Ï  s    zPyEncoder.encode_to_pyfdc                 C   s<   d}|dkr8|   |¡\}}}|dkr| ||d… ¡ q|S )zì
        :param fh: File handle.
        :param bufsize: Buffer size.

        :returns: If finished successfully, return 0.
            Otherwise, return an error code. Err codes are from
            :data:`.ImageFile.ERRORS`.
        r   N)r’   r“   )r0   r–   r•   r¶   ÚstatusÚbufr   r   r   r”   Þ  s    	zPyEncoder.encode_to_fileN)
rn   ro   rp   rq   rµ   r³   r�   r’   r‘   r”   r   r   r   r   r´   ¶  s   
r´   )r   )r   rU   r*   rJ   Ú r   Z_utilr   r   rœ   r\   r   r   r   r   rs   rz   rš   r¡   r¢   r§   r®   r´   r   r   r   r   Ú<module>   s6   û

 h 
4!F/