o
    Z#a`                     @   sn  d dl Z d dlZd dlZd dlZddlmZmZmZmZm	Z	 ddl
mZ ddl
mZ ddl
mZ dd ZG d	d
 d
ejZddddZd6ddZdd Zdd Zdd Zdd Zd6ddZdd Zdd Zdd  ZdZd!d" Zd#d$ Zd%d& Zd'd( Z d)d* Z!d+d, Z"d-d. Z#d7d/d0Z$d8d2d3Z%e&ej'ee e(ej'e e)ej'e e*ej'd4 e+ej'd5 dS )9    N   )Image
ImageChops	ImageFileImagePaletteImageSequence)i16le)o8)o16lec                 C   s   | d d dv S )N   )s   GIF87as   GIF89a )prefixr   r   4/usr/lib/python3/dist-packages/PIL/GifImagePlugin.py_accept)      r   c                       s|   e Zd ZdZdZdZdZdd Zdd Ze	d	d
 Z
e	dd Zdd Zdd Z fddZdd Zdd Zdd Z  ZS )GifImageFileZGIFzCompuserve GIFFNc                 C   s,   | j d}|r|d r| j |d S d S )Nr   r   )fpread)selfsr   r   r   data:   s   zGifImageFile.datac                 C   s  | j d}t|std|d d | jd< t|dt|df| _g | _|d }|d@ d }|d	@ rw|d
 | jd< | j d|> }tdt	|dD ],}|d ||   krg||d    krg||d  ksvn t
d|}| | _| _ nqJ| j | _| j  | _d | _d | _| d d S )N   znot a GIF filer   version   
      r         
background   r      RGB)r   r   r   SyntaxErrorinfoi16_sizetilerangelenr   rawglobal_palettepalette_GifImageFile__fptell_GifImageFile__rewind	_n_frames_is_animated_seek)r   r   flagsbitspir   r   r   _open@   s,   8zGifImageFile._openc                 C   sZ   | j d u r*|  }z	 | |  d  q ty$   |  d | _ Y nw | | | j S )NTr   )r/   r-   seekEOFErrorr   Zcurrentr   r   r   n_frames^   s   

zGifImageFile.n_framesc                 C   sl   | j d u r3| jd ur| jdk| _ | j S |  }z
| d d| _ W n ty-   d| _ Y nw | | | j S )Nr   TF)r0   r/   r-   r7   r8   r9   r   r   r   is_animatedj   s   





zGifImageFile.is_animatedc                 C   s   |  |sd S || jk rd | _| d | j}t| jd |d D ]}z| | W q! ty@ } z
| | td|d }~ww d S )Nr   r   zno more images in GIF file)Z_seek_check_GifImageFile__frameimr1   r'   r8   r7   )r   frameZ
last_framefer   r   r   r7   {   s   




zGifImageFile.seekc                    s  |dkrd| _ d | _g d| _d| _| j| j d| _n| jr$| 	  || jd kr2t
d| || _g | _| j| _| j rR| j| j  |  rO	 |  sJd| _ | jdkrd | _d| jv rzd| _| j| jd d | jdtj| _| jd= nd| _| jdtj| _| jr| j| j| j d }i }d }d }	 | jd}|r|d
krn|dkrA| jd}|  }|d dkr|d }|d@ r|d }t|dd |d< d|@ }	|	d? }	|	r|	| _nT|d dkr|rd|v r|d  |7  < n||d< |  }|sq|d dkr5|| j f|d< |d d dkr5|  }t|dkr5|d dkr5t|d|d< |  r@	 |  s:n~|dkr| jd}t|dt|d}
}|
t|d |t|d }}|| jd ksv|| jd krt|| jd t|| jd f| _|
|||f| _|d }|d@ dk}|d@ r|d @ d }td| jd|> }| jdd }| j | _ n	 q|p| j  fd!d"}z| jdk rd | _nx| jdkr| j\}
}}}||
 || f}t | | j!d|}|d urd}||d# }nd}|| j!d$d}tj"#|||| _n4| jr)| $| j| j| _n&|d urO| j\}
}}}||
 || f}t | tj"#d|||d# | _W n
 t%yZ   Y nw |d ur|dkro|d uro|| jd< d%|
|||f| j ||ffg| _nt&d&D ]}||v r|| | j|< q|| jv r| j|= q|dkrň rd'nd(| _| jd'kr|sdd)l'm'} || j}|| _(d S  | _)|| _*d S )*Nr   )r   r   r   r   r   zcannot seek to frame transparencyRGBAr!   T   ;   !   r   r   duration   r       comment   	extensionr      NETSCAPE2.0loop   ,	      r   r   @   r   r   c                    s4    rt  j| d | d d  } | S | | | f} | S )Nr   )tupler+   )colorZframe_paletter   r   _rgb  s
   
z GifImageFile._seek.<locals>._rgb)r   r   gif)rG   rJ   rL   rN   PL)copy)+Z_GifImageFile__offsetZdisposedispose_extentr<   r,   r7   r.   Zdisposal_methodr&   load
ValueErrorr   r   Zpyaccessr#   moder=   putpalettealphaconvertr   ZFLOYDSTEINBERGpaster   r$   r-   r(   sizemaxr%   r   r)   r*   Z_decompression_bomb_checkgetcorefill_cropAttributeErrorr8   rZ   r+   _frame_palette_frame_transparency)r   r>   r+   r#   Zframe_transparency	interlacer   blockr2   Zdispose_bitsZx0Zy0Zx1Zy1r3   rV   Zdispose_sizerT   Zdispose_modekrZ   r   rU   r   r1      s  







 "
R












zGifImageFile._seekc                    s   | j dkrd| jv rtj| j| j| jd | _n*| j| _| j	r=d| _tjd| j| j
p-d| _| jj| j	   d | _	nd| _d | _t   d S )Nr   rB   rX   rY   )r<   r#   r   re   rf   r^   rb   r=   _prev_imri   rj   
putpalettegetdatasuperload_preparer   	__class__r   r   rr   \  s   

zGifImageFile.load_preparec                 C   s   | j dkrd S | jd ur| j| jd | jd}n| jd}| || j}| j| _| jj| _|jdkrA| j	|| j| d S | j	|| j d S )Nr   rC   r!   )
r<   rj   r=   r_   r`   rg   r[   rn   r^   ra   )r   Zframe_imr   r   r   load_endo  s   



zGifImageFile.load_endc                 C   s   | j S N)r<   rs   r   r   r   r-     s   zGifImageFile.tellc                 C   sP   z#z| j | jkr| j   W n	 ty   Y nw W d | _ d S W d | _ d S d | _ w rw   )r,   r   closerh   rs   r   r   r   
_close__fp  s   

zGifImageFile._close__fp)__name__
__module____qualname__formatZformat_descriptionZ!_close_exclusive_fp_after_loadingr*   r   r6   propertyr:   r;   r7   r1   rr   rv   r-   ry   __classcell__r   r   rt   r   r   2   s$    

 Sr   rY   rX   )1rY   rX   Fc                 C   s   | j tv r|   | S t| j dkrV|rQd}| jr%t| j d d }| jdtj	|d} | jj dkrO| jj
 D ]}|d dkrN| jj
| | jd	<  | S q:| S | dS | d
S )a  
    Takes an image (or frame), returns an image in a mode that is appropriate
    for saving in a Gif.

    It may return the original image, or it may return an image converted to
    palette or 'L' mode.

    UNDONE: What is the point of mucking with the initial call palette, for
    an image that shouldn't have a palette, or it would be a mode 'P' and
    get returned in the RAWMODE clause.

    :param im: Image object
    :param initial_call: Default false, set to true for a single frame.
    :returns: Image object
    r!      r   r   rX   )r+   colorsrC   r   rB   rY   )r^   RAWMODEr\   r   Zgetmodebaser+   r(   rp   r`   ZADAPTIVEr   keysr#   )r=   Zinitial_callZpalette_sizeZrgbar   r   r   _normalize_mode  s&   


r   c           	   	   C   sf  d}|rt |tttfrt|dd }t |tjrt|j}| jdkr1|s0| jddd }n|s>tdd t	dD }tjd|d| _|rg }t	dt
|d	D ]%}t|||d	  }z| jj| }W n tyq   d}Y nw || qRt|D ]\}}|du rt	t
|D ]}||vr|||<  nqq|| |} nt| |}|dur| ||S || j_| S )
at  
    Normalizes the palette for image.
      - Sets the palette to the incoming palette, if provided.
      - Ensures that there's a palette for L mode images
      - Optimizes the palette if necessary/desired.

    :param im: Image object
    :param palette: bytes object containing the source palette, or ....
    :param info: encoderinfo
    :returns: Image object
    Ni   rX   r!   c                 s   s    | ]}|d  V  qdS )r   Nr   ).0r5   r   r   r   	<genexpr>  s    z%_normalize_palette.<locals>.<genexpr>r+   r   r   )
isinstancebytes	bytearraylistr   r+   r^   r=   Z
getpaletter'   r(   rS   r   KeyErrorappend	enumerateZremap_palette_get_optimize)	r=   r+   r#   Zsource_paletteused_palette_colorsr5   Zsource_colorindexjr   r   r   _normalize_palette  sJ   


r   c              	   C   s   t | d}|j D ]\}}| j|| q
t||| j}t|| jD ]}|| q#d}t| r5|dB }t	|| d| dt| f|_
t||dd| j dt|j fg |d d S )NTr   rR   r   r   r   rW       )r   r#   itemsencoderinfo
setdefaultr   _get_global_headerwriteget_interlace_write_local_headerZencoderconfigr   _saverb   r   r^   )r=   r   r+   Zim_outrm   vr   r2   r   r   r   _write_single_frame  s   
$r   c              	   C   s  | j d| jd}| j d| jd}g }d}d }t| g| j dg D ]}t|D ]}	t|	 }	|dkrL|	j	 D ]\}
}| j 
|
| q@t|	|| j }	| j  }t|ttfre|| |d< t|ttfrr|| |d< |d7 }|r|d }|ddkr|d u r| j d| jdd	}t|	|}td
|	j|}||d d j |}n|d }t|	t|krt|	|}nt|	d|d}| }|s|r|d d  |d 7  < q/nd }||	||d q/q(t|dkr:|D ]?}|d }	|d st|	|d D ]}|| q
d}n|sd|d d< |	|d }	|d d d }t||	||d  qdS d| j v rWt| j d ttfrYt | j d | j d< d S d S d S )NrG   disposalr   Zappend_imagesr   rA   r    rB   )r   r   r   rX   r=   r!   r   )r=   bboxr   r   r   Tinclude_color_table)!r   rd   r#   	itertoolschainr   Iteratorr   rZ   r   r   r   r   r   rS   _get_backgroundr   newrb   ro   r+   _get_palette_bytesr   Zsubtract_modulor`   Zgetbboxr   r(   r   r   Zcrop_write_frame_datasum)r=   r   r+   rG   r   Z	im_framesZframe_countZbackground_imZ
imSequenceim_framerm   r   r   ZpreviousrT   r   Zbase_imZdeltar   Z
frame_datar   offsetr   r   r   _write_multiple_frames  s|   

-
r   c                 C   s   t | ||dd d S )NT)save_all)r   )r=   r   filenamer   r   r   	_save_allP  s   r   c                 C   s   d| j v s
d| jv r| j d| jd}nd }| j dd| j d< |r*t| ||s0t| || |d t|dr@|  d S d S )Nr+   optimizeTrD   flush)r   r#   rd   r   r   r   hasattrr   )r=   r   r   r   r+   r   r   r   r   T  s   

r   c                 C   s$   | j dd}t| jdk rd}|S )Nrk   r      r   )r   rd   minrb   )r=   rk   r   r   r   r   e  s   r   c                 C   s  d}z|j d }W n	 ty   Y n$w t|}d}t||j }|d ur6z||}W n ty5   d}Y nw d|j v rEt|j d d }nd}t|j dd}|sX|dksX|r|r\dnd}	|	|d	> O }	|shd}| d
td td t|	 t	| t| td  d|j v rdt
|j d kr| d
td  |j d }
t|
tr|
 }
tdt
|
dD ]}|
||d  }| tt
||  q| td d|j v r|j d }| d
td td d td td t	| td  |j d}|rt|}t|}|r|dB }||B }| dt	|d  t	|d  t	|jd  t	|jd  t|  |rD|rD| t| | td d S )NFrB   TrG   r   r   r   r   r    rE   rF   rQ   rJ   rI   rK   rN   r   rM   r   r   r   rO   r   )r   r   intr   r   r]   rd   r   r	   o16r(   r   strencoder'   r   _get_color_table_sizerb   _get_header_palette)r   r=   r   r2   Ztransparent_color_existsrB   r   rG   r   Zpacked_flagrJ   r5   ZsubblockZnumber_of_loopsr   palette_bytescolor_table_sizer   r   r   r   o  s   








r   c           
      C   s  |   }ztt|dS}| jdkrtjd|g|tjd n:dd|g}dg}tj|tjtjd}tj||j|tjd}|j	  |
 }	|	rJt|	||
 }	|	rVt|	|W d    n1 s`w   Y  W zt| W d S  tyx   Y d S w zt| W w  ty   Y w w )Nwbr!   Zppmtogif)stdoutstderrZppmquantZ256)stdinr   r   )Z_dumpopenr^   
subprocessZ
check_callZDEVNULLPopenPIPEr   rx   waitZCalledProcessErrorosunlinkOSError)
r=   r   r   Ztempfiler?   Z	quant_cmdZ	togif_cmdZ
quant_procZ
togif_procZretcoder   r   r   _save_netpbm  sL   



r   c                 C   s   | j dv rD|rF|ddrHtp| j dk}|s| j| j dk rJg }t|  D ]\}}|r1|| q&|sBt|dkrLt	|t|krN|S dS dS dS dS dS dS )aL  
    Palette optimization is a potentially expensive operation.

    This function determines if the palette should be optimized using
    some heuristics, then returns the list of palette entries in use.

    :param im: Image object
    :param info: encoderinfo
    :returns: list of indexes of palette entries in use, or None
    )rX   rY   r   r   rY   i   r   N)
r^   rd   _FORCE_OPTIMIZEwidthZheightr   Z	histogramr   r(   rc   )r=   r#   Zoptimiser   r5   countr   r   r   r     s"   

r   c                 C   s6   | sdS t | dk rdS ttt | d dd S )Nr   rP   r   r   r    )r(   mathZceillog)r   r   r   r   r     s
   r   c                 C   s<   t | }d|> t| d  }|dkr| tdd | 7 } | S )z
    Returns the palette, null padded to the next power of 2 (*3) bytes
    suitable for direct inclusion in the GIF header

    :param palette_bytes: Unpadded palette bytes, in RGBRGB form
    :returns: Null padded palette
    r    r   r   )r   r(   r	   )r   r   Zactual_target_size_diffr   r   r   r   '  s
   r   c                 C   s   | j j S )z
    Gets the palette for inclusion in the gif header

    :param im: Image object
    :returns: Bytes, len<=768 suitable for inclusion in gif header
    r   )r=   r   r   r   r   9  s   r   c              
   C   sd   d}|r0|}t |tr0z
| j|| }W |S  ty/ } zt|dkr*W Y d }~dS  d }~ww |S )Nr   z$cannot allocate more than 256 colors)r   rS   r+   Zgetcolorr]   r   )r=   ZinfoBackgroundr   r@   r   r   r   r   C  s   
r   c                 C   s   d}dD ]*}|r.||v r.|dkr|| dks)|dkr*dt ||   kr(dks*n qd} nq| jd	dkr9d}t| |d
}t| }t|}d| t| jd  t| jd  t|d t|td t	|gS )z2Return a list of strings representing a GIF headers   87a)rB   rG   rN   rJ   rG   r   rJ   r   rK   s   89ar   r   s   GIFr   )
r(   r#   rd   r   r   r   r   rb   r	   r   )r=   r#   r   ZextensionKeyr   r   r   r   r   r   r   W  s<   
r   c              	   C   sT   z&||_ t| ||d t|| dd|j dt|j fg | d W |` d S |` w )Nr   rW   r   r   )r   r   r   r   rb   r   r^   r   )r   r   r   paramsr   r   r   r   ~  s   r   c                 C   sd   t | |}|du ri }d|vrd| jv r| jd |d< t| ||}|j| _|j| _t| |}||fS )a  
    Legacy Method to get Gif data from image.

    Warning:: May modify image data.

    :param im: Image object
    :param palette: bytes object containing the source palette, or ....
    :param info: encoderinfo
    :returns: tuple of(list of header items, optimized palette)

    Nr   )r   r#   r   r+   r=   r   )r=   r+   r#   r   Zim_modheaderr   r   r   	getheader  s   

r   r   c                 K   s0   G dd d}|    | }t|| || |jS )a  
    Legacy Method

    Return a list of strings representing this image.
    The first string is a local image header, the rest contains
    encoded image data.

    :param im: Image object
    :param offset: Tuple of (x, y) pixels. Defaults to (0,0)
    :param \**params: E.g. duration or other encoder info parameters
    :returns: List of Bytes containing gif encoded frame data

    c                   @   s   e Zd Zg Zdd ZdS )zgetdata.<locals>.Collectorc                 S   s   | j | d S rw   )r   r   )r   r   r   r   r   r     r   z getdata.<locals>.Collector.writeN)rz   r{   r|   r   r   r   r   r   r   	Collector  s    r   )r\   r   r   )r=   r   r   r   r   r   r   r   rp     s
   rp   z.gifz	image/gif)F)NN)r   ),r   r   r   r    r   r   r   r   r   Z_binaryr   r$   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rp   Zregister_openr}   Zregister_saveZregister_save_allZregister_extensionZregister_mimer   r   r   r   <module>   sJ   	  a
$5N

T2%

'

!