o
    iz                    @   s  d Z ddlZddl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mZ ddlZddlmZmZ ddlmZ dd	lmZ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)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddl<m=Z= ddl>m?Z? ddlm@Z@ ddlmAZA ddlBmCZC e	DeEZFdddZGeHdZIdd ZJdd ZKdd  ZLd!d" ZMG d#d$ d$ZNeG d%d& d&ZOG d'd( d(ZPG d)d* d*ZQeRdi d+d,d-d.dd/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsZSejTdi dtdu eSU D ZVdvdw ZWeWeV_XG dxdy dyZYG dzd{ d{ZZG d|d} d}eCj[Z\G d~d de!Z]G dd dZ^G dd deZ_e Z`ejaG dd deZbdS )uA   
A PDF matplotlib backend
Author: Jouni K Seppänen <jks@iki.fi>
    N)datetime)total_ordering)BytesIO)Image)_text_layoutcbook)Gcf)_Backend_check_savefig_extra_argsFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase)MixedModeRenderer)Figure)findfontis_opentype_cff_fontget_font)AFM)FIXED_WIDTHITALICLOAD_NO_SCALELOAD_NO_HINTINGKERNING_UNFITTED)MathTextParser)Affine2DBboxBase)Path)UTC)_path)_ttconv   )_backend_pdf_psK   c                 C   s   d}d}g }t | D ]%\}}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)stringslinelencurrposlastiresultislength r2   Z/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/matplotlib/backends/backend_pdf.pyfilla   s   
r4   s   ([\\()\r\n])c                 C   s6   |  d}|dv rd| S |dkrdS |dkrdS J )Nr   s   \()   \r%   s   \n   s   \r)group)matchmr2   r2   r3   _string_escape   s   
r:   c           
   
   C   s   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 ]}	|	|vr_td|	  qP||	 ||	 sotd|	  qPd|v r|t|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 Nr2   ).0kvr2   r2   r3   
<dictcomp>   s    z)_create_pdf_info_dict.<locals>.<dictcomp>c                 S   
   t | tS r@   )
isinstancestrxr2   r2   r3   is_string_like      
z-_create_pdf_info_dict.<locals>.is_string_likec                 S   rE   r@   )rF   r   rH   r2   r2   r3   is_date   rK   z&_create_pdf_info_dict.<locals>.is_datec                 S   s   t | tr
| jdv S | dv S )N)s   Trues   Falses   Unknown)TrueFalseUnknownrF   NamenamerH   r2   r2   r3   check_trapped   s   

z,_create_pdf_info_dict.<locals>.check_trapped)	TitleAuthorSubjectKeywordsr=   r>   r?   ModDateTrappedzUnknown infodict keyword: zBad value for infodict keyword rY   )osgetenvr   utcfromtimestampintreplacer   todaympl__version__itemsr   _warn_externalrQ   )
backendmetadatasource_date_epochsource_dateinforJ   rL   rS   keywordsrB   r2   r2   r3   _create_pdf_info_dict   sD   
rj   c                 C   s   |  d}|  }|dur|j}n
tjrtj}ntj}|dkr%|d7 }|S |dk r9|d| d | d f 7 }|S |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zr2   r2   r3   _datetime_to_pdf   s   
rv   c                    s  t  dr	  S t ttjfr&t stdd  }|ddS t t	r1ddg  S t t
tjfr=d  S t trbz
 d	}t|W S  tya   tj d
 }t| Y S w t trqdtt  d S t trtdg fddt D dS t ttfrtdgdd  D dS  du rdS t trtt S t trtdd  jD S tdt  )z!Map Python objects to PDF syntax.pdfReprz%Can only output finite numbers in PDFs   %.10f   0   .s   falses   trues   %dASCIIzUTF-16BE   (   )s   <<c                    s(   g | ]}t | d  t |  qS )r$   )rQ   rw   )rA   keyobjr2   r3   
<listcomp>#  s     zpdfRepr.<locals>.<listcomp>s   >>   [c                 S      g | ]}t |qS r2   rw   rA   valr2   r2   r3   r   *         ]Ns   nullc                 S   r   r2   r   r   r2   r2   r3   r   6  r   z.Don't know a PDF representation for {} objects)!hasattrrw   rF   floatnpfloatingisfinite
ValueErrorrstripboolr]   integerrG   encodeUnicodeEncodeErrorcodecsBOM_UTF16_BEbytes_string_escape_regexsubr:   dictr4   sortedlisttupler   rv   r   bounds	TypeErrorformattype)r   rt   r0   r2   r~   r3   rw      sT   











rw   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   
   || _ d S r@   idselfr   r2   r2   r3   __init__D  rK   zReference.__init__c                 C   
   d| j  S )Nz<Reference %d>r   r   r2   r2   r3   __repr__G  rK   zReference.__repr__c                 C   r   )Ns   %d 0 Rr   r   r2   r2   r3   rw   J  rK   zReference.pdfReprc                 C   s,   |j }|d| j  |t| |d d S )N	   %d 0 obj
s   
endobj
)writer   rw   )r   contentsfiler   r2   r2   r3   r   M  s   zReference.writeN)__name__
__module____qualname____doc__r   r   rw   r   r2   r2   r2   r3   r   =  s    r   c                   @   sb   e Zd ZdZdZedZdd Zdd Z	dd	 Z
d
d Zdd Zdd Zedd Zdd ZdS )rQ   zPDF name object.rR   z[^!-~]c                 C   sF   t |tr|j| _d S t |tr|d}| jtj|d| _d S )Nascii)	rF   rQ   rR   r   decode_regexr   hexifyr   )r   rR   r2   r2   r3   r   Z  s
   


zName.__init__c                 C   r   )Nz	<Name %s>r   r   r2   r2   r3   r   b  rK   zName.__repr__c                 C   s   dt | j S )N/)rG   rR   r   r2   r2   r3   __str__e  s   zName.__str__c                 C   s   t |to
| j|jkS r@   rP   r   otherr2   r2   r3   __eq__h     zName.__eq__c                 C   s   t |to
| j|jk S r@   rP   r   r2   r2   r3   __lt__k  r   zName.__lt__c                 C   
   t | jS r@   )hashrR   r   r2   r2   r3   __hash__n  rK   zName.__hash__c                 C   s   dt |   S )Nz#%02x)ordr7   )r8   r2   r2   r3   r   q  s   zName.hexifyc                 C   s
   d| j  S )N   /r   r   r2   r2   r3   rw   u  rK   zName.pdfReprN)r   r   r   r   	__slots__recompiler   r   r   r   r   r   r   staticmethodr   rw   r2   r2   r2   r3   rQ   T  s    

rQ   c                   @   s,   e Zd ZdZdZdd Zdd Zdd Zd	S )
OperatorzPDF operator object.opc                 C   r   r@   r   )r   r   r2   r2   r3   r   }  rK   zOperator.__init__c                 C   r   )Nz<Operator %s>r   r   r2   r2   r3   r     rK   zOperator.__repr__c                 C      | j S r@   r   r   r2   r2   r3   rw        zOperator.pdfReprN)r   r   r   r   r   r   r   rw   r2   r2   r2   r3   r   y  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   r   r@   _x)r   rI   r2   r2   r3   r     rK   zVerbatim.__init__c                 C   r   r@   r   r   r2   r2   r3   rw     r   zVerbatim.pdfReprN)r   r   r   r   r   rw   r2   r2   r2   r3   r     s    r   close_fill_stroke   bfill_stroke   B   f	closepath   hclose_stroke   sstroke   Sendpath   n
begin_texts   BTend_texts   ETcurveto   c	rectangles   relineto   lmoveto   mconcat_matrixs   cmuse_xobjects   Dosetgray_stroke   Gsetgray_nonstroke   gsetrgb_strokes   RGsetrgb_nonstrokes   rgsetcolorspace_strokes   CSsetcolorspace_nonstrokes   cssetcolor_strokes   SCNsetcolor_nonstrokes   scnsetdash   dsetlinejoin   j
setlinecap   J	setgstates   gsgsave   qgrestore   Qtextposs   Td
selectfonts   Tf
textmatrixs   Tmshows   Tjshowkerns   TJsetlinewidth   wclip   Wshadings   shc                 C   s   i | ]	\}}|t |qS r2   )r   )rA   rR   valuer2   r2   r3   rD     s    rD   c                 C   s$   |r
| rt jS t jS | rt jS t j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.
    )Opr   r   r4   r   )r4   r   r2   r2   r3   _paint_path  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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   r'   pdfFiler   compressobjextraposNc                 C   s   || _ || _|| _|j| _d| _|du rt | _n| | _|dur-| j	t
d|d | j| j  tjd rD|sDttjd | _| jdu rOt | _dS |   | j | _dS )aA  
        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)FilterDecodeParmspdf.compression)r   r'   r
  fhr   r  r   r  copyupdaterQ   
recordXrefr`   rcParamszlibr   _writeHeadertellr  )r   r   r'   r   r  pngr2   r2   r3   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   Lengthr  r  r  s   
stream
)	r   r   r   r  r'   r`   r  rQ   rw   )r   r   r   r2   r2   r3   r    s   

zStream._writeHeaderc                 C   s   |    | jdu r*| j }t|| _| jj| _|   | j| | jd dS | j | j	 }| jd | j
| j| dS )zFinalize stream.Ns   
endstream
endobj
)_flushr'   r   getvaluer
  r  r  r   r  r  writeObject)r   r   r1   r2   r2   r3   end  s   



z
Stream.endc                 C   s6   | j du r| j| dS | j |}| j| dS )zWrite some data on the stream.N)r  r   r   compress)r   data
compressedr2   r2   r3   r     s   
zStream.writec                 C   s.   | j dur| j  }| j| d| _ dS dS )zFlush the compression object.N)r  flushr   r   )r   r"  r2   r2   r3   r    s
   


zStream._flushNN)
r   r   r   r   r   r   r  r  r   r  r2   r2   r2   r3   r	    s    
(	r	  c                       s  e Zd ZdZd^ fdd	Zede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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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^d@dAZ%dBdC Z&dDdE Z'dFdG Z(dHdI Z)dJdK Z*e+d`dLdMZ,dadOdPZ-dbdRdSZ.dTdU Z/dVdW Z0dXdY Z1dZd[ Z2d\d] Z3  Z4S )cPdfFilezPDF file object.Nc                    sJ  t    td| _g dg| _d| _d| _d| _t	j
|ddd\}}|sBz| | _W n ty<   t }|| _Y nw |}d| _|| _d| _|d	 |d
 | d| _| d| _g | _| d| _| d| _| d| _| d| _| d| _| d| _td| jd}| | j| td|pi | _i | _dd tdD | _ i | _!i | _"t#$ | _%i | _&dd tdD | _'i | _(dd tdD | _)g | _*t+, | _-dd tdD | _.g | _/t+, | _0dd tdD | _1t+, | _2i | _3g | _4g | _5dd d6 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   i  the zero objectFNr   wbT)return_openeds	   %PDF-1.4
s   % 
rootpagesfontszextended graphics statesztiling patternszGouraud triangleszexternal objects	resourcesCatalog)TypePagespdfc                 s       | ]
}t d | V  qdS )FNrQ   rA   r/   r2   r2   r3   	<genexpr>V      z#PdfFile.__init__.<locals>.<genexpr>c                 s   r1  )ANr3  r4  r2   r2   r3   r5  ]  r6  c                 s   r1  )SMNr3  r4  r2   r2   r3   r5  _  r6  c                 s   r1  )HNr3  r4  r2   r2   r3   r5  c  r6  c                 s   r1  )INr3  r4  r2   r2   r3   r5  g  r6  c                 S   r   r2   r3  rA   rI   r2   r2   r3   r   q  r   z$PdfFile.__init__.<locals>.<listcomp>PDF Text ImageB ImageC ImageI)FontXObject	ExtGStatePatternShadingProcSet)7superr   	itertoolscount_object_seq	xrefTablepassed_in_file_objectoriginal_file_like	tell_baser   to_filehandler  IOErrorr   r  currentstreamr   reserveObject
rootObjectpagesObjectpageList
fontObject_extGStateObjecthatchObjectgouraudObjectXObjectObjectresourceObjectrQ   r  rj   infoDict	fontNames_internal_font_seqdviFontInfotype1Descriptorsr"   CharacterTracker_character_trackeralphaStates_alpha_state_seq_soft_mask_states_soft_mask_seq_soft_mask_groupscollectionsOrderedDicthatchPatterns_hatch_pattern_seqgouraudTriangles_images
_image_seqmarkersmulti_byte_charprocspathspageAnnotationssplit)r   filenamere   r  openedr)  procsetsr,  	__class__r2   r3   r     s|   







zPdfFile.__init__3.3c                 C   s
   | j jjS r@   )r   r^  used_charactersr   r2   r2   r3   rv  ~  s   
zPdfFile.used_charactersc              	   C   s   |    ||| _| _| d}td| j| jddd| d| g|tdtdtdd| jd	}| d
}| || | j	
| | |j| d | tjd tj g | _d S )Nzpage contentsPager   H   GroupTransparency	DeviceRGB)r.  SCS)r.  Parent	ResourcesMediaBoxContentsry  Annotspagezlength of content streamround)	endStreamwidthheightrN  rQ   rP  rW  rn  r  rQ  r(   beginStreamr   outputGraphicsContextPdf
joinstylesr  r   )r   r  r  contentObjectthePage
pageObjectr2   r2   r3   newPage  s,   



zPdfFile.newPager  r   r   c                 C   s<   t dt d||d}| d}| || | j| d S )NAnnotText)r.  Subtyper  Rect
annotation)rQ   rN  r  rn  r(   )r   textpositionRecttheNoteannotObjectr2   r2   r3   newTextnote  s   
zPdfFile.newTextnotec              
   C   s
  |    |   |   |   |   |   dd | j D }| j D ]
}|d ||d < q'| j	
 D ]\}}|||< q7| jD ]\	}}}}}}	}
}}|||< qC| | 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 r2   r2   )rA   imagerR   obr2   r2   r3   rD     s    z$PdfFile.finalize.<locals>.<dictcomp>r!   r   r/  )r.  KidsCountN)r  
writeFontswriteExtGSTates_write_soft_mask_groupswriteHatcheswriteGouraudTrianglesri  valuesrk  rl  rb   rm  r  rV  writeImageswriteMarkerswritePathCollectionTemplatesrP  rQ   rQ  r'   writeInfoDict	writeXrefwriteTrailer)r   xobjectstuprR   r  pathtransr  r)   cappaddingfilledstrokedr2   r2   r3   finalize  s:   

zPdfFile.finalizec                 C   sF   |    | jr| j  dS | jdur| j| j  | j  dS )z)Flush all buffers and free all resources.N)r  rH  r  r#  rI  r   r  closer   r2   r2   r3   r    s   
zPdfFile.closec                 C   s*   | j d u r| j| d S | j | d S r@   )rM  r  r   r   r!  r2   r2   r3   r     s   
zPdfFile.writec                 G   s&   |  tdd |D  |  d d S )Nc                 S   r   r2   r   r;  r2   r2   r3   r     r   z"PdfFile.output.<locals>.<listcomp>r%   )r   r4   r  r2   r2   r3   r    s   zPdfFile.outputc                 C   s$   | j d u sJ t||| ||| _ d S r@   )rM  r	  )r   r   r'   r  r  r2   r2   r3   r    s   zPdfFile.beginStreamc                 C   s"   | j d ur| j   d | _ d S d S r@   )rM  r  r   r2   r2   r3   r    s   


zPdfFile.endStreamc                 C   sn   t |tr|}ntjd rt|dtjd}nt|}| j|}|du r5t	| j
}|| j|< td|| |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.use14corefontsafm)fontext	directoryNzAssigning font %s = %r)rF   rG   r`   r  r   RendererPdf_afm_font_dirrY  getnextrZ  _logdebug)r   fontproprp  Fxr2   r2   r3   fontName  s   



zPdfFile.fontNamec                 C   s   | j |j}|dur|jS ttd}||j }|jdu r*t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  dviread
PsfontsMapfind_tex_filerp  r   r   psnamer  rZ  r  r  typesSimpleNamespaceencodingr  )r   r  dvi_infotex_font_mappsfontr  r2   r2   r3   dviFontName  s*   


zPdfFile.dviFontNamec                 C   s   i }t | j D ]\}}|j}td| | |||< q	t | jD ]5}| j| }td| |drBtd | 	|||< q#td | j
j|}|rX| ||||< q#| | j| d S )Nz"Embedding Type-1 font %s from dvi.zEmbedding font %s.z.afmzWriting AFM font.zWriting TrueType font.)r   r[  rb   r  r  r  _embedTeXFontrY  endswith_write_afm_fontr^  usedr  embedTTFr  rR  )r   r+  dvinamerh   r  rp  charsr2   r2   r3   r    s"   



zPdfFile.writeFontsc                 C   sr   t |d}t|}W d    n1 sw   Y  | }tdtdt|tdd}| d}| || |S )Nrbr=  Type1WinAnsiEncoding)r.  r  BaseFontEncodingfont dictionary)openr   get_fontnamerQ   rN  r  )r   rp  r  fontfontnamefontdictfontdictObjectr2   r2   r3   r  2  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rFtd	dgttt|j
d
|d	< |jd u rat d|j t|j|d< | || |S t|j}|jrp||j}t|jd |d< |jdd|jddf}| j|j|f}|d u r| ||j}|| j|j|f< ||d< | || |S )Nz#Embedding TeX font %s - fontinfo=%sfont widthsr  r=  r  r   r!   )r.  r  	FirstCharLastCharWidthsr  r.  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  FontNameslant        extend      ?FontDescriptor)r  r  r  r  __dict__rN  r  widthsrQ   r'   r  mapr  
_parse_encr  warningr  	type1font	Type1Fontr  	transformpropr  r\  createType1Descriptor)r   fontinfowidthsObjectr  r  t1fontr  fontdescr2   r2   r3   r  >  sR   



	

zPdfFile._embedTeXFontc           
      C   s   |  d}|  d}|jd }|jd }d}|r|dO }	 	 |dO }|r(|d
O }	 	 	 t|}tdt|jd ||j||j|jdd||jd dd}	| ||	 | |j	d t
|jd t
|jd dd | j|jd  | j|jd  |   |S )Nfont descriptorz	font fileItalicAngleisFixedPitchr   r!             @            r  r    i  
FamilyName2   )r.  r  FlagsFontBBoxr  AscentDescent	CapHeightXHeightFontFile
FontFamilyStemV)Length1Length2Length3)rN  r  r   rQ   bboxascender	descenderr  r  r   r'   partsrM  r   r  )
r   r  r  fontdescObjectfontfileObjectitalic_anglefixed_pitchflagsft2font
descriptorr2   r2   r3   r  x  sP   




zPdfFile.createType1Descriptorc                 C   s4   |  |}d|j tjtj|d |gS )N-r   )r  r)   rR   r   rZ   r  splitextbasename)r   rp  symbol_namer  r2   r2   r3   _get_xobject_symbol_name  s   
z PdfFile._get_xobject_symbol_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                    s~  t }tjd }|jdfdd  fdd} fdd}|jd	d
t|dp7ddd}|dp@ddi}|j}	|j	}
d}d}|	t
@ rS|dO }	 |r[|dO }n|dO }|
t@ rg|dO }	 	 	 td| fdd|jD  |jdd |jdd |d dd |d |d d dd 
}trd!}td"tj |d#kr||||S |d!kr||||S d$S )%z9Embed the TTF font from the named file into the document.pdf.fonttypeTc                 S   s4   | | d }|rt |S |dk rt|S t|S )z2Convert font coordinates to PDF glyph coordinates.r  r   )r  mathfloorceil)r1   upenearestr  r2   r2   r3   cvt  s   

zPdfFile.embedTTF.<locals>.cvtc                    s   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  td fddt||	d D }W d   n1 spw   Y  t	||d< g }g }t
 }|D ]$}|}|}|| |}|dkr|||f q|| q|  d}|D ]\}}||d kr|| |t| |}qztt|}W n ty   td  w i }t|D ]X}|| }dt|i}||v rtd|d< td|d< |
|d < ||d!d" d } d#}|jd| j|   ||v r=|}|j |< q|||< q!|| !|| !|| !|| |S )$z5The Type 3-specific part of embedding a Truetype fontr  r  r  zcharacter procs)r      c                       g | ]} |d dqS Fr1  r2   r;  r2  r2   r3   r         z;PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.<listcomp>r=  Type3r  )MbP?r   r   r:  r   r   r  r  )r.  r  r  r  r  r  rQ   r  
FontMatrix	CharProcsr  r  r   )cp1252c                    s*   t  j|  }j|ttB dj}|S )Nr$  )r   decoding_table	load_charr   r   horiAdvance)charcoder0   r  )r=  r2  r  r2   r3   get_char_width  s   z?PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.get_char_widthignorec                    s   g | ]} |qS r2   r2   )rA   rB  )rC  r2   r3   r     s    r!   NMaxWidthr3  z=The PDF backend does not currently support the selected font.r  r>  r.  Formr  BBoxs   d1r  charProc)"rN  r  rQ   	encodingsr=  warningscatch_warningsfilterwarningsrangemaxsetget_char_indexr(   get_glyph_nameaddsortr    get_pdf_charprocsrZ   fsencodeRuntimeErrorr  r  r   r'   findr  r   rM  r   r  r+  rl  r  )r  
charactersr&  r   r   r  charprocsObjectdifferencesArray	firstcharlastcharr  r  r  	glyph_idsdifferencesmulti_byte_charscccodegind
glyph_namelast_crR   rawcharprocs	charprocscharnamestreamcharprocDictcharprocObjectr2  rp  ps_namer   )r=  r  rC  r3   embedTTFType3  s   
















z'PdfFile.embedTTF.<locals>.embedTTFType3c                     s   d} d} d} d} d} d} d}	tdtd	d
ddd|||d}
tdtdtd|g|	d}||d<  d}|j dd|i td }d}	 |d}|sln|t|7 }j| qdW d   n1 sw   Y  	  
|| dgd }g }d}|D ]+}|}| |}| j|ttB d}|| |jf |dk rt|||< t||}q|  |d|d  }d}g }d}g }|D ]1\}}||d kr|| ||g |||g n|d | ||d d< t||}|}qg }|D ]\}}|d ||d!d"d# t||d D f  qjt|d$|f }d%|d&}|jdd't|i j| 	  |	jdd'|i j| 	  ||d(< 
||
 
|| 
|| 
|| |S ))z6The 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 mapr=  CIDFontType2AdobeIdentityr   )RegistryOrdering
Supplement)r.  r  r  CIDSystemInfor  WCIDToGIDMapType0z
Identity-H)r.  r  r  r  DescendantFonts	ToUnicode	FontFile2zdecoded length of a fontzlength of font streamr  r  Ti   N r
  r>  r!   rF  s   <%04x> <%04x> [%s]r$   c                 s   s    | ]}d | V  qdS )s   <%04x>Nr2   r;  r2   r2   r3   r5    s    z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>r%    utf-16ber  rE  )rN  rQ   r  r   r  readr'   rM  r   r  r  rQ  r@  r   r   r(   rA  chrrO  rT  r)   rN  _identityToUnicodeCMapr   ) r  rY  r&  r   cidFontDictObjecttype0FontDictObjectcidToGidMapObjectr!  wObjecttoUnicodeMapObjectcidFontDicttype0FontDictlength1Objectr  length1r!  cid_to_gid_mapr  	max_ccodera  rb  rc  glyph
last_ccodew	max_widthunicode_groupsr  unicode_bfrangestartr  unicode_cmaprl  r2   r3   embedTTFType42[  s   














z(PdfFile.embedTTF.<locals>.embedTTFType42r   r^   pcltr   )	capHeightxHeightpostitalicAngler   r   Fr!   r  r  r  r	  r
  r  r  r  c                    r4  r5  r2   r;  r7  r2   r3   r     r8  z$PdfFile.embedTTF.<locals>.<listcomp>r6  r  r  )
r.  r  r  r  r  r  r  r  r  r  *   z[%r can not be subsetted into a Type 3 font. The entire font will be embedded in the output.   N)r   r`   r  units_per_EMpostscript_namer   rQ   get_sfnt_table
face_flagsstyle_flagsr   r   r  r  r  r   r  r  rZ   r  r)  )r   rp  rY  r  fonttypern  r  r  r  ffsfr$  symbolicr&  r2   rl  r3   r    sZ   
tv



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   r?  r!   )r.  CAca)r_  r  r  r`  rQ   )r   alphastaterR   r2   r2   r3   
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 maskr?  FMask
Luminosityr!   )r.  r|  BCG)r.  AISSMaskr>  rG  rz  
DeviceGray)r|  r}  )r!   r   r   r!   r   r   rA  r|  )r   r   r!   r!   )r.  r  FormTypery  Matrixr  rH  )
ra  r  r  rb  rN  rQ   rc  r(   r  r  )r   smaskr  rR   groupObr2   r2   r3   _soft_mask_state  s<   



zPdfFile._soft_mask_statec                 C   s*   |  | jtg | j | j  d S r@   )r  rS  r   r_  r  ra  r   r2   r2   r3   r  G  s   zPdfFile.writeExtGSTatesc                 C   s8   | j D ]\}}}| |jd | | j|  |   qd S r@   )rc  r  r   r  r  )r   r  
attributescontentr2   r2   r3   r  P  s
   

zPdfFile._write_soft_mask_groupsc                 C   sn   |d ur|\}}}|d urt |}|d urt |}|||f}| j|d }|d ur+|S t| j}|| j|< |S r@   )r   rf  r  r  rg  )r   hatch_styleedgefacehatchpatternrR   r2   r2   r3   hatchPatternV  s   



zPdfFile.hatchPatternc           
      C   sD  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rr| 	|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 patternProcsetsc                 S   r   r2   r3  r;  r2   r2   r3   r   o  r   z(PdfFile.writeHatches.<locals>.<listcomp>r<  r@  r!   r   rx  )	r.  PatternType	PaintType
TilingTyperH  XStepYStepr  r  r  zhatch.linewidthFsimplify)r   rf  rb   rN  ro  r  r   rQ   r  r  r  r   r   r   r4   r`   r  r  pathOperationsr   r  r   scaler   r  r  rT  )
r   	hatchDictsidelenr  rR   r  res
stroke_rgbfill_rgbr  r2   r2   r3   r  h  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 )rQ   r'   rh  rN  r(   )r   pointscolorsrR   r  r2   r2   r3   addGouraudTriangles  s   zPdfFile.addGouraudTrianglesc                 C   s  t  }| jD ]\}}}}|||< |j}||d |d  df}|jd }|dv s+J ||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rfd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!   r  r!   r  r  r  axis   l    r     r{  r  F)ShadingTypeBitsPerCoordinateBitsPerComponentBitsPerFlag
ColorSpace	AntiAliasDecode)r$  u1)r  z>u4)r  r  r  )dtyper$  r  g     o@)r   rh  shapereshaper   minrO  r  r   rQ   emptyr   tobytesr  r  rU  )r   gouraudDictrR   r  r  r  r  flat_pointscolordimflat_colors
points_min
points_maxfactor	streamarrr2   r2   r3   r    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 )ri  r  r   r  rj  rN  )r   r  entryrR   r  r2   r2   r3   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rP|dddddf d }t|d	krEd}||fS tj|dd}||fS d}||f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.
        Nr}  r  r  C)orderr  ).Nr3  )ndimr   arrayr  all)r   imrgbr  r2   r2   r3   _unpack  s   
zPdfFile._unpackc                 C   s   t  }|jd dkr|jdd}t|j|dd |d 	 td|	d\}}|d	krE|	|}t
||kr>td
| j| n|dkrKdS ||d |dd q )zo
        Write the image *data* into the pdf file using png
        predictors with Flate compression.
        r}  r!   r  r  )r   r  Ts   !L4ss   IDATztruncated datas   IENDr  N)r   r  squeezer   	fromarraysaveseekstructunpackr  r'   rW  rM  r   )r   r!  bufferr1   r   r2   r2   r3   	_writePng  s"   

zPdfFile._writePngc           	      C   s   |j \}}}tdtd||tddd| dd}|r ||d< tjd	 r,d
||d}nd}| j|| d||d |rB| | 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.
        r>  r   r  r{  r!   r  r  )r.  r  WidthHeightr  r  r  r  
   )	PredictorColorsColumnsNzlength of image stream)r  )r  rQ   r`   r  r  rN  r   rM  r   r  r  )	r   r!  r   r  r  r  r  r   r  r2   r2   r3   	_writeImg  s.   
zPdfFile._writeImgc                 C   s^   | j  D ]'\}}}| |\}}|d ur"| d}| ||j nd }| ||j| qd S )Nr  )ri  r  r  rN  r  r   )r   imgrR   r  r!  adatasmaskObjectr2   r2   r3   r  +  s   
zPdfFile.writeImagesc                 C   s   | j ||dd}t|t|t|||f}	| j|	}
|
du rBtdt| j }| dt| j }||}||||g| j|	< |S |
d |k rL||
d< |
d }|S )z<Return name of a marker XObject representing the given path.Fr  NzM%dz	marker %dr}  r   )	r  r   r   rk  r  rQ   r'   rN  get_extents)r   r  r  r4   r   lw	joinstylecapstylepathopsr}   r.   rR   r  r  r2   r2   r3   markerObject5  s   
zPdfFile.markerObjectc           
   	   C   s   | j  D ]M\\}}}}}\}}}}	||	d }| |jd tdtdt|jd | t	j
| tj | t	j| tj | j|  | t|| |   qd S )N   r>  rG  r.  r  rH  )rk  rb   paddedr  r   rQ   r   extentsr  r  r  r  r   	capstylesr   
paint_pathr  )
r   r  r4   r   r  r  rR   r  r  r  r2   r2   r3   r  R  s$   


zPdfFile.writeMarkersc           	      C   sP   t dt| j }| dt| j }| j||||| | |||f	 |S )NzP%dzpath %d)rQ   r'   rm  rN  r(   get_joinstyleget_capstyle)	r   gcr  r  r  r  r  rR   r  r2   r2   r3   pathCollectionObjecth  s   zPdfFile.pathCollectionObjectc              
   C   s   | j D ]f\	}}}}}}}}}	| j||dd}
||}tt|js)g 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   r>  rG  r  )rm  r  r  r   r  r   r  r  r   r  r   rQ   r  r  r  r  r   r  r   r  r  )r   rR   r  r  r  r  r  r  r  r  r  r  r  r2   r2   r3   r  p  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 )N       T)	r   r   convert_to_stringr  r   r   r   r   r   )r  r  r  r  sketchr2   r2   r3   r    s   
zPdfFile.pathOperationsFc                 C   sN   |rdd| j d | jd f}|j}nd }d}| j|||||d}| j|  d S )Nr  rx  F)r  r   )r  r  should_simplifyr  r  )r   r  r  r  r   r  cmdsr2   r2   r3   	writePath  s   zPdfFile.writePathr~  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  rF  rG  r(   r   )r   rR   r   r2   r2   r3   rN    s   
zPdfFile.reserveObjectc                 C   s   | j  | j | j| d< d S Nr   )r  r  rJ  rG  r   r2   r2   r3   r    s   zPdfFile.recordXrefc                 C   s   |  |j |||  d S r@   )r  r   r   )r   objectr   r2   r2   r3   r    s   zPdfFile.writeObjectc                 C   s   | j  | j | _| dt| j  t| jD ]'\}\}}}|du r+td||f |dkr1dnd}d|||f }| | qdS )zWrite out the xref table.s
   xref
0 %d
NzNo offset for object %d (%s)r&  r   r   s   %010d %05d %b 
)	r  r  rJ  	startxrefr   r'   rG  r&   AssertionError)r   r/   offset
generationrR   r}   r  r2   r2   r3   r    s   
zPdfFile.writeXrefc                 C   s    |  d| _| | j| j dS )z8Write out the info dictionary, checking it for good formrh   N)rN  
infoObjectr  rX  r   r2   r2   r3   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
)SizeRootInfos   
startxref
%d
%%%%EOF
N)r   rw   r'   rG  rO  r*  r&  r   r2   r2   r3   r    s   
zPdfFile.writeTrailerr@   r$  )NNNFN)r~  )5r   r   r   r   r   r   
deprecatedpropertyrv  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  r  r  r   r  r  r  r  r  r  r   r  r#  rN  r  r  r  r  r  __classcell__r2   r2   rs  r3   r%    sf    d 
:B  24	&,
 


r%  c                       s   e Zd ZedZdZ fddZdd Zd-dd	Z	e
d
dd Ze
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ed
d"d/d$d%Zd&d' Zd0d)d*Zd+d, Z  ZS )1r  zfonts/pdfcorefontsr  c                    s2   t  || || _|  | _td| _|| _d S )NPdf)rC  r   r   new_gcr  r   mathtext_parser	image_dpi)r   r   r5  r  r  rs  r2   r3   r     s
   


zRendererPdf.__init__c                 C   s   | j j| j   d S r@   )r   r  r  r  r   r2   r2   r3   r    r   zRendererPdf.finalizeNc                 C   s   t |dd}||_t |dd}| d u r|jddd |jr'|j|jf|_n|d u s1t|dk r:|jd	 d
f|_n
|jd	 |d	 f|_| j	
|}|rR| jj|  ||_||_d S )N
_fillcolorr  r  r  _effective_alphasr  r  r  T)isRGBAr  r  r  )getattrr6  get_rgbset_foreground_forced_alpha_alphar8  r'   _rgbr  deltar   r  )r   r  	fillcolor	orig_fillorig_alphasrA  r2   r2   r3   check_gc  s   
zRendererPdf.check_gcru  c                 O   s   | j jj|i | dS )z;Keep track of which characters are required from each font.N)r   r^  trackr   argskwargsr2   r2   r3   track_characters  s   zRendererPdf.track_charactersc                 O   s   | j jj|i | d S r@   )r   r^  mergerG  r2   r2   r3   merge_used_characters  s   z!RendererPdf.merge_used_charactersc                 C   s
   | j d S )Nr  )r5  r   r2   r2   r3   get_image_magnification  rK   z#RendererPdf.get_image_magnificationc                 C   s   |j d d \}}|dks|dkrd S |d u r|d | | d| | j }d| | j }| j|}|d u rO| jtj|dd|||tj	|tj
tj d S |  \}	}
}}}}| jtjdddd||tj	|	|
||||tj	|tj
tj d S )Nr  r   r  r  r!   )r  	set_alpharE  r5  r   r  r  r  r   r   r   r   frozen	to_values)r   r  rI   yr  r  hr  imobtr1tr2tr3tr4tr5tr6r2   r2   r3   
draw_image  s(   





zRendererPdf.draw_imagec                 C   sH   |  || | j|||d u o| d u |  | j| j  d S r@   )rE  r   r#  get_hatch_pathget_sketch_paramsr  r  paint)r   r  r  r  rgbFacer2   r2   r3   	draw_path  s   zRendererPdf.draw_pathc           $      C   s  d}t |}t |}t|sd}|  }nt |d d df |d kr.|d dk}nd}t|s7d}n%t t |	dkrDd}nt |d d df |d krZ|d dk}nd}t|dkrit|d jnd}| |||||}|| d || k }|r|st| |||||||||	|
|||S t 	|	}g }t
| |||D ]\}\}}| j||||||}|| q| jj}|| j   d\}}| |||||||||	|
|||D ])\}}}} }!| | |! || || }"}#|d	ddd	|"|#tj|tj	 ||}}q|| j   d S )
NTFr  )r   r  r  r   r  r  r!   )r   asarrayr'   	get_hatchr  vertices_iter_collection_uses_per_pathr   draw_path_collectionrO  r&   _iter_collection_raw_pathsr   r  r(   r  r  push_iter_collectionrE  r  r   r   pop)$r   r  master_transformrm  all_transformsoffsetsoffsetTrans
facecolors
edgecolors
linewidths
linestylesantialiasedsurlsoffset_positioncan_do_optimizationr  r  len_pathuses_per_pathshould_do_optimizationr  
path_codesr/   r  r  rR   r  lastxlastyxoyopath_idgc0r^  dxdyr2   r2   r3   rd  &  sj   






z RendererPdf.draw_path_collectionc                 C   sj  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 ]L\}}t |r|dd  \}}d|  kr| jjd krn nd|  kr| jjd ksn qa|| || }}|dddd||tj|tj	 ||}}qa|tj d S )	Nr  r  r   rx  F)r  r  rF  r!   )r'   r   draw_markersrE  r4   r   r   r  r  r  
_linewidthr  r  r  r   iter_segmentsr  r  r   r   r   )r   r  marker_pathmarker_transr  r  r^  len_marker_pathusesr4   r   r  markerry  rz  rb  coderI   rQ  r  r  r2   r2   r3   r  l  sD   

 
zRendererPdf.draw_markersc                 C   s    |  ||d|d| d S )N)r!   r  r  )r!   r  r  )draw_gouraud_trianglesr  )r   r  r  r  r  r2   r2   r3   draw_gouraud_triangle  s   
z!RendererPdf.draw_gouraud_trianglec                 C   s  t |t |ks
J t |dkrd S |jdksJ |jd dks"J |jd dks+J |jdks2J |jd dks;J |jd dv sDJ |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 r||
 | 	| |	|t
j d S |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!   r  r  r  )r   r   r  )r'   r  r  r  r  r   r  r  rN  rE  r  r  r   allcloser  r   r   r   )r   r  r  r  r  r  tpointsrR   _r  r  smask_obgstater2   r2   r3   r    s@   





(z"RendererPdf.draw_gouraud_trianglesr   c              	   C   s   ||  kr
dkrn n| j || || tj d S t|}| j t|t|t| t|||tj | j ddtj d S r$  )	r   r  r  r   r-  radianscossinr   )r   rI   rQ  angleoldxoldyoldangler2   r2   r3   _setup_textpos  s   
zRendererPdf._setup_textposc                 C   s<  | j |d|\}}}	}
}}| jj| tjd }t|}| j	t
j | j	t|t|t| t|||t
j | ||j | j	t
j d}d\}}|
D ]L\}}}}}}t|red}n|}|dkso|dkr| ||d|| ||}}||f|kr| j	| j||t
j ||f}| j	| t||t
j qV| j	t
j |dkr|
D ]J\}}}}}}t|rd}n|}|dkr|dkr| j| | j	t
jd	| ddd	| ||t
j | j||}| j	t|t
j | j	t
j q|D ]\}}}}| j	t
j||||t
jt
jt
j q| j	t
j d S )
Nrx  r,  r$  r  r  r3  r   r  r:  ) r4  parser   r^  rK  r`   r  r-  r  r  r  r   r  r  r   rE  r@  r   r   r  r  r   encode_stringr  r   r   r+  rQ   r   r   r   r4   )r   r  rI   rQ  r0   r  r  r  r  descentglyphsrectsrv  global_fonttypea	prev_fontr  r  oxoyr  fontsizenumr*  r  rR   r2   r2   r3   draw_mathtext  sl   



zRendererPdf.draw_mathtextismathTeX!c	           $      C   sz  |   }	| }
|	||
}t|d}|\}W d    n1 s"w   Y  d g }}|jD ],\}}}}}||krK| j|}|d||jgg7 }|}|d||t	|gg|| gg7 }q/d\}}}
|t
|d k r|||d  \}}|d dkr~|d }
na|d |d   krdkrn nQ|d |d kr|d |d  }t|d	k r|d
 d  |d
 d 7  < |d  |d |d  7  < n|d
  |d |
 |d
 d g7  < |d |d< ||d = qa|d7 }|t
|d k sit |||}| ||j | jtj d\}}}}|D ]^}|d dkr#| j|d |d tj q|d dkrh||d |d f\}}| ||||| ||}}t
|d
 dkr\| j|d
 d tj q| j|d
 tj qJ | jtj |  }|| |d tjtjtjtjtj g} |j!D ],\}}}!}"t||g||" |g||" ||! g|||! gddgg| }#| "||#||j qd S )Nrx  r  r  )r   r   Nr!   r  r   r  g?r  r}  g     @@r  )#get_texmanagerget_size_in_pointsmake_dvir  Dvir  r   r  sizer   r'   absr   
rotate_deg	translaterE  r@  r  r  r   r   r  r  r   r   r   r3  copy_propertiesset_linewidthr   MOVETOLINETO	CLOSEPOLYboxesr_  )$r   r  rI   rQ  r0   r  r  r  mtext
texmanagerr  dvifiledvir  oldfontseqx1y1r  r  r  r  r/   curxeltnxtr(  mytranscuryr  r  boxgcr  rR  r  r  r2   r2   r3   draw_tex  sv   
"

0$



*zRendererPdf.draw_texc                 C   s    |dv r
| ddS | ddS )Nr  r=  r^   r  )r   )r   r0   r  r2   r2   r3   r  [  s   zRendererPdf.encode_stringFc	              
   C   s  |  ||j |r| ||||||S | }	tjd r$| |}
d}n| |}
| jj	
|
| tjd }t|
jr=d}|dksJtdd |D rp| jtj| j||	tj | ||| | j| ||tjtj d S g }g }d}t|tj||
td	D ],\}\}}t|d
kr|r|d d | n|||gf d}q|||f d}q| jtj t|}| jt |t!|t!| t |||tj" | jtj| j||	tj d}|D ]\}}| |dd|dd | j| d#||tj |}q| jtj |D ];\}}|
$|}| jtj | jd|	 ddd|	 |dtj" | j%|
j|}| jt&|tj' | jtj( q| jtj( d S )Nr  r!   r,  r  r  c                 s   s    | ]	}t |d kV  qdS )r3  N)r   )rA   charr2   r2   r3   r5  y  s    z(RendererPdf.draw_text.<locals>.<genexpr>F)	kern_moder3  r}  Tr   r~  r:  ))rE  r@  r  r  r`   r  _get_font_afm_get_font_ttfr   r^  rF  r   fnamer  r  r  r   r  r   r  r  r   r   zipr   layoutr   r   r(   r   r-  r  r  r  r   r)   rR  r+  rQ   r   r   )r   r  rI   rQ  r0   r  r  r  r  r  r  r  singlebyte_chunksmultibyte_glyphsprev_was_singlebyter  	glyph_idxglyph_xr  prev_start_xstart_xr  rd  rR   r2   r2   r3   	draw_text`  s   








zRendererPdf.draw_textc                 C   r   r@   )r  r   r   r2   r2   r3   r3    s   
zRendererPdf.new_gcr@   )r   r   r   )r  Nr.  )r   r   r   r   _get_data_pathr  _use_afm_rc_namer   r  rE  r/  rJ  rL  rM  rZ  r_  rd  r  r  r  r  r  _delete_parameterr  r  r  r3  r1  r2   r2   rs  r3   r    s2    





	G
&
(

CO
Wr  c                
   @   s   e Zd Z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d1d2 Zd3d4 Zd5S )6r  c                 C   s&   t |  d| _d| _|| _d | _d S )Nr7  r9  )r   r   r6  r8  r   parent)r   r   r2   r2   r3   r     s
   

zGraphicsContextPdf.__init__c                 C   s   t | j}|d= |d= t|S )Nr   r  )r   r  repr)r   rs   r2   r2   r3   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?  r'   r@  r   r2   r2   r3   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  )r'   r6  _hatch)r   rH  r6  r2   r2   r3   r4     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  r4   r   r   r2   r2   r3   r]    s   zGraphicsContextPdf.paintr   r!   r  )buttr  
projecting)miterr  bevelc                 C      | j | tjgS r@   )r  r  r   r   styler2   r2   r3   capstyle_cmd     zGraphicsContextPdf.capstyle_cmdc                 C   r  r@   )r  r  r   r  r2   r2   r3   joinstyle_cmd  r  z GraphicsContextPdf.joinstyle_cmdc                 C   s
   |t jgS r@   )r  r  )r   r  r2   r2   r3   linewidth_cmd  rK   z GraphicsContextPdf.linewidth_cmdc                 C   s(   |\}}|d u rg }d}t ||tjgS r$  )r   r  r   )r   dashesr(  dashr2   r2   r3   dash_cmd  s
   zGraphicsContextPdf.dash_cmdc                 C   s   | j |}|tjgS r@   )r   r  r  r   )r   r  forcedeffective_alphasrR   r2   r2   r3   	alpha_cmd  s   
zGraphicsContextPdf.alpha_cmdc                 C   sT   |s| j d ur| | j S tdtjgS || j |f}| j|}tdtj|tjgS )Nr{  r@  )r6  fillcolor_cmdrQ   r  r   r   r  r   )r   r  hatch_colorr  rR   r2   r2   r3   	hatch_cmd	  s   

zGraphicsContextPdf.hatch_cmdc                 C   sV   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 Nzpdf.inheritcolorr   r!   r  r  )r`   r  r  r   r   r   r  r2   r2   r3   rgb_cmd	  s
   
$zGraphicsContextPdf.rgb_cmdc                 C   s^   |d u s	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 r  )r`   r  r  r   r   r  r2   r2   r3   r  	  s
   $z GraphicsContextPdf.fillcolor_cmdc                 C   s*   t | j}||  | j|_|| _tjgS r@   )r  r   r  r  r  r   )r   r  r2   r2   r3   rf  	  s
   

zGraphicsContextPdf.pushc                 C   s,   | j d usJ | | j  | j j | _ tjgS r@   )r  r  r  r   r   r2   r2   r3   rh  &	  s   
zGraphicsContextPdf.popc                 C   s   g }| j | jf||fkr'| jdur'||   | j | jf||fkr'| jdus| j | jf||fks6| jdu rj||   | j |krN||tjtjtj	g | j|krj|
 \}}|tj||ddtjtj	g  |S )z1Set clip rectangle. Calls `.pop()` and `.push()`.NFr  )	_cliprect	_clippathr  r  rh  rf  r  r   r  r   get_transformed_path_and_affiner%  r  )r   cliprectclippathr"  r  affiner2   r2   r3   clip_cmd,	  s&   





zGraphicsContextPdf.clip_cmd)r  r  )r?  r>  r8  )	_capstyler6  )
_joinstyle)r  )_dashes)r@  r  _hatch_colorc           
   
      s  g }d}| j D ]\}}d}|D ]F}t| |}t |}	z|du s$|	du r)||	u}nt||	k}W n  tyP   t|}t|	}	|j|	jkpMt||	k}Y nw |rU nq|dkr^|r^d}|r|dkrfd} fdd|D }	||| g|	R   |D ]}t	| |t | q|q|S )zy
        Copy properties of other into self and return PDF commands
        needed to transform self into other.
        FNr  Tr  c                    s   g | ]}t  |qS r2   )r;  )rA   pr   r2   r3   r   n	  s    z,GraphicsContextPdf.delta.<locals>.<listcomp>)
commandsr;  r   r   r   r`  r  anyr  setattr)
r   r   r"  fill_performedparamscmd	differentr  ourstheirsr2   r  r3   rA  N	  sB   




zGraphicsContextPdf.deltac                 C   s8   t | | t|d| j}t|d| j}|| _|| _dS )z5
        Copy properties of other into self.
        r6  r8  N)r   r  r;  r6  r8  )r   r   rB  r  r2   r2   r3   r  t	  s   
z"GraphicsContextPdf.copy_propertiesc                 C   s*   g }| j dur||   | j dus|S )zB
        Make sure every pushed graphics state is popped.
        N)r  r  rh  )r   r"  r2   r2   r3   r  	  s
   

zGraphicsContextPdf.finalizeN)r   r   r   r   r   r   r4   r]  r  r  r  r  r  r  r  r  r  r  rf  rh  r  r   rA  r  r  r2   r2   r2   r3   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`.
        re   N)r%  r
  r  )r   rp  r  re   r2   r2   r3   r   	  s   
zPdfPages.__init__c                 C   s   | S r@   r2   r   r2   r2   r3   	__enter__	     zPdfPages.__enter__c                 C   s   |    d S r@   )r  )r   exc_typeexc_valexc_tbr2   r2   r3   __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)
r
  r  r  get_pagecountr  rH  rZ   remover  rR   r   r2   r2   r3   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').
        )r
  rX  r   r2   r2   r3   infodict	  s   zPdfPages.infodictc                 K   s   t |ts"|du rt }nt|}|du rtd||jj}z|j}t	||_|j
| fddi| W ||_dS ||_w )a  
        Save a `.Figure` to this file as a new page.

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

        Parameters
        ----------
        figure : `.Figure` or int, optional
            Specifies what figure is saved to file. If not specified, the
            active figure is saved. If a `.Figure` instance is provided, this
            figure is saved. If an int is specified, the figure instance to
            save is looked up by number.
        NzNo figure {}r   r0  )rF   r   r   
get_activeget_fig_managerr   r   canvasfigureFigureCanvasPdfsavefig)r   r  rI  managerorig_canvasr2   r2   r3   r  	  s   



zPdfPages.savefigc                 C   s   t | jjS )z=Return the current number of pages in the multipage pdf file.)r'   r
  rQ  r   r2   r2   r3   r  	  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)r
  r  )r   r  r  r2   r2   r3   attach_note	  s   zPdfPages.attach_note)TNr@   )r   r   r   r   r   r   r  r  r  r  r  r  r  r2   r2   r2   r3   r	  	  s    

r	  c                   @   s:   e Zd ZdZdZddiZdd Zeddddd	d
ZdS )r  z
    The canvas the figure renders into.  Calls the draw and print fig
    methods, creates the renderers, etc...

    Attributes
    ----------
    figure : `matplotlib.figure.Figure`
        A high-level Figure instance
    rx  r0  zPortable Document Formatc                 C   s   dS )Nr0  r2   r   r2   r2   r3   get_default_filetype
  r  z$FigureCanvasPdf.get_default_filetypeN)dpibbox_inches_restorere   c          	   
   C   s   | j d | j  \}}t|tr|j}nt||d}z;||| t| j |||t	|||||d}| j 
| |  t|tsF|  W t|trR|  d S |  d S t|trb|  w |  w )Nrx  r  )r!  )r  set_dpiget_size_inchesrF   r	  r
  r%  r  r   r  drawr  r  r  )	r   rp  r   r!  re   r  r  r   rendererr2   r2   r3   	print_pdf
  s.   






zFigureCanvasPdf.print_pdf)	r   r   r   r   	fixed_dpi	filetypesr  r
   r&  r2   r2   r2   r3   r  	  s    
r  c                   @   s   e Zd ZeZdS )_BackendPdfN)r   r   r   r  FigureCanvasr2   r2   r2   r3   r)  /
  s    r)  )r#   r2   )cr   r   rd  r   	functoolsr   ior   rD  loggingr-  rZ   r   r  ro   r  rK  r  numpyr   PILr   
matplotlibr`   r   r   matplotlib._pylab_helpersr   matplotlib.backend_basesr	   r
   r   r   r   r   !matplotlib.backends.backend_mixedr   matplotlib.figurer   matplotlib.font_managerr   r   r   matplotlib.afmr   matplotlib.type1fontr  matplotlib.dvireadr  matplotlib.ft2fontr   r   r   r   r   matplotlib.mathtextr   matplotlib.transformsr   r   matplotlib.pathr   matplotlib.datesr   r   r    r~  r"   	getLoggerr   r  r4   r   r   r:   rj   rv   rw   r   rQ   r   r   r   _pdfopsr  rb   r  r  r  r	  r%  RendererPDFPSBaser  r  r	  r  FigureManagerPdfexportr)  r2   r2   r2   r3   <module>   s,    

2
PK$
				





^         ;   v Nv-