U
    QtcY                     @   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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)is_pathi   i   Fzimage buffer overrun errorzdecoding errorzunknown errorzbad configurationzout of memory error)ic                 C   sN   z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-h5vj885l/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 | _ztz|   W n8 tttttjfk
r } zt||W 5 d }~X Y nX | jr| jd dks| jd dkrt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   W   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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k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
k
r   | jj}Y nX z| j}d}W n t
k
r   | jj}Y nX |r| j d \}}}}	|dkrt|	dkr|	d | jkr|	d tjkrzddl}
t| j}|
j| d|
jd	| _W 5 Q R X || jd |	d   | j kr\ttj| j| j|||	| _d}| jrd| j_W n" t
ttfk
r   d| _Y nX |   d
}| js@| j jtd z
| j}W n t
k
r   d}Y nX dd t !| j dd D | _ | j D ] \}}}}	|| t"| j||	| j#}z|%| j| |j&rz|'| j |(dd }n|}z|| j)}W nF t*t+j,fk
r } z t-rW Y q.n
td|W 5 d}~X Y nX |st-rq.ntdt| d|| }|(|\}}|dk rq.||d }q~W 5 |$  X qg | _ || _.| /  | j0rn| j1rn| j2  d| _| jst-s|dk rt3| 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-   r	   Z
map_bufferimZpaletteZdirtyImportErrorload_preparesortr   Ztile_prefix	itertoolsgroupby_getdecoderr   cleanupsetimagepulls_fdsetfddecoder    r&   r*   r   LOAD_TRUNCATED_IMAGESr   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    

""    

    

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 k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%   F  s    zStubImageFile._openc                 C   sP   |   }|d kr"td| j d|| }|d k	s8t|j| _|j| _| S )Nzcannot find loader for this z file)_loadr   r5   rF   AssertionErrorr3   __dict__)r0   loaderimager   r   r   rF   I  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   T  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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)datarw   r7   r   r   r   resetf  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 rd| _d| _ |dk rd| _t| ndS | j|d | _n| jrnz&t	
| j}t|}W 5 Q R X W n tk
r   Y nX 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   rM   rK   )finishedr|   rc   r`   minrH   r\   rz   r   ioBytesIOr   r!   r   rI   r   rS   rW   r,   r   rY   rQ   )r0   r|   skiprg   rf   r"   rQ   flagdoar   r   r   feedn  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   sz   | j r*| d d | _| _ | js*td| js8td| jrtt| j$}zt	
|| _W 5 | j  X W 5 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)rc   r   r|   r~   r   rz   r   r   rF   r   r!   )r0   r"   r   r   r   r/     s    

zParser.close)rn   ro   rp   rq   incrementalrz   r|   rc   r`   r~   r}   r   r   r   r/   r   r   r   r   r{   Y  s   Pr{   c              
   C   s   |    t| dsd| _|jtd tt|| jd d }z$| }|	  t
| |||| W n: ttjfk
r } zt
| |||d| W 5 d}~X Y nX t|dr|	  dS )zHelper 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      Nflush)rF   rI   r   rT   r   maxr   r-   rP   r   _encode_tiler
   r   UnsupportedOperation)rQ   r"   r   bufsizefhexcr   r   r   _save  s    	
$
r   c              	   C   s   |D ]\}}}}	|dkr"| | t| j||	| j}
z~|
| j| |
jrd|
	| |

 \}}n4|r|
|\}}}|| |rhqqhn|
||}|dk rtd| d|W 5 |
  X qd S )Nr   zencoder error z when writing image file)rN   r   Z_getencoderr,   r   rX   rY   rQ   	pushes_fdr[   encode_to_pyfdencodewriteencode_to_filer   )rQ   r"   r   r   r   r   rf   rd   r   r   encoderlre   r   r   r   r   r      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 rt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>7  s     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   =  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_   C  s    zPyCodecState.extentsN)rn   ro   rp   r   r_   r   r   r   r   r   <  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   H  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   O  s    zPyCodec.initc                 C   s   dS )zT
        Override to perform codec specific cleanup

        :returns: None
        Nr   r7   r   r   r   rX   X  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   r[   `  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rtd| jj| jj | j jd ks| jj| jj | j jd krt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   rY   i  s"    zPyCodec.setimage)N)rn   ro   rp   r   r   rX   r[   rY   r   r   r   r   r   G  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   rZ     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   rY   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   propertyrZ   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   )N)r   rU   r*   rJ    r   Z_utilr   r   r   r]   r   r   r   r   rs   r{   r   r   r   r   r   r   r   r   r   r   r   <module>   s8   

 k 

!F/