B
    ñ¶I`þR  ã               @   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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dS )#é    Né   )ÚImage)ÚisPathi   i   Fzimage buffer overrun errorzdecoding errorzunknown errorzbad configurationzout of memory error)éÿÿÿÿéþÿÿÿéýÿÿÿiøÿÿÿi÷ÿÿÿc             C   sN   yt j | ¡}W n tk
r.   t | ¡}Y nX |s>d| › �}t|d ƒ‚d S )Nzdecoder error z when reading image file)r   ÚcoreZgetcodecstatusÚAttributeErrorÚERRORSÚgetÚOSError)ÚerrorÚmessage© r   ú1/tmp/pip-unpacked-wheel-wndzrte2/PIL/ImageFile.pyÚraise_oserror<   s    
r   c             C   s   t  dt¡ t| ƒS )Nzdraise_ioerror is deprecated and will be removed in Pillow 9 (2022-01-02). Use raise_oserror instead.)ÚwarningsÚwarnÚDeprecationWarningr   )r   r   r   r   Úraise_ioerrorF   s    r   c             C   s   | d S )Né   r   )Útr   r   r   Ú	_tilesortO   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 | _yfy|  ¡  W n8 tttttjfk
r¨ } zt|ƒ|‚W d d }~X Y nX | jr¾| jd dkrÆtdƒ‚W n& tk
rî   | jrè| j ¡  ‚ Y nX 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   \   s<    

zImageFile.__init__c             C   s,   | j r| j S | jd k	r(tj | j ¡ ¡S d S )N)r   Úformatr   ZMIMEr   Úupper)r3   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%   r2   )r3   r   r   r   Úverify‘   s    
zImageFile.verifyc             C   s¦  | j dkrtdƒ‚tj | ¡}| j s(|S d| _| jo@t| j ƒdk}|oPttdƒ }d}y| j	}d}W n t
k
r€   | jj}Y nX y| j}d}W n t
k
r¬   | jj}Y nX |�rÖ| j d \}}}}	|dk�rÖt|	ƒdk�rÖ|	d | jk�rÖ|	d tjk�rÖy´ttjd	ƒ�rLtj | j¡| _| j |¡ | j | j| j|	d |	d
 ¡| _nPddl}
t| jƒ�}|
j| ¡ d|
jd�| _W dQ R X tj | j| j|||	¡| _d}| j�r°d| j_W n" t
ttfk
�rÔ   d| _Y nX |  ¡  d}| j�sF| j jtd� y
| j }W n t
k
�r   d}Y nX �x$| j D �]\}}}}	t !| j||	| j"¡}zê||ƒ | #| j|¡ |j$�r†| %| j¡ | &d¡\}}n¬|}x¦y|| j'ƒ}W n> t(t)j*fk
�rØ } zt+�r¾P n
tdƒ|‚W dd}~X Y nX |�sþt+�rêP ntdt|ƒ› d�ƒ‚|| }| &|¡\}}|dk �r P ||d… }�qŒW W d| ,¡  X �q(W g | _ || _-|  .¡  | j/�rt| j0�rt| j 1¡  d| _| j�sšt+�sš|dk �ršt2|ƒ tj | ¡S )z"Load image data based on tile listNzcannot load this imager   Úpypy_version_infor   FÚrawé   Úmapr   )Úaccessr   )Úkeyó    zimage file is truncatedzimage file is truncated (z bytes not processed))3r   r   r   Úloadr=   r&   ÚlenÚhasattrÚsysÚ	load_readr	   r%   ÚreadÚ	load_seekÚseekr/   Z	_MAPMODESr   Z	readimager0   ÚimÚmmapr$   ÚfilenoZACCESS_READZ
map_bufferZpaletteZdirtyÚImportErrorÚload_prepareÚsortr   Ztile_prefixÚ_getdecoderr!   ÚsetimageÚpulls_fdÚsetfdÚdecoder#   r)   r-   r   ÚLOAD_TRUNCATED_IMAGESÚcleanupr    Úload_endr'   Z!_close_exclusive_fp_after_loadingr2   r   )r3   ZpixelZuse_mmapr    rF   rH   Zdecoder_nameÚextentsÚoffsetÚargsrJ   r%   Zerr_codeÚprefixÚdecoderÚstatusÚbÚsÚeÚnr   r   r   rA   š   s®    





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)rI   r/   r0   r   r   ÚnewrA   )r3   r   r   r   rM      s    "
zImageFile.load_preparec             C   s   d S )Nr   )r3   r   r   r   rV   (  s    zImageFile.load_endc             C   sB   || j k s.t| dƒr| jd ks6|| j| j  kr6tdƒ‚|  ¡ |kS )NÚ	_n_framesz attempt to seek outside sequence)r   rC   rc   Zn_framesr,   Útell)r3   Úframer   r   r   Ú_seek_check4  s
    
zImageFile._seek_check)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r8   r9   rA   rM   rV   rf   Ú__classcell__r   r   )r5   r   r   Y   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)ÚNotImplementedError)r3   r   r   r   r(   K  s    zStubImageFile._openc             C   sL   |   ¡ }|d kr"td| j› d�ƒ‚| | ¡}|d k	s8t‚|j| _|j| _d S )Nzcannot find loader for this z file)Ú_loadr   r6   rA   ÚAssertionErrorr5   Ú__dict__)r3   ÚloaderÚimager   r   r   rA   N  s    
zStubImageFile.loadc             C   s   t dƒ‚dS )z (Hook) Find actual image loader.z+StubImageFile subclass must implement _loadN)rm   )r3   r   r   r   rn   X  s    zStubImageFile._loadN)rg   rh   ri   rj   r(   rA   rn   r   r   r   r   rl   C  s   
rl   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kst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)Údataro   )r3   r   r   r   Úresetj  s    zParser.resetc          	   C   sÈ  | j r
dS | jdk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îy&t	 
| j¡�}t |¡}W dQ R X W n tk
�r   Y n²X t|dƒ�p(t|dƒ}|�s@t|jƒdk�rHd| _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   rG   rE   )Úfinishedrt   r[   rX   ÚminrB   rS   rr   r   ÚioÚBytesIOr   r$   r   rC   r   rM   rO   r/   r!   rP   rI   )r3   rt   Úskipr`   r_   r%   rI   ÚflagÚdÚoÚar   r   r   Úfeedr  sR    	


zParser.feedc             C   s   | S )Nr   )r3   r   r   r   Ú	__enter__Â  s    zParser.__enter__c             G   s   |   ¡  d S )N)r2   )r3   rY   r   r   r   Ú__exit__Å  s    zParser.__exit__c          	   C   sz   | j r*|  d¡ d | _| _ | js*tdƒ‚| js8tdƒ‚| jrtt | j¡�$}zt 	|¡| _W d| j 
¡  X W dQ R X | 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)r[   r   rt   rv   r   rr   rx   ry   r   r$   rA   )r3   r%   r   r   r   r2   È  s    

zParser.close)rg   rh   ri   rj   Úincrementalrr   rt   r[   rX   rv   ru   r   r€   r�   r2   r   r   r   r   rs   ]  s   Prs   c          
   C   sö  |   ¡  t| dƒsd| _|jtd� tt|| jd d ƒ}|tj	krP| 
¡  dS y| ¡ }| 
¡  W nÜ ttjfk
�r@ } z¶x°|D ]¨\}}}}	t | j||	| j¡}|dkr¶| |¡ | | j|¡ |jrâ| |¡ | ¡ \}
}n&x$| |¡\}
}}| |¡ |räP qäW |dk �r$td|› d�ƒ|‚| ¡  q„W W dd}~X Y nžX xš|D ]’\}}}}	t | j||	| j¡}|dk�r|| |¡ | | j|¡ |j�rª| |¡ | ¡ \}
}n| ||¡}|dk �rÐtd|› d�ƒ‚| ¡  �qHW t|d	ƒ�rò| 
¡  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)rA   rC   rƒ   rN   r   Úmaxr"   r0   rD   Ústdoutr…   rK   r	   rx   ÚUnsupportedOperationr   Z_getencoderr/   rH   rP   rI   Z	pushes_fdrR   Zencode_to_pyfdÚencodeÚwriter   rU   Zencode_to_file)rI   r%   r   ÚbufsizeÚfhÚexcr_   r]   r}   r~   Úlr^   r|   r   r   r   Ú_saveè  sT    	









r�   c             C   sf   |dkrdS |t kr|  |¡S g }x8|dkrZ|  t|t ƒ¡}|sBP | |¡ |t|ƒ8 }q$W d |¡S )ao  
    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 up to <i>size</i> bytes of data.
    r   r@   )Ú	SAFEBLOCKrF   rw   ÚappendrB   Újoin)r%   r0   rt   Ú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Úyoff)r3   r   r   r   r   ?  s    zPyCodecState.__init__c             C   s    | j | j| j | j | j| j fS )N)r˜   r™   r–   r—   )r3   r   r   r   rW   E  s    zPyCodecState.extentsN)rg   rh   ri   r   rW   r   r   r   r   r•   >  s   r•   c               @   s\   e Zd ZdZdZdd„ Zdd„ Zedd„ ƒZd	d
„ Z	dd„ Z
dd„ Zd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 Decoder in Python<file-decoders-py>`
    Fc             G   s(   d | _ tƒ | _d | _|| _|  |¡ d S )N)rI   r•   ÚstateÚfdr/   Úinit)r3   r/   rY   r   r   r   r   S  s
    zPyDecoder.__init__c             C   s
   || _ dS )zš
        Override to perform decoder specific initialization

        :param args: Array of args items from the tile entry
        :returns: None
        N)rY   )r3   rY   r   r   r   r�   Z  s    zPyDecoder.initc             C   s   | j S )N)Ú	_pulls_fd)r3   r   r   r   rQ   c  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 <0 for the bytes consumed.
            Err codes are from :data:`.ImageFile.ERRORS`.
        N)rm   )r3   Úbufferr   r   r   rS   g  s    	zPyDecoder.decodec             C   s   dS )zV
        Override to perform decoder specific cleanup

        :returns: None
        Nr   )r3   r   r   r   rU   r  s    zPyDecoder.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œ   )r3   rœ   r   r   r   rR   z  s    zPyDecoder.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 decoder

        :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)rI   r0   r›   r–   r—   r˜   r™   Ú
ValueError)r3   rI   rW   Zx0Zy0Úx1Úy1r   r   r   rP   ƒ  s    zPyDecoder.setimagec             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   rO   rP   rI   r›   rW   rS   r    )r3   rt   Úrawmoder|   r^   r   r   r   Ú
set_as_raw¦  s    

zPyDecoder.set_as_raw)N)N)rg   rh   ri   rj   rž   r   r�   ÚpropertyrQ   rS   rU   rR   rP   r¤   r   r   r   r   rš   I  s   		
#rš   )r   )rx   r-   rD   r   Ú r   Z_utilr   r"   r�   rT   r
   r   r   r   r   rl   rs   r�   r”   r•   rš   r   r   r   r   Ú<module>   s2   

	
 k 
>