a
    s=ic                    @   s  d 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	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ZddlZddlZddlm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"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddlm?Z? ddl@mAZA e
BeCZDejEddddLddZFdMddZGdd ZHd d! ZIdNd"d#ZJdOd$d%ZKdPd&d'ZLeMNd(d)d*d+d,d-ZOd.d/ ZPd0d1 ZQG d2d3 d3ZReG d4d5 d5ZSeEdG d6d7 d7ZTG d8d9 d9ZUG d:d; d;eZVG d<d= d=ZWd>d? ZXG d@dA dAZYG dBdC dCeAjZZ[G dDdE dEe%Z\G dFdG dGZ]G dHdI dIe#Z^e$Z_e"j`G dJdK dKe"ZadS )QuO   
A PDF Matplotlib backend.

Author: Jouni K Seppänen <jks@iki.fi> and others.
    N)datetime)Enum)total_ordering)BytesIO)Image)_api_text_helpers
_type1fontcbookdviread)Gcf)_BackendFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase)MixedModeRenderer)Figure)get_fontfontManager)AFM)FIXED_WIDTHITALICLOAD_NO_SCALELOAD_NO_HINTINGKERNING_UNFITTEDFT2Font)Affine2DBboxBase)Path)UTC)_path   )_backend_pdf_ps3.6za vendored copy of _fill)alternativeK   c                 C   s   t | |dS )N)linelen)_fill)stringsr'    r*   p/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/matplotlib/backends/backend_pdf.pyfill_   s    r,   c                 C   s   d}d}g }t | D ]J\}}t|}|| |k r>||d 7 }q|d| ||  |}|}q|d| |d  d|S )z
    Make one string from sequence of strings, with whitespace in between.

    The whitespace is chosen to form lines of at most *linelen* characters,
    if possible.
    r   r"       N   
)	enumeratelenappendjoin)r)   r'   Zcurrposlastiresultislengthr*   r*   r+   r(   d   s    r(   c           
   
   C   s4  t d}|r*tt|}|jtd}nt }dtj	 dd|  dtj	 |d|}dd	 |
 D }d
d }d|_dd }d|_dd }d|_|||||||||d	}|D ]b}	|	|vrtd|	dt|d q||	 ||	 std|	 d||	 d||	 j d qd|v r0t|d |d< |S )a  
    Create a PDF infoDict based on user-supplied metadata.

    A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though
    the user metadata may override it. The date may be the current time, or a
    time set by the ``SOURCE_DATE_EPOCH`` environment variable.

    Metadata is verified to have the correct keys and their expected types. Any
    unknown keys/types will raise a warning.

    Parameters
    ----------
    backend : str
        The name of the backend to use in the Producer value.

    metadata : dict[str, Union[str, datetime, Name]]
        A dictionary of metadata supplied by the user with information
        following the PDF specification, also defined in
        `~.backend_pdf.PdfPages` below.

        If any value is *None*, then the key will be removed. This can be used
        to remove any pre-defined values.

    Returns
    -------
    dict[str, Union[str, datetime, Name]]
        A validated dictionary of metadata.
    SOURCE_DATE_EPOCH)tzinfozMatplotlib vz, https://matplotlib.orgzMatplotlib z
 backend v)CreatorProducerCreationDatec                 S   s   i | ]\}}|d ur||qS Nr*   .0kvr*   r*   r+   
<dictcomp>       z)_create_pdf_info_dict.<locals>.<dictcomp>c                 S   s
   t | tS r=   )
isinstancestrxr*   r*   r+   is_string_like   s    z-_create_pdf_info_dict.<locals>.is_string_likezan instance of strc                 S   s
   t | tS r=   )rD   r   rF   r*   r*   r+   is_date   s    z&_create_pdf_info_dict.<locals>.is_datez an instance of datetime.datetimec                 S   s    t | tr| jdv S | dv S d S )N)s   Trues   Falses   Unknown)TrueFalseUnknownrD   NamenamerF   r*   r*   r+   check_trapped   s    

z,_create_pdf_info_dict.<locals>.check_trappedz#one of {"True", "False", "Unknown"})	ZTitleAuthorSubjectKeywordsr:   r;   r<   ZModDateTrappedzUnknown infodict keyword: z. Must be one of .zBad value for infodict keyword z. Got z which is not rT   )osgetenvr   utcfromtimestampintreplacer    todaympl__version__itemsZtext_for_warningr   Zwarn_externalsetrN   )
backendmetadatasource_date_epochZsource_dateinforH   rI   rP   keywordsr@   r*   r*   r+   _create_pdf_info_dictz   sT     

re   c                 C   s   |  d}|  }|dur"|j}ntjr0tj}ntj}|dkrH|d7 }n>|dk rn|d| d | d f 7 }n|d|d |d f 7 }|S )zX
    Convert a datetime to a PDF string representing it.

    Used for PDF and PGF.
    zD:%Y%m%d%H%M%SNr   Zz+%02d'%02d'i  z-%02d'%02d')strftime	utcoffsetsecondstimedaylightaltzonetimezone)drzr*   r*   r+   _datetime_to_pdf   s    

rq   c                 C   s   t | }t |}t |}| ||  }|||  }| ||  ||  }	|||  ||  }
| ||  }|||  }| |f||f|	|
f||ffS )zR
    Calculate the coordinates of rectangle when rotated by angle around x, y
    )mathradianssincos)rG   ywidthheightangleZ	sin_angleZ	cos_angleabcrn   efr*   r*   r+   !_calculate_quad_point_coordinates   s    

r   c                 C   s   t | ||||}|d rdnd}tdd |D | }tdd |D | }tdd |D | }	tdd |D | }
ttj||||	|
ffS )	zg
    Get the coordinates of rotated rectangle and rectangle that covers the
    rotated rectangle.
    Z   gh㈵>r   c                 s   s   | ]}|d  V  qdS r   Nr*   r?   rA   r*   r*   r+   	<genexpr>
  rC   z,_get_coordinates_of_block.<locals>.<genexpr>c                 s   s   | ]}|d  V  qdS r"   Nr*   r   r*   r*   r+   r     rC   c                 s   s   | ]}|d  V  qdS r   r*   r   r*   r*   r+   r     rC   c                 s   s   | ]}|d  V  qdS r   r*   r   r*   r*   r+   r     rC   )r   minmaxtuple	itertoolschainfrom_iterable)rG   rv   rw   rx   ry   verticespadZmin_xZmin_yZmax_xZmax_yr*   r*   r+   _get_coordinates_of_block   s    	
r   c           	      C   sR   t |||||\}}tdtd|g dtd|  dd}|d rN||d< |S )	z=
    Create a link annotation object for embedding URLs.
    AnnotLink)r   r   r   URI)Sr   )TypeSubtypeRectZBorderAr   Z
QuadPoints)r   rN   get_url)	gcrG   rv   rw   rx   ry   Z
quadpointsrectZlink_annotationr*   r*   r+   _get_link_annotation  s    
r   z\\z\(z\)z\nz\r)\()
c                 C   s  t | dr|  S t| ttjfrLt| s4tdd|  }|ddS t| t	rbddg|  S t| t
tjfrzd|  S t| trt|  r| d	ntj| d
 S t| trd| dtd d S t| t rtdgdd |  D dS t| ttfr*tdgdd | D dS | du r8dS t| trPtt| S t| trptdd | jD S tdt | dS )z!Map Python objects to PDF syntax.pdfReprz%Can only output finite numbers in PDFs   %.10f   0   .s   falses   trues   %dasciizUTF-16BE   (zlatin-1   )s   <<c                 S   s(   g | ] \}}t | d  t| qS )r-   )rN   r   r>   r*   r*   r+   
<listcomp>`  rC   zpdfRepr.<locals>.<listcomp>s   >>   [c                 S   s   g | ]}t |qS r*   r   r?   valr*   r*   r+   r   f  rC      ]Ns   nullc                 S   s   g | ]}t |qS r*   r   r   r*   r*   r+   r   r  rC   z.Don't know a PDF representation for {} objects)!hasattrr   rD   floatnpZfloatingisfinite
ValueErrorrstripboolrY   integerrE   isasciiencodecodecsBOM_UTF16_BEbytesdecode	translate_str_escapesdictr(   r^   listr   r   rq   r   Zbounds	TypeErrorformattype)objro   r*   r*   r+   r   0  sR    




	
r   c                 C   s*   | dkr|dkS | dkr |dkS t  dS )a  
    Returns True if the font is able to provide codepoint *glyph* in a PDF.

    For a Type 3 font, this method returns True only for single-byte
    characters. For Type 42 fonts this method return True if the character is
    from the Basic Multilingual Plane.
          *     N)NotImplementedError)fonttypeglyphr*   r*   r+   _font_supports_glyphy  s
    r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )	ReferencezV
    PDF reference object.

    Use PdfFile.reserveObject() to create References.
    c                 C   s
   || _ d S r=   idselfr   r*   r*   r+   __init__  s    zReference.__init__c                 C   s
   d| j  S )Nz<Reference %d>r   r   r*   r*   r+   __repr__  s    zReference.__repr__c                 C   s
   d| j  S )Ns   %d 0 Rr   r   r*   r*   r+   r     s    zReference.pdfReprc                 C   s,   |j }|d| j  |t| |d d S )N	   %d 0 obj
s   
endobj
)writer   r   )r   contentsfiler   r*   r*   r+   r     s    zReference.writeN)__name__
__module____qualname____doc__r   r   r   r   r*   r*   r*   r+   r     s
   r   c                   @   s   e Zd ZdZdZdd h edh eededd  D Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zeeddd Zdd ZdS )rN   zPDF name object.rO   c                 C   s   i | ]}|d | qS )#%02xr*   r?   r|   r*   r*   r+   rB     s   zName.<dictcomp>   !~r"   c                 C   s@   t |tr|j| _n(t |tr(|d}|| jd| _d S )Nr   )rD   rN   rO   r   r   r   _hexifyr   )r   rO   r*   r*   r+   r     s
    



zName.__init__c                 C   s
   d| j  S )Nz	<Name %s>r   r   r*   r*   r+   r     s    zName.__repr__c                 C   s   d| j d S )N/r   )rO   r   r   r*   r*   r+   __str__  s    zName.__str__c                 C   s   t |to| j|jkS r=   rM   r   otherr*   r*   r+   __eq__  s    zName.__eq__c                 C   s   t |to| j|jk S r=   rM   r   r*   r*   r+   __lt__  s    zName.__lt__c                 C   s
   t | jS r=   )hashrO   r   r*   r*   r+   __hash__  s    zName.__hash__r$   c                 C   s   dt |   S )Nr   )ordgroup)matchr*   r*   r+   hexify  s    zName.hexifyc                 C   s
   d| j  S )N   /r   r   r*   r*   r+   r     s    zName.pdfReprN)r   r   r   r   	__slots__ranger   r   r   r   r   r   r   r   staticmethodr   
deprecatedr   r   r*   r*   r*   r+   rN     s   $rN   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	Operatoropc                 C   s
   || _ d S r=   r   )r   r   r*   r*   r+   r     s    zOperator.__init__c                 C   s
   d| j  S )Nz<Operator %s>r   r   r*   r*   r+   r     s    zOperator.__repr__c                 C   s   | j S r=   r   r   r*   r*   r+   r     s    zOperator.pdfReprN)r   r   r   r   r   r   r   r*   r*   r*   r+   r     s   r   c                   @   s    e Zd ZdZdd Zdd ZdS )VerbatimzEStore verbatim PDF command content for later inclusion in the stream.c                 C   s
   || _ d S r=   Z_x)r   rG   r*   r*   r+   r     s    zVerbatim.__init__c                 C   s   | j S r=   r   r   r*   r*   r+   r     s    zVerbatim.pdfReprN)r   r   r   r   r   r   r*   r*   r*   r+   r     s   r   c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(e)*d'e+d(d) Z,d*d+ Z-e.d,d- Z/d.S )/Opz'PDF operators (not an exhaustive list).   b   B   f   h   s   S   ns   BTs   ET   cs   re   l   ms   cms   Do   G   gs   RGs   rgs   CSs   css   SCNs   scn   d   j   Js   gs   q   Qs   Tds   Tfs   Tms   Tjs   TJ   w   Ws   shr$   c                 C   s   | j S r=   valuer   r*   r*   r+   <lambda>  rC   zOp.<lambda>c                 C   s   | j S r=   r
  r   r*   r*   r+   r     s    z
Op.pdfReprc                 C   s*   |r|r| j S | jS n|r | jS | jS dS )z
        Return the PDF operator to paint a path.

        Parameters
        ----------
        fill : bool
            Fill the path with the fill color.
        stroke : bool
            Stroke the outline of the path with the line color.
        N)fill_strokestroker,   endpath)clsr,   r  r*   r*   r+   
paint_path  s    zOp.paint_pathN)0r   r   r   r   Zclose_fill_stroker  r,   	closepathZclose_stroker  r  
begin_textend_textcurveto	rectanglelinetomovetoconcat_matrixuse_xobjectsetgray_strokesetgray_nonstrokesetrgb_strokesetrgb_nonstrokesetcolorspace_strokesetcolorspace_nonstrokeZsetcolor_strokesetcolor_nonstrokesetdashsetlinejoin
setlinecap	setgstategsavegrestoretextpos
selectfont
textmatrixshowshowkernsetlinewidthclipshadingr   r   propertyr   r   classmethodr  r*   r*   r*   r+   r     sT   r   c                   @   s>   e Zd ZdZdZdddZdd Zdd	 Zd
d Zdd Z	dS )Streamz
    PDF stream object.

    This has no pdfRepr method. Instead, call begin(), then output the
    contents of the stream by calling write(), and finally call end().
    )r   r0   pdfFiler   compressobjextraposNc                 C   s   || _ || _|| _|j| _d| _|du r2t | _n
| | _|durZ| j	t
d|d | j| j  tjd r|sttjd | _| jdu rt | _n|   | j | _dS )a@  
        Parameters
        ----------
        id : int
            Object id of the stream.
        len : Reference or None
            An unused Reference object for the length of the stream;
            None means to use a memory buffer so the length can be inlined.
        file : PdfFile
            The underlying object to write the stream to.
        extra : dict from Name to anything, or None
            Extra key-value pairs to include in the stream header.
        png : dict or None
            If the data is already png encoded, the decode parameters.
        NFlateDecode)FilterZDecodeParmspdf.compression)r   r0   r3  fhr   r4  r   r5  copyupdaterN   
recordXrefr\   rcParamszlibr   _writeHeadertellr6  )r   r   r0   r   r5  pngr*   r*   r+   r   ,  s*    



zStream.__init__c                 C   sT   | j j}|d| j  | j}| j|d< tjd r<td|d< |t| |d d S )Nr   ZLengthr9  r7  r8  s   
stream
)	r   r   r   r5  r0   r\   r>  rN   r   )r   r   r   r*   r*   r+   r@  S  s    

zStream._writeHeaderc                 C   s   |    | jdu rR| j }t|| _| jj| _|   | j| | jd n,| j | j	 }| jd | j
| j| dS )zFinalize stream.Ns   
endstream
endobj
)_flushr0   r   getvaluer3  r:  r@  r   rA  r6  writeObject)r   r   r7   r*   r*   r+   end^  s    



z
Stream.endc                 C   s4   | j du r| j| n| j |}| j| dS )zWrite some data on the stream.N)r4  r   r   compress)r   data
compressedr*   r*   r+   r   n  s    
zStream.writec                 C   s*   | j dur&| j  }| j| d| _ dS )zFlush the compression object.N)r4  flushr   r   )r   rI  r*   r*   r+   rC  w  s    

zStream._flush)NN)
r   r   r   r   r   r   r@  rF  r   rC  r*   r*   r*   r+   r2  #  s   
'	r2  c                 C   s  t | dd}d|j }i }|D ]x}||t}t|jdg|j| d t	}|
 \}}	|d t	}t|	dk\}
|
dd d }tth |h |
d @ h |
d @ t	}||| ||d  ||d   d t	kjdd	 }|j|fd
v r|d d df  d8  < || d t	}||d  ||d   d t	||< dtt|dd tt||	d d dd dg dd d |||< q|S )Nr"   )Zhinting_factor  r   g      ?@   r      Zaxis))DejaVuSerif-ItalicM   )rO      r   s    d1
F)r   r   rC   r   r   Tr   )r   units_per_EMZ
load_glyphr   r   arrayhoriAdvancebboxZastyperY   get_pathZnonzerosortedallpostscript_namer2   maprE   r   r!   convert_to_stringr   get_glyph_name)Z	font_path	glyph_idsfontconvZprocsZglyph_idgd1rA   r|   ZquadsZquads_onZquads_mid_onZimplicitr*   r*   r+   _get_pdf_charprocs  sJ    

$	$ rd  c                       s  e Zd ZdZdb fdd	Zdd Zg dfdd	Zd
d Zdd Zdd Z	dd Z
dd ZdcddZdd ZddddZdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Z d>d? Z!d@dA Z"dBdC Z#dddDdEZ$dFdG Z%dHdI Z&dJdK Z'dLdM Z(dNdO Z)e*dedPdQZ+dfdSdTZ,dgdVdWZ-dXdY Z.dZd[ Z/d\d] Z0d^d_ Z1d`da Z2  Z3S )hPdfFilezPDF file object.Nc                    sF  t    td| _g dg| _d| _d| _d| _t	j
|ddd\}}|sz| | _W n tyx   t }|| _Y n0 |}d| _|| _d| _|d	 |d
 | d| _| d| _g | _| d| _| d| _| d| _| d| _| d| _| d| _td| jd}| | j| td|p4i | _i | _dd tdD | _ i | _!i | _"t#$ | _%i | _&dd tdD | _'i | _(dd tdD | _)g | _*i | _+dd tdD | _,g | _-i | _.dd tdD | _/i | _0i | _1g | _2g | _3g | _4dd d5 D }| j| j| j| j| j|d}| | j| dS ) a  
        Parameters
        ----------
        filename : str or path-like or file-like
            Output target; if a string, a file will be opened for writing.

        metadata : dict from strings to strings and dates
            Information dictionary object (see PDF reference section 10.2.1
            'Document Information Dictionary'), e.g.:
            ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.

            The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
            'Creator', 'Producer', 'CreationDate', 'ModDate', and
            'Trapped'. Values have been predefined for 'Creator', 'Producer'
            and 'CreationDate'. They can be removed by setting them to `None`.
        r"   )r   r   the zero objectFNr   wbT)Zreturn_openeds	   %PDF-1.4
s   % 
rootZpagesfontszextended graphics statesztiling patternszGouraud triangleszexternal objects	resourcesCatalog)r   Pagespdfc                 s   s   | ]}t d | V  qdS )FNrN   r?   r5   r*   r*   r+   r     rC   z#PdfFile.__init__.<locals>.<genexpr>c                 s   s   | ]}t d | V  qdS )r   Nro  rp  r*   r*   r+   r     rC   c                 s   s   | ]}t d | V  qdS )ZSMNro  rp  r*   r*   r+   r     rC   c                 s   s   | ]}t d | V  qdS )HNro  rp  r*   r*   r+   r     rC   c                 s   s   | ]}t d | V  qdS )INro  rp  r*   r*   r+   r     rC   c                 S   s   g | ]}t |qS r*   ro  r?   rG   r*   r*   r+   r     rC   z$PdfFile.__init__.<locals>.<listcomp>PDF Text ImageB ImageC ImageI)FontXObject	ExtGStatePatternShadingZProcSet)6superr   r   count_object_seq	xrefTablepassed_in_file_objectoriginal_file_like	tell_baser
   Zto_filehandlerA  IOErrorr   r:  currentstreamr   reserveObject
rootObjectpagesObjectpageList
fontObject_extGStateObjecthatchObjectgouraudObjectXObjectObjectresourceObjectrN   rE  re   infoDict	fontNames_internal_font_seqdviFontInfotype1Descriptorsr#   ZCharacterTracker_character_trackeralphaStates_alpha_state_seq_soft_mask_states_soft_mask_seq_soft_mask_groupshatchPatterns_hatch_pattern_seqgouraudTriangles_images
_image_seqmarkersmulti_byte_charprocspaths_annotationspageAnnotationssplit)r   filenamera   r:  Zopenedrh  Zprocsetsrj  	__class__r*   r+   r     s|    



zPdfFile.__init__c                 C   s   |    || | _| _| d}| d}td| j| jddd| d| g||d}| d}| || | j	| | j
	|| jf | |j| d | td	tj | td	tj | tjd
 tj g | _d S )Nzpage contentsannotationsZPager   H   )r   ZParent	ResourcesZMediaBoxContentsZAnnotspagezlength of content stream	DeviceRGBround)	endStreamrw   rx   r  rN   r  r  rE  r  r1   r  r  beginStreamr   outputr   r  r   GraphicsContextPdf
joinstylesr#  )r   rw   rx   ZcontentObjectannotsObjectZthePageZ
pageObjectr*   r*   r+   newPage  s,    


zPdfFile.newPager  r   r   c                 C   s&   t dt d||d}| j| d S )Nr   Text)r   r   r  r   )rN   r  r1   )r   textpositionRectZtheNoter*   r*   r+   newTextnote7  s    zPdfFile.newTextnotec                    sH    fdd t t| tjd d  } |d}|d d d | S )Nc                    s2   | |k rt j|  S  | | |t j| |   S d S r=   )stringascii_uppercase)nbasetoStrr*   r+   r  A  s    
z,PdfFile._get_subsetted_psname.<locals>.toStrr"   rM        +)r   	frozensetkeyssysmaxsize)r   ps_namecharmaphashedprefixr*   r  r+   _get_subsetted_psname@  s    	
zPdfFile._get_subsetted_psnamec              
   C   s  |    |   |   |   |   |   |   dd | j D }| j	 D ]}|d ||d < qV| j
 D ]\}}|||< qv| jD ]\	}}}}}}	}
}}|||< q| | j| |   |   |   | | jtd| jt| jd |   |   |   dS )z>Write out the various deferred objects and the pdf end matter.c                 S   s   i | ]\}}}||qS r*   r*   )r?   imagerO   obr*   r*   r+   rB   Z  s   z$PdfFile.finalize.<locals>.<dictcomp>r"   r   rl  )r   ZKidsZCountN)r  _write_annotations
writeFontswriteExtGSTates_write_soft_mask_groupswriteHatcheswriteGouraudTrianglesr  valuesr  r  r^   r  rE  r  writeImageswriteMarkerswritePathCollectionTemplatesr  rN   r  r0   writeInfoDict	writeXrefwriteTrailer)r   ZxobjectstuprO   r  pathtransr  r2   cappaddingfilledstrokedr*   r*   r+   finalizeP  s<    

zPdfFile.finalizec                 C   sD   |    | jr| j  n&| jdur6| j| j  | j  dS )z)Flush all buffers and free all resources.N)r  r~  r:  rJ  r  r   rD  closer   r*   r*   r+   r  q  s    
zPdfFile.closec                 C   s(   | j d u r| j| n| j | d S r=   )r  r:  r   r   rH  r*   r*   r+   r   |  s    
zPdfFile.writec                 G   s&   |  tdd |D  |  d d S )Nc                 S   s   g | ]}t |qS r*   r   rs  r*   r*   r+   r     rC   z"PdfFile.output.<locals>.<listcomp>r.   )r   r(   r  r*   r*   r+   r    s    zPdfFile.outputc                 C   s$   | j d u sJ t||| ||| _ d S r=   )r  r2  )r   r   r0   r5  rB  r*   r*   r+   r    s    zPdfFile.beginStreamc                 C   s   | j d ur| j   d | _ d S r=   )r  rF  r   r*   r*   r+   r    s    

zPdfFile.endStreamr5  c                C   s(   |  |jd | | j| |   d S r=   )r  r   r  r   r  )r   refrH  r5  r*   r*   r+   outputStream  s    zPdfFile.outputStreamc                 C   s    | j D ]\}}| || qd S r=   )r  rE  )r   r  r  r*   r*   r+   r    s    zPdfFile._write_annotationsc                 C   s   t |tr|g}n(tjd r0tj|dtjd}n
t|}d}|D ]J}| j	|}|sZ|}|du rBt
| j}|| j|< td|| |sB|}qB|S )z
        Select a font based on fontprop and return a name suitable for
        Op.selectfont. If fontprop is a string, it will be interpreted
        as the filename of the font.
        pdf.use14corefontsZafm)Zfontext	directoryNzAssigning font %s = %r)rD   rE   r\   r>  _fontManagerZ_find_fonts_by_propsRendererPdf_afm_font_dirr  getnextr  _logdebug)r   Zfontprop	filenamesZfirst_FxfnameFxr*   r*   r+   fontName  s&    




zPdfFile.fontNamec                 C   s   | j |j}|dur|jS ttd}||j }|jdu rTtd	|j
|jt| j}td||j tj|||j|j
|j|jd| j |j< |S )z
        Given a dvi font object, return a name suitable for Op.selectfont.
        This registers the font information in ``self.dviFontInfo`` if not yet
        registered.
        Nz
pdftex.mapzNNo usable font file found for {} (TeX: {}); the font may lack a Type-1 versionzAssigning font %s = %s (dvi))dvifontpdfnamefontfilebasefontencodingfileeffects)r  r  texnamer  r   Z
PsfontsMapZ_find_tex_filer  r   r   Zpsnamer  r  r  r  typesSimpleNamespaceencodingr  )r   r  Zdvi_infoZtex_font_mapZpsfontr  r*   r*   r+   dviFontName  s,    


zPdfFile.dviFontNamec                 C   s   i }t | j D ](\}}|j}td| | |||< qt | jD ]j}| j| }td| |drtd | 	|||< qFtd | j
j|}|rF| ||||< qF| | j| d S )Nz"Embedding Type-1 font %s from dvi.zEmbedding font %s.z.afmzWriting AFM font.zWriting TrueType font.)rY  r  r^   r  r  r  _embedTeXFontr  endswith_write_afm_fontr  usedr  embedTTFrE  r  )r   ri  Zdvinamerc   r  r  charsr*   r*   r+   r    s     



zPdfFile.writeFontsc                 C   sr   t |d}t|}W d    n1 s(0    Y  | }tdtdt|tdd}| d}| || |S )Nrbru  Type1ZWinAnsiEncoding)r   r   BaseFontEncodingfont dictionary)openr   Zget_fontnamerN   r  rE  )r   r  r:  r`  fontnamefontdictfontdictObjectr*   r*   r+   r    s    &
zPdfFile._write_afm_fontc                 C   s`  t d|jj|j | d}| ||jj | d}tdtddt	|jjd |d}|j
d urtd	dgttt|j
d
|d	< |jd u rt d|j t|j|d< | || |S t|j}|jr||j}t|jd |d< |jdd|jddf}| j|j|f}|d u rH| ||j}|| j|j|f< ||d< | || |S )Nz#Embedding TeX font %s - fontinfo=%sfont widthsr
  ru  r  r   r"   )r   r   	FirstCharLastCharWidthsr	  r   ZDifferenceszBecause of TeX configuration (pdftex.map, see updmap option pdftexDownloadBase14) the font %s is not embedded. This is deprecated as of PDF 1.5 and it may cause the consumer application to show something that was not intended.r  FontNameZslant        extend      ?FontDescriptor)r  r  r  r  __dict__r  rE  widthsrN   r0   r  r\  r   Z
_parse_encr  warningr  r	   Z	Type1Fontr  	transformpropr  r  createType1Descriptor)r   ZfontinfowidthsObjectr  r  t1fontr  Zfontdescr*   r*   r+   r     sR    


	



zPdfFile._embedTeXFontc           
      C   s   |  d}|  d}|jd }|jd }d}|r8|dO }|dO }|rL|dO }t|}td	t|jd
 ||j||j|jdd||jd dd}	| ||	 | j|d	|j
d d t|j
d t|j
d ddd |S )Nfont descriptorz	font fileItalicAngleZisFixedPitchr   r"      rL  r  r  rK  i  Z
FamilyName2   )r   r  FlagsFontBBoxr"  AscentDescent	CapHeightXHeightZFontFileZ
FontFamilyStemVrC   rM  )Length1ZLength2ZLength3r  )r  r  r   rN   rW  ascender	descenderrE  r  r2   partsr0   )
r   r   r  fontdescObjectfontfileObjectZitalic_angleZfixed_pitchflagsZft2font
descriptorr*   r*   r+   r  0  s@    



zPdfFile.createType1Descriptorc                 C   s4   |  |}d|j tjtj|d |gS )N-r   )r  r2   rO   r   rV   r  splitextbasename)r   r  
glyph_namer  r*   r*   r+   _get_xobject_glyph_nameo  s    
zPdfFile._get_xobject_glyph_namesO  /CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo
<< /Registry (Adobe)
   /Ordering (UCS)
   /Supplement 0
>> def
/CMapName /Adobe-Identity-UCS def
/CMapType 2 def
1 begincodespacerange
<0000> <ffff>
endcodespacerange
%d beginbfrange
%s
endbfrange
endcmap
CMapName currentdict /CMap defineresource pop
end
endc                    sl  t }tjd |jdfdd  fdd} fdd}|j| d	d
t|	dpddd}|	dpddi}|j
}|j}	d}
d}|t@ r|
dO }
|r|
dO }
n|
dO }
|	t@ r|
dO }
td|
 fdd|jD  |jdd |jdd |d dd |d |d d dd
}dkrR||||S dkrh||||S dS ) z9Embed the TTF font from the named file into the document.pdf.fonttypeTc                 S   s8   | | d }|rt |S |dk r*t|S t|S dS )z2Convert font coordinates to PDF glyph coordinates.rK  r   N)r  rr   floorceil)r7   Zupenearestr  r*   r*   r+   cvt  s    
zPdfFile.embedTTF.<locals>.cvtc                    sr   d} d} d} d}g }d\}}	fddjD }
td||	|td	|d
 |
g d|td|d|d}ddlm   fddt 6 td fddt||	d D }W d   n1 s0    Y  t	||d< g }g }t
 }|D ]L}|}|}|| |}|dkrH|||f n
|| q|  d}|D ]4\}}||d kr|| |t| |}qft|}i }t|D ]}|| }i }||v rtdtd|
d}||dd d } d}j|||d  ||v r2|}|j|< n|||< q|| || || || |S )!z5The Type 3-specific part of embedding a Truetype fontr  r!  r
  zcharacter procs)r   r   c                    s   g | ]} |d dqS Fr<  r*   rs  r=  r*   r+   r     rC   z;PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.<listcomp>ru  ZType3r  )MbP?r   r   rA  r   r   r	  r  )r   r  r  r  r  r   rN   r&  Z
FontMatrixZ	CharProcsr	  r  r   )cp1252c                    s*   t  j|  }j|ttB dj}|S )Nr2  )r   decoding_table	load_charr   r   rV  )charcoder6   rw   )rB  r=  r`  r*   r+   get_char_width  s
    z?PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.get_char_widthignorec                    s   g | ]} |qS r*   r*   )r?   rF  )rG  r*   r+   r     s   r"   NMaxWidthr   rv  Formr   r   BBox   d1rM  charProcr  )r  rW  rN   	encodingsrB  warningscatch_warningsfilterwarningsr   r   r_   get_char_indexr1   r^  addsortrd  rY  findr  r8  r  rE  )r`  
charactersr3  r  r0  r  ZcharprocsObjectZdifferencesArrayZ	firstcharZlastcharrW  r  r  r_  ZdifferencesZmulti_byte_charsr|   ccodegindr7  Zlast_crO   rawcharprocsZ	charprocscharnamestreamcharprocDictcharprocObject)r=  r  r  r   )rB  r`  rG  r+   embedTTFType3  s    






$






	

z'PdfFile.embedTTF.<locals>.embedTTFType3c           '         s   d} d} d} d} d} d} d}	dd	d
 |D }
td|
 t|
}tdtj|	 j
 | }t|} tdtddddd|||d}tdtdtd|g|	d}||d< j|| d|	 j
id dgd }g }d}|D ]Z}|}| |}| j|ttB d}|| |jf |dk rlt|||< t||}q|  |d|d  }d}g }d}g }|D ]f\}}||d kr|| ||g |||g n|d  | ||d  d< t||}|}qg }|D ]P\}}|d!kr,qtd!|}|d"||d#d$d
 t||d D f  qjt|d%|f }g }|D ]&}t|s||}|| q fd&d'|jD } t|}!t|!D ]h}"|!|" }#td(td)| d*}$|#|# d+d, d }# d-}%j|%|#|$d !|"}&|%j"|&< qd|#d.}|| |	| ||d/< $|| $|| $|| $|| |S )0z6The Type 42-specific part of embedding a Truetype fontr!  zCID font dictionaryzType 0 font dictionaryzCIDToGIDMap streamzfont file streamzType 0 widthszToUnicode map c                 s   s   | ]}t |V  qd S r=   )chrr   r*   r*   r+   r     rC   z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>zSUBSET %s characters: %szSUBSET %s %d -> %dru  ZCIDFontType2ZAdobeZIdentityr   )RegistryZOrderingZ
Supplement)r   r   r  ZCIDSystemInfor  WZCIDToGIDMapZType0z
Identity-H)r   r   r  r	  ZDescendantFonts	ToUnicodeZ	FontFile2r,  r   i   rC  Nr"   rJ  rS  r   s   <%04x> <%04x> [%s]r-   c                 s   s   | ]}d | V  qdS )s   <%04x>Nr*   rs  r*   r*   r+   r   f  rC   r.   c                    s   g | ]} |d dqS r>  r*   rs  r@  r*   r+   r   q  rC   z<PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<listcomp>rv  rK  rL  rN  rM  rO  utf-16berI  )%r  r2   r  r  r#   Zget_glyphs_subsetrV   statst_size	getbuffernbytesr   rN   r  rD  rT  rE  r   r   r1   rV  rb  r   rV  r   r   _identityToUnicodeCMapr0   r   rW  rd  rY  rW  r8  r  r   rE  )'r`  rX  r3  r0  ZcidFontDictObjectZtype0FontDictObjectZcidToGidMapObjectr1  ZwObjectZtoUnicodeMapObjectZ
subset_strZfontdataZ	full_fontZcidFontDictZtype0FontDictZcid_to_gid_mapr  Z	max_ccoder|   rY  rZ  r   Z
last_ccodew	max_widthZunicode_groupsrw   Zunicode_bfrangestartrF  Zunicode_cmapr_  rW  r[  r\  r]  r^  r_  rO   r=  r  r   r  r   r*   r+   embedTTFType42  s    
















	
z(PdfFile.embedTTF.<locals>.embedTTFType42r   rZ   pcltr   )	capHeightxHeightpostZitalicAngler   r   Fr"   r#      rL  r  c                    s   g | ]} |d dqS r>  r*   rs  r@  r*   r+   r     rC   z$PdfFile.embedTTF.<locals>.<listcomp>r?  rs  rt  )
r   r  r%  r&  r'  r(  r)  r*  r"  r+  r   r   N)r   r\   r>  rT  r  r[  Zget_charmapr   rN   Zget_sfnt_tableZ
face_flagsZstyle_flagsr   r   rW  r-  r.  )r   r  rX  r`  r`  rq  rr  ru  ffZsfr2  Zsymbolicr3  r*   rp  r+   r    sP    
j 
	



zPdfFile.embedTTFc                 C   sN   | j |d}|dur|d S t| j}|td|d |d df| j |< |S )z?Return name of an ExtGState that sets alpha to the given value.Nr   rw  r"   )r   CAca)r  r  r  r  rN   )r   alphastaterO   r*   r*   r+   
alphaState  s    
zPdfFile.alphaStatec                 C   s   | j |d}|dur|d S t| j}| d}|tddtdtddg|d	d
f| j |< | j|tdtddtdtddg ddd|iig ddtdtj	gf |S )aA  
        Return an ExtGState that sets the soft mask to the given shading.

        Parameters
        ----------
        smask : Reference
            Reference to a shading in DeviceGray color space, whose luminosity
            is to be used as the alpha channel.

        Returns
        -------
        Name
        Nr   z transparency group for soft maskrw  FMaskZ
Luminosityr"   )r   r   BCG)r   ZAISSMaskrv  rK  ZTransparency
DeviceGray)r   CS)r"   r   r   r"   r   r   ry  r   )r   r   r"   r"   )r   r   ZFormTypeGroupMatrixr  rM  )
r  r  r  r  r  rN   r  r1   r   r/  )r   smaskr|  rO   ZgroupObr*   r*   r+   _soft_mask_state  s<    



zPdfFile._soft_mask_statec                 C   s*   |  | jtg | j | j  d S r=   )rE  r  r   r  r  r  r   r*   r*   r+   r  	  s    zPdfFile.writeExtGSTatesc                 C   s8   | j D ],\}}}| |jd | | j|  |   qd S r=   )r  r  r   r  r  )r   r  
attributescontentr*   r*   r+   r    s    
zPdfFile._write_soft_mask_groupsc                 C   sn   |d ur<|\}}}|d ur"t |}|d ur2t |}|||f}| j|d }|d urV|S t| j}|| j|< |S r=   )r   r  r  r  r  )r   hatch_styleedgeZfacehatchpatternrO   r*   r*   r+   hatchPattern  s    



zPdfFile.hatchPatternc           
      C   sF  t  }d}| j D ]\}}| d}|||< ddd d D i}| |jd tddddd	d	||g|||dd	d	dd	| jd
 gd	 |\}}}	| 	|d	 |d |d t
j |d ur| 	|d	 |d |d t
jd	d	||t
jt
j
 | 	tjd t
j | j	| jt|	t |dd  | 	t
j |   q| | j| d S )N      R@zhatch patternZProcsetsc                 S   s   g | ]}t |qS r*   ro  rs  r*   r*   r+   r   1  rC   z(PdfFile.writeHatches.<locals>.<listcomp>rt  rx  r"   r   r  )	r   ZPatternTypeZ	PaintTypeZ
TilingTyperM  ZXStepZYStepr  r  rM  zhatch.linewidthFsimplify)r   r  r^   r  r  r  r   rN   rx   r  r   r  r  r  r,   r\   r>  r-  pathOperationsr   r  r   scaler  r  rE  r  )
r   Z	hatchDictZsidelenr  rO   r  resZ
stroke_rgbZfill_rgbr  r*   r*   r+   r  *  sJ    





zPdfFile.writeHatchesc                 C   s>   t dt| j }| d| }| j||||f ||fS )a  
        Add a Gouraud triangle shading.

        Parameters
        ----------
        points : np.ndarray
            Triangle vertices, shape (n, 3, 2)
            where n = number of triangles, 3 = vertices, 2 = x, y.
        colors : np.ndarray
            Vertex colors, shape (n, 3, 1) or (n, 3, 4)
            as with points, but last dimension is either (gray,)
            or (r, g, b, alpha).

        Returns
        -------
        Name, Reference
        zGT%dzGouraud triangle )rN   r0   r  r  r1   )r   pointscolorsrO   r  r*   r*   r+   addGouraudTrianglesP  s    zPdfFile.addGouraudTrianglesc                 C   s  t  }| jD ]h\}}}}|||< |j}||d |d  df}|jd }|dv sXJ ||d |d  |f}	|dkr~d}tj|ddd }
tj|ddd }d	||
  }| |jd dd
ddt	|dkrdndd|
d |d |
d |d gddg|  d tj
|d |d  fdddd|ffgd}d|d< ||
 | |d< |	d d d |f d |d< | |  |   q| | j| d S )Nr   r"   rM  r"   r#  r#  r   rN  r   l    rw     r  r  F)ZShadingTypeZBitsPerCoordinateBitsPerComponentZBitsPerFlag
ColorSpaceZ	AntiAliasZDecode)r2  u1)r  z>u4)rM  r  r  )Zdtyper2  r  g     o@)r   r  shapereshaper   r   r   r  r   rN   emptyr   tobytesr  rE  r  )r   ZgouraudDictrO   r  r  r  r  Zflat_pointsZcolordimZflat_colorsZ
points_minZ
points_maxfactorZ	streamarrr*   r*   r+   r  g  sV    



zPdfFile.writeGouraudTrianglesc                 C   sT   | j t|d}|dur"|d S t| j}| d| }|||f| j t|< |S )z=Return name of an image XObject representing the given image.Nr"   zimage )r  r  r   r  r  r  )r   r  entryrO   r  r*   r*   r+   imageObject  s    
zPdfFile.imageObjectc                 C   s   |ddd }|j dkr |dfS |ddddddf }tj|dd}|jd dkr|dddddf d }t|d	krd}qtj|dd}nd}||fS dS )
z
        Unpack image array *im* into ``(data, alpha)``, which have shape
        ``(height, width, 3)`` (RGB) or ``(height, width, 1)`` (grayscale or
        alpha), except that alpha is None if the image is fully opaque.
        NrS  rM  r   C)orderr#  ).Nr   )ndimr   rU  r  rZ  )r   imrgbr{  r*   r*   r+   _unpack  s    
zPdfFile._unpackc           	      C   s   t  }|j|dd |d d}d }}td|d\}}|dv r||}t||krftd|d	kr|t|d }q|d
kr|}q|dkr||7 }n|dkrqn||d |dd q*|||fS )zn
        Write the image *img* into the pdf file using png
        predictors with Flate compression.
        rB  )r   r  rC   Ns   !L4s)   IHDR   PLTE   IDATztruncated datar  r  r  s   IENDr"   r#  )	r   saveseekstructunpackreadr0   RuntimeErrorrY   )	r   imgbufferpng_data	bit_depthpaletter7   r   rH  r*   r*   r+   	_writePng  s*    


zPdfFile._writePngc                 C   s  |j \}}}tdtd||tddd| dd}|r@||d< tjd	 rF|j d
 dkrf|jd
d}t|}|jdd}	|dkr(|	dur(t|	}
t	tdtj
}t	tdtj}|jd|||
d}| |\}}}|du s|du rtd|d|
d  }td|
d t|f |d< ||d< d}n| |\}}}d||d}nd}| j|| d||d |rv| j| n| j|  |   dS )a  
        Write the image *data*, of shape ``(height, width, 1)`` (grayscale) or
        ``(height, width, 3)`` (RGB), as pdf object *id* and with the soft mask
        (alpha channel) *smask*, which should be either None or a ``(height,
        width, 1)`` array.
        rv  r   r  r  r"   r   r  )r   r   ZWidthZHeightr  r  r  r9  rS  r"   rN  r   )Z	maxcolorsr   NZDitherPaletteP)modeditherr  r  zinvalid PNG headers   [/Indexed /DeviceRGB %d %s]r  r  
   )Z	PredictorZColorsColumnszlength of image stream)rB  )r  rN   r\   r>  Zsqueezer   Z	fromarrayZ	getcolorsr0   getattrNONEZADAPTIVEconvertr  r  r   r   r  r  r  r   r  r  )r   rH  r   r  rx   rw   Zcolor_channelsr   r  Z
img_colorsZ
num_colorsr  Zpmoder  r  r  _rB  r*   r*   r+   	_writeImg  sd    
zPdfFile._writeImgc                 C   s^   | j  D ]N\}}}| |\}}|d urD| d}| ||j nd }| ||j| q
d S )Nr  )r  r  r  r  r  r   )r   r  rO   r  rH  ZadataZsmaskObjectr*   r*   r+   r    s    
zPdfFile.writeImagesc                 C   s   | j ||dd}t|t|t|||f}	| j|	}
|
du rtdt| j }| dt| j }||}||||g| j|	< n|
d |k r||
d< |
d }|S )z<Return name of a marker XObject representing the given path.Fr  NzM%dz	marker %drS  r   )	r  r   r   r  r  rN   r0   r  get_extents)r   r  r  r,   r  lw	joinstylecapstylepathopskeyr4   rO   r  rW  r*   r*   r+   markerObject  s    
zPdfFile.markerObjectc           
   	   C   s   | j  D ]\\}}}}}\}}}}	||	d }| |jd tdtdt|jd | t	j
| tj | t	j| tj | j|  | t|| |   q
d S )N   rv  rK  rL  )r  r^   paddedr  r   rN   r   extentsr  r  r  r   r#  	capstylesr$  r  r  )
r   r  r,   r  r  r  rO   r  rW  r  r*   r*   r+   r  5  s"    

zPdfFile.writeMarkersc           	      C   sP   t dt| j }| dt| j }| j||||| | |||f	 |S )NzP%dzpath %d)rN   r0   r  r  r1   get_joinstyleget_capstyle)	r   r   r  r  r  r  r  rO   r  r*   r*   r+   pathCollectionObjectK  s    zPdfFile.pathCollectionObjectc              
   C   s   | j D ]\	}}}}}}}}}	| j||dd}
||}tt|jsRg d}n||}t|j}| 	|j
d tdtd|d | tj| tj | tj| tj | j|
  | t||	 |   qd S )NFr  r   r   r   r   rv  rK  rL  )r  r  r  r   rZ  r   r  r  r   r  r   rN   r  r  r  r   r#  r  r$  r  r  )r   rO   r  r  r  r  r  r  r  r  r  rW  r  r*   r*   r+   r  S  s,    




z$PdfFile.writePathCollectionTemplatesc                 C   s8   t t| ||||dtjjtjjdtjjtjjgdgS )Nr  rC   T)	r   r!   r]  r   r  r  r  r  r  )r  r  r.  r  sketchr*   r*   r+   r  h  s    
zPdfFile.pathOperationsFc                 C   sN   |r$dd| j d | jd f}|j}nd }d}| j|||||d}| j|  d S )Nr  r  F)r  r  )rw   rx   Zshould_simplifyr  r  )r   r  r  r.  r  r  cmdsr*   r*   r+   	writePathq  s    zPdfFile.writePathra  c                 C   s$   t | j}| jdd|g t|S )z
        Reserve an ID for an indirect object.

        The name is used for debugging in case we forget to print out
        the object with writeObject.
        Nr   )r  r|  r}  r1   r   )r   rO   r   r*   r*   r+   r  |  s    
zPdfFile.reserveObjectc                 C   s   | j  | j | j| d< d S Nr   )r:  rA  r  r}  r   r*   r*   r+   r=    s    zPdfFile.recordXrefc                 C   s   |  |j |||  d S r=   )r=  r   r   )r   objectr   r*   r*   r+   rE    s    zPdfFile.writeObjectc                 C   s   | j  | j | _| dt| j  t| jD ]P\}\}}}|du rXtd||f q0|dkrddnd}d|||f }| | q0dS )zWrite out the xref table.s
   xref
0 %d
NzNo offset for object %d (%s)rf  r   r   s   %010d %05d %b 
)	r:  rA  r  	startxrefr   r0   r}  r/   AssertionError)r   r5   offsetZ
generationrO   r  r  r*   r*   r+   r    s    
zPdfFile.writeXrefc                 C   s    |  d| _| | j| j dS )z8Write out the info dictionary, checking it for good formrc   N)r  
infoObjectrE  r  r   r*   r*   r+   r    s    zPdfFile.writeInfoDictc                 C   s>   |  d |  tt| j| j| jd |  d| j  dS )zWrite out the PDF trailer.s   trailer
)SizeZRootZInfos   
startxref
%d
%%%%EOF
N)r   r   r0   r}  r  r  r  r   r*   r*   r+   r    s    
zPdfFile.writeTrailer)N)NN)N)NNN)FN)ra  )4r   r   r   r   r   r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r   r  r8  rl  r  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r=  rE  r  r  r  __classcell__r*   r*   r  r+   re    sd   i	!
:?  ?4	&,
;


re  c                       s   e Zd ZedZdZ fddZdd Zd)dd	Z	d
d Z
d*ddZd+ddZdd Zd,ddZdd Zdd Zd-ddZdd ZddddZd d! Zd.d#d$Zd%d& Zd'd( Z  ZS )/r  zfonts/pdfcorefontsr  c                    s(   t  || || _|  | _|| _d S r=   )rz  r   r   new_gcr   	image_dpi)r   r   r  rx   rw   r  r*   r+   r     s    
zRendererPdf.__init__c                 C   s   | j j| j   d S r=   )r   r  r   r  r   r*   r*   r+   r    s    zRendererPdf.finalizeNc                 C   s   t |dd}||_t |dd}| d u r8|jddd |jrN|j|jf|_n:|d u sbt|dk rt|jd	 d
f|_n|jd	 |d	 f|_| j	
|}|r| jj|  ||_||_d S )N
_fillcolorr  r  r  _effective_alphasr  r  r  T)ZisRGBAr#  r   r  )r  r  Zget_rgbZset_foreground_forced_alpha_alphar  r0   _rgbr   deltar   r  )r   r   	fillcolorZ	orig_fillZorig_alphasr  r*   r*   r+   check_gc  s    zRendererPdf.check_gcc                 C   s
   | j d S )Nr  )r  r   r*   r*   r+   get_image_magnification  s    z#RendererPdf.get_image_magnificationc                 C   s   |j d d \}}|dks"|dkr&d S |d u r8|d | | d| | j }d| | j }| j|}|d u r| jtj|dd|||tj	|tj
tj nP|  \}	}
}}}}| jtjdddd||tj	|	|
||||tj	|tj
tj d S )NrM  r   r  r  r"   )r  	set_alphar  r  r   r  r  r   r&  r  r  r'  frozenZ	to_values)r   r   rG   rv   r  r  hrm  ZimobZtr1Ztr2Ztr3Ztr4Ztr5Ztr6r*   r*   r+   
draw_image  s(    





zRendererPdf.draw_imagec                 C   sH   |  || | j|||d u o(| d u |  | j| j  d S r=   )r  r   r  Zget_hatch_pathZget_sketch_paramsr  r   paint)r   r   r  r  rgbFacer*   r*   r+   	draw_path  s    zRendererPdf.draw_pathc           $      C   s   d}t |}t |}t|s0d}|  }n0t |d d df |d kr\|d dk}nd}t|snd}nJt t |	dkrd}n0t |d d df |d kr|d dk}nd}t|dkrt|d jnd}| |||||}|| d || k }|r|s,t| |||||||||	|
|||S t 	|	}g }t
| |||D ].\}\}}| j||||||}|| qL| jj}|| j   d\}}| |||||||	|
|||D ]T\}}}} }!| | |! || ||  }"}#|d	ddd	|"|#tj|tj	 || }}q|| j   d S )
NTFr   )r   r   r  r   r  rv  r"   )r   asarrayr0   Z	get_hatchrZ  r   Z_iter_collection_uses_per_pathr   draw_path_collectionr   r/   Z_iter_collection_raw_pathsr   r  r1   r  r   pushZ_iter_collectionr  r   r  r  pop)$r   r   Zmaster_transformr  Zall_transformsoffsetsZoffset_transZ
facecolorsZ
edgecolorsZ
linewidthsZ
linestylesZantialiasedsurlsZoffset_positionZcan_do_optimizationr  r  Zlen_pathZuses_per_pathZshould_do_optimizationr  Z
path_codesr5   r  r  rO   r  lastxlastyZxoZyoZpath_idZgc0r  dxdyr*   r*   r+   r     sj    




z RendererPdf.draw_path_collectionc                 C   sp  t |}t |}|| || d k r>t| |||||| d S | || ||}	| }
| jj}| j|||	|
| j	j
| | }|tj d\}}|j|dd| jjd | jjd fddD ]\}}t |r|dd  \}}d|  kr | jjd krn qd|  kr$| jjd ks(q q|| ||  }}|dddd||tj|tj	 || }}q|tj d S )	Nr  rv  r   r  F)r.  r  rJ  r"   )r0   r   draw_markersr  r,   r  r   r  r  r   
_linewidthr  r  r   r&  iter_segmentsrw   rx   r  r  r'  )r   r   Zmarker_pathZmarker_transr  r  r  Zlen_marker_pathZusesr,   r  r  markerr  r  r   coderG   rv   r  r  r*   r*   r+   r  F  sH    

"


zRendererPdf.draw_markersc                 C   s    |  ||d|d| d S )N)r"   r   rM  )r"   r   r#  )draw_gouraud_trianglesr  )r   r   r  r  r  r*   r*   r+   draw_gouraud_trianglel  s    
z!RendererPdf.draw_gouraud_trianglec                 C   s  t |t |ksJ t |dkr$d S |jdks2J |jd dksDJ |jd dksVJ |jdksdJ |jd dksvJ |jd dv sJ |j}||d |d  df}||}||}| j||\}}| jj}	|jd dkr
|d | 	| |	|t
j d S |d }
t|
|d d d d df rT||
 | 	| |	|t
j n`|d d d d df d d d d d f }
| j||
\}}| j|}|	t
j|t
j|t
jt
j d S )Nr   r   r"   rM  r  r  )r   r   r   )r0   r  r  r  r  r   r  r  r  r  r   r/  r   Zallcloser  r&  r%  r'  )r   r   r  r  r  r  ZtpointsrO   r  r  r{  Zsmask_obZgstater*   r*   r+   r  p  s@    



 

(z"RendererPdf.draw_gouraud_trianglesr   c              	   C   s   ||  krdkr4n n| j || || tj nPt|}| j t|t|t| t|||tj | j ddtj d S r  )	r   r  r   r(  rr   rs   ru   rt   r*  )r   rG   rv   ry   oldxoldyZoldangler*   r*   r+   _setup_textpos  s    
zRendererPdf._setup_textposc                 C   s  | j j|d|\}}}	}
}| d urL| jjd d t|||||| tj	d }t
|}| jtj | jt
|t
|t
| t
|||tj | ||j d}d\}}g }| jtj |
D ]\}}}}}| jj|| |j}t||s||||||f q| ||d|| || }}||f|krd| j| j||tj ||f}| j| t||tj q| jtj |D ](\}}}}}|  |||!||| q|D ]0\}}}}| jtj||||tj"tj#tj$ q| jtj$ d S )Nr  rS  r"   r9  )NNrv  r   )%Z
_text2pathZmathtext_parserparser   r   r  r1   r   r\   r>  rr   rs   r  r   r&  ru   rt   r  r  r  r  r  Ztrack_glyphr  r   r  r  r)  encode_stringrb  r+  r  _draw_xobject_glyphrT  r  r,   r'  )r   r   rG   rv   r6   r  ry   rw   rx   ZdescentZglyphsZrectsr   rz   	prev_fontr  r  Zunsupported_charsr`  fontsizenumoxZoyr  r*   r*   r+   draw_mathtext  sV    


zRendererPdf.draw_mathtext)mtextc          #   	   C   s  |   }| }	|||	}
t|
d}|\}W d    n1 sD0    Y  | d ur| jjd d t	||||j
|j| d g  }}|jD ]X\}}}}}||kr| j|}|d||jgg7 }|}|d||t|gg|| gg7 }qd\}}}	|t|d k r|||d  \}}|d dkr4|d }	n|d |d   krTdkrn n|d |d kr|d	 |d  }t|d
k r|d d  |d d 7  < |d	  |d	 |d  7  < n0|d  |d |	 |d d g7  < |d	 |d	< ||d = q|d7 }qt |||}| ||j | jtj d\}}}}|D ]}|d dkrv| j|d |d tj n|d dkr||d |d f\}}| ||||| || }}t|d dkr| j|d d tj n| j|d tj n
dsHJ qH| jtj |   }|!| |"d t#j$t#j%t#j%t#j%t#j&g}|j'D ]X\}}} }!t#||g||! |g||! ||  g|||  gddgg|}"| (||"||j qRd S )Nr  rS  r"   r`  r  )r   r   NrM  r   r#  g?r   g     @@r  F))Zget_texmanagerget_size_in_pointsZmake_dvir   ZDvir   r   r  r1   r   rw   rx   r  r  sizer   r0   absr   Z
rotate_degr   r  r  r  r   r  r)  r  r  r+  r,  r  r  copy_propertiesZset_linewidthr   ZMOVETOZLINETOZ	CLOSEPOLYZboxesr  )#r   r   rG   rv   r6   r  ry   r  Z
texmanagerr  ZdvifileZdvir  Zoldfontseqx1y1r  r   rw   r  r5   ZcurxeltZnxtr  ZmytransZcuryr  r  Zboxgcr  r  rm  r  r*   r*   r+   draw_tex  sx    $
"

6$




*zRendererPdf.draw_texc                 C   s    |dv r| ddS | ddS )Nr  rB  rZ   rg  )r   )r   r6   r   r*   r*   r+   r  +	  s    zRendererPdf.encode_stringFc	              	      s   ||j |r&||||||S |  tjd rH|}	dn$|}	jj	
|	| tjd | d ur|	| |	 \}
}jjd d t||||
d |d | dvrjtjj| tj ||| j|tjtj ng }g }d}|	}tj||	tdD ]}tt|jr|sX|j |krr||j |j!g f |j }|j"r|d d	 |j" |d d	 |j d
}n||j |j!|j#f d}q0jtj$ t%&|}jt%'|t%(|t%(| t%'|||tj) jtj d}|D ]n\}}}j|j*}j| tj |dd|dd j fddt+,|t-D tj. |}q(jtj |D ]\}}}/| ||d qjtj0 d S )Nr  r"   r9  rS  rL  )r   r   T)Z	kern_moderM  Fr   c                    s:   g | ]2\}}|t kr$d t|   nd|qS )ira  )r   r  r  r2   )r?   tpr   r  r   r   r*   r+   r   	  s   z)RendererPdf.draw_text.<locals>.<listcomp>)1r  r  r  r  r\   r>  Z_get_font_afmZ_get_font_ttfr   r  trackr   Zset_textZget_width_heightr  r1   r   r  r   r  r  r)  r  r  r+  r  r   Zlayoutr   r   r   char	ft_objectrG   Z	prev_kern	glyph_idxr&  rr   rs   ru   rt   r  r  r   groupbyr   r,  r	  r'  )r   r   rG   rv   r6   r  ry   Zismathr  r`  rw   rx   Zsinglebyte_chunksZmultibyte_glyphsZprev_was_multibyter
  itemrz   Zprev_start_xr  Zstart_xZkerns_or_charsZft_namer  r*   r  r+   	draw_text0	  s    










zRendererPdf.draw_textc                 C   sR   | |}| j|j|}| jtjd| ddd| ||tjt|tj	tj
 dS )z<Draw a multibyte character from a Type 3 font as an XObject.rA  r   N)r^  r   r8  r  r  r   r&  r  rN   r  r'  )r   r`  r  r  rG   rv   r7  rO   r*   r*   r+   r	  	  s    

zRendererPdf._draw_xobject_glyphc                 C   s
   t | jS r=   )r  r   r   r*   r*   r+   r  	  s    zRendererPdf.new_gc)N)N)N)N)r   r   r   )FN)r   r   r   r
   Z_get_data_pathr  Z_use_afm_rc_namer   r  r  r  r  r  r  r  r  r  r  r  r  r  r!  r	  r  r  r*   r*   r  r+   r    s(   



	G 
&(

6S
dr  c                
       s  e Zd Z fddZdd Zdd Zdd Zd	d
 ZddddZddddZ	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&efd'efd(e
fd)efd*efd+efd,efd-efd.eff	Zd/d0 Z fd1d2Zd3d4 Z  ZS )5r  c                    s&   t    d| _d| _|| _d | _d S )Nr  r  )rz  r   r  r  r   parent)r   r   r  r*   r+   r   	  s
    
zGraphicsContextPdf.__init__c                 C   s   t | j}|d= |d= t|S )Nr   r"  )r   r  repr)r   rn   r*   r*   r+   r   	  s    
zGraphicsContextPdf.__repr__c                 C   s0   | j dko.| jdko.t| jdkp.| jd dkS )z
        Predicate: does the path need to be stroked (its outline drawn)?
        This tests for the various conditions that disable stroking
        the path, in which case it would presumably be filled.
        r   r   r  )r  r  r0   r  r   r*   r*   r+   r  	  s    zGraphicsContextPdf.strokec                 G   s>   t |r|d }n| j}| jp<|duo<t |dkp<|d dkS )z
        Predicate: does the path need to be filled?

        An optional argument can be used to specify an alternative
        _fillcolor, as needed by RendererPdf.draw_markers.
        r   Nr   r  )r0   r  _hatch)r   argsr  r*   r*   r+   r,   	  s    
zGraphicsContextPdf.fillc                 C   s   t |  |  S )zo
        Return the appropriate pdf operator to cause the path to be
        stroked, filled, or both.
        )r   r  r,   r  r   r*   r*   r+   r  	  s    zGraphicsContextPdf.paintr   r"   rM  )Zbuttr  Z
projecting)Zmiterr  Zbevelc                 C   s   | j | tjgS r=   )r  r   r$  r   styler*   r*   r+   capstyle_cmd	  s    zGraphicsContextPdf.capstyle_cmdc                 C   s   | j | tjgS r=   )r  r   r#  r&  r*   r*   r+   joinstyle_cmd	  s    z GraphicsContextPdf.joinstyle_cmdc                 C   s
   |t jgS r=   )r   r-  )r   rw   r*   r*   r+   linewidth_cmd	  s    z GraphicsContextPdf.linewidth_cmdc                 C   s(   |\}}|d u rg }d}t ||tjgS r  )r   r   r"  )r   dashesr  dashr*   r*   r+   dash_cmd	  s
    zGraphicsContextPdf.dash_cmdc                 C   s   | j |}|tjgS r=   )r   r}  r   r%  )r   r{  Zforcedeffective_alphasrO   r*   r*   r+   	alpha_cmd	  s    zGraphicsContextPdf.alpha_cmdc                 C   sZ   |s*| j d ur| | j S tdtjgS n,|| j |f}| j|}tdtj|tjgS d S )Nr  rx  )r  fillcolor_cmdrN   r   r   r   r  r!  )r   r  Zhatch_colorr  rO   r*   r*   r+   	hatch_cmd	  s    

zGraphicsContextPdf.hatch_cmdc                 C   sZ   t jd rg S |d |d   kr.|d kr@n n|d tjgS g |d d tjS d S Nzpdf.inheritcolorr   r"   rM  r   )r\   r>  r   r  r  r   r  r*   r*   r+   rgb_cmd	  s
    
$zGraphicsContextPdf.rgb_cmdc                 C   sb   |d u st jd rg S |d |d   kr6|d krHn n|d tjgS g |d d tjS d S r2  )r\   r>  r   r  r  r3  r*   r*   r+   r0  	  s
    $z GraphicsContextPdf.fillcolor_cmdc                 C   s*   t | j}||  | j|_|| _tjgS r=   )r  r   r  r"  r   r&  )r   r"  r*   r*   r+   r  
  s
    

zGraphicsContextPdf.pushc                 C   s,   | j d usJ | | j  | j j | _ tjgS r=   )r"  r  r   r'  r   r*   r*   r+   r  
  s    
zGraphicsContextPdf.popc                 C   s   g }| j | jf||fkr2| jdur2||   q| j | jf||fksP| jdu r||   | j |kr||tjtjtj	g | j|kr|
 \}}|tj||ddtjtj	g  |S )z1Set clip rectangle. Calls `.pop()` and `.push()`.NFr  )	_cliprect	_clippathr"  r  r  r  r   r  r.  r  Zget_transformed_path_and_affinere  r  )r   ZcliprectZclippathr  r  Zaffiner*   r*   r+   clip_cmd
  s&    


zGraphicsContextPdf.clip_cmd)r5  r6  )r  r  r  )Z	_capstyler  )Z
_joinstyle)r  )Z_dashes)r  r$  Z_hatch_colorc           
   
      s  g }d}| j D ]\}}d}|D ]}t| |}t |}	z*|du sJ|	du rT||	u}nt||	k}W n@ ty   t|}t|	}	|j|	jkpt||	k}Y n0 |r  qq |dkr|rd}|r|dkrd} fdd|D }	||| g|	R   |D ]}t	| |t | qq|S )zy
        Copy properties of other into self and return PDF commands
        needed to transform self into other.
        FNr9  Tr8  c                    s   g | ]}t  |qS r*   )r  )r?   pr   r*   r+   r   V
  rC   z,GraphicsContextPdf.delta.<locals>.<listcomp>)
commandsr  r   r   r   r  r  anyr  setattr)
r   r   r  Zfill_performedparamscmdZ	differentr:  ZoursZtheirsr*   r;  r+   r  6
  s:    




zGraphicsContextPdf.deltac                    s8   t  | t|d| j}t|d| j}|| _|| _dS )z5
        Copy properties of other into self.
        r  r  N)rz  r  r  r  r  )r   r   r  r.  r  r*   r+   r  \
  s    z"GraphicsContextPdf.copy_propertiesc                 C   s"   g }| j dur||   q|S )zB
        Make sure every pushed graphics state is popped.
        N)r"  r  r  )r   r  r*   r*   r+   r  g
  s    
zGraphicsContextPdf.finalize)r   r   r   r   r   r  r,   r  r  r  r(  r)  r*  r-  r/  r1  r4  r0  r  r  r7  r<  r  r  r  r  r*   r*   r  r+   r  	  s>   &r  c                   @   s`   e Zd ZdZdZdddZdd Zd	d
 Zdd Zdd Z	dddZ
dd Zg dfddZdS )PdfPagesa=  
    A multi-page PDF file.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> # Initialize:
    >>> with PdfPages('foo.pdf') as pdf:
    ...     # As many times as you like, create a figure fig and save it:
    ...     fig = plt.figure()
    ...     pdf.savefig(fig)
    ...     # When no figure is specified the current figure is saved
    ...     pdf.savefig()

    Notes
    -----
    In reality `PdfPages` is a thin wrapper around `PdfFile`, in order to avoid
    confusion when using `~.pyplot.savefig` and forgetting the format argument.
    )_file
keep_emptyTNc                 C   s   t ||d| _|| _dS )a  
        Create a new PdfPages object.

        Parameters
        ----------
        filename : str or path-like or file-like
            Plots using `PdfPages.savefig` will be written to a file at this
            location. The file is opened at once and any older file with the
            same name is overwritten.

        keep_empty : bool, optional
            If set to False, then empty pdf files will be deleted automatically
            when closed.

        metadata : dict, optional
            Information dictionary object (see PDF reference section 10.2.1
            'Document Information Dictionary'), e.g.:
            ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.

            The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
            'Creator', 'Producer', 'CreationDate', 'ModDate', and
            'Trapped'. Values have been predefined for 'Creator', 'Producer'
            and 'CreationDate'. They can be removed by setting them to `None`.
        ra   N)re  rB  rC  )r   r  rC  ra   r*   r*   r+   r   
  s    zPdfPages.__init__c                 C   s   | S r=   r*   r   r*   r*   r+   	__enter__
  s    zPdfPages.__enter__c                 C   s   |    d S r=   )r  )r   exc_typeexc_valexc_tbr*   r*   r+   __exit__
  s    zPdfPages.__exit__c                 C   sH   | j   | j   |  dkr>| js>| j js>t| j jj	 d| _ dS )z_
        Finalize this object, making the underlying file a complete
        PDF file.
        r   N)
rB  r  r  get_pagecountrC  r~  rV   remover:  rO   r   r*   r*   r+   r  
  s    

zPdfPages.closec                 C   s   | j jS )z
        Return a modifiable information dictionary object
        (see PDF reference section 10.2.1 'Document Information
        Dictionary').
        )rB  r  r   r*   r*   r+   infodict
  s    zPdfPages.infodictc                 K   s   t |tsD|du rt }n
t|}|du r<td||jj}z0|j}t	||_|j
| fddi| W ||_n||_0 dS )a5  
        Save a `.Figure` to this file as a new page.

        Any other keyword arguments are passed to `~.Figure.savefig`.

        Parameters
        ----------
        figure : `.Figure` or int, default: the active figure
            The figure, or index of the figure, that is saved to the file.
        NzNo figure {}r   rm  )rD   r   r   Z
get_activeZget_fig_managerr   r   ZcanvasfigureFigureCanvasPdfsavefig)r   rM  kwargsmanagerZorig_canvasr*   r*   r+   rO  
  s    



zPdfPages.savefigc                 C   s   t | jjS )z=Return the current number of pages in the multipage pdf file.)r0   rB  r  r   r*   r*   r+   rJ  
  s    zPdfPages.get_pagecountr  c                 C   s   | j || dS )z
        Add a new text note to the page to be saved next. The optional
        positionRect specifies the position of the new note on the
        page. It is outside the page per default to make sure it is
        invisible on printouts.
        N)rB  r  )r   r  r  r*   r*   r+   attach_note
  s    zPdfPages.attach_note)TN)N)r   r   r   r   r   r   rE  rI  r  rL  rO  rJ  rR  r*   r*   r*   r+   rA  q
  s   

rA  c                       s@   e Zd ZdZddiZdd Zddddd	Z fd
dZ  ZS )rN  r  rm  zPortable Document Formatc                 C   s   dS )Nrm  r*   r   r*   r*   r+   get_default_filetype
  s    z$FigureCanvasPdf.get_default_filetypeN)bbox_inches_restorera   c          	   
   C   s   | j j}d| j _| j  \}}t|tr0|j}nt||d}zr||| t| j |||t	|||||d}| j 
| |  t|ts|  W t|tr|  q|  nt|tr|  n|  0 d S )Nr  rD  )rT  )rM  dpiZget_size_inchesrD   rA  rB  re  r  r   r  drawr  r  r  )	r   r  rT  ra   rU  rw   rx   r   rendererr*   r*   r+   	print_pdf
  s.    








zFigureCanvasPdf.print_pdfc                    s   | j   t  S r=   )rM  Zdraw_without_renderingrz  rV  r   r  r*   r+   rV  	  s    
zFigureCanvasPdf.draw)	r   r   r   Z	fixed_dpi	filetypesrS  rX  rV  r  r*   r*   r  r+   rN  
  s   rN  c                   @   s   e Zd ZeZdS )_BackendPdfN)r   r   r   rN  ZFigureCanvasr*   r*   r*   r+   rZ    s   rZ  )r&   )r&   )r   )r   )r   )br   r   r   enumr   	functoolsr   ior   r   loggingrr   rV   r  r  r  rj   r  rQ  r?  numpyr   ZPILr   Z
matplotlibr\   r   r   r	   r
   r   Zmatplotlib._pylab_helpersr   Zmatplotlib.backend_basesr   r   r   r   r   Z!matplotlib.backends.backend_mixedr   Zmatplotlib.figurer   Zmatplotlib.font_managerr   r   r  Zmatplotlib._afmr   Zmatplotlib.ft2fontr   r   r   r   r   r   Zmatplotlib.transformsr   r   Zmatplotlib.pathr   Zmatplotlib.datesr    r!   ra  r#   	getLoggerr   r  r   r,   r(   re   rq   r   r   r   rE   	maketransr   r   r   r   rN   r   r   r   r2  rd  re  ZRendererPDFPSBaser  r  rA  rN  ZFigureManagerPdfexportrZ  r*   r*   r*   r+   <module>   s    
2
W



I&	F].          	   z Nu(