o
    he                    @   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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l0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6m7Z7 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ZDdFddZEdd ZFdd ZGdGddZHdGd d!ZIdGd"d#ZJeKLd$d%d&d'd(d)ZMd*d+ ZNd,d- ZOG d.d/ d/ZPeG d0d1 d1ZQG d2d3 d3ZRG d4d5 d5eZSG d6d7 d7ZTd8d9 ZUG d:d; d;ZVG d<d= d=eAjWZXG d>d? d?e&ZYG d@dA dAZZG dBdC dCe$Z[e%Z\e#j]G dDdE dEe#Z^dS )HuO   
A PDF Matplotlib backend.

Author: Jouni K Seppänen <jks@iki.fi> and others.
    N)timezone)datetime)Enum)total_ordering)BytesIO)Image)_api_text_helpers
_type1fontcbookdviread)Gcf)_BackendFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase)MixedModeRenderer)Figure)get_fontfontManager)AFM)FT2Font	FaceFlagsKerning	LoadFlags
StyleFlags)Affine2DBboxBase)Path)UTC)_path   )_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 r3   s/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/matplotlib/backends/backend_pdf.py_fill_   s   
r5   c           
   
   C   s6  t d}|rtt|tj}|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 ]1}	|	|vrptd|	dt|d q[||	 ||	 std|	 d||	 d||	 j d q[d|v rt|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 Nr3   .0kvr3   r3   r4   
<dictcomp>       z)_create_pdf_info_dict.<locals>.<dictcomp>c                 S   
   t | tS r;   )
isinstancestrxr3   r3   r4   is_string_like      
z-_create_pdf_info_dict.<locals>.is_string_likezan instance of strc                 S   rB   r;   )rC   r   rE   r3   r3   r4   is_date   rH   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 )N)s   Trues   Falses   Unknown)TrueFalseUnknownrC   NamenamerE   r3   r3   r4   check_trapped   s   

z,_create_pdf_info_dict.<locals>.check_trappedz#one of {"True", "False", "Unknown"})	TitleAuthorSubjectKeywordsr8   r9   r:   ModDateTrappedzUnknown infodict keyword: z. Must be one of .zBad value for infodict keyword z. Got z which is not rV   )osgetenvr   fromtimestampintr   utcreplacer    todaympl__version__itemstext_for_warningr   warn_externalsetrN   )
backendmetadatasource_date_epochsource_dateinforG   rI   rP   keywordsr>   r3   r3   r4   _create_pdf_info_dictu   sV   
 
rk   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altzoner   )drzr3   r3   r4   _datetime_to_pdf   s   
rv   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)rF   ywidthheightangle	sin_angle	cos_angleabcrs   efr3   r3   r4   !_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       | ]}|d  V  qdS r   Nr3   r=   r?   r3   r3   r4   	<genexpr>      z,_get_coordinates_of_block.<locals>.<genexpr>c                 s   r   r"   Nr3   r   r3   r3   r4   r     r   c                 s   r   r   r3   r   r3   r3   r4   r     r   c                 s   r   r   r3   r   r3   r3   r4   r     r   )r   minmaxtuple	itertoolschainfrom_iterable)rF   r{   r|   r}   r~   verticespadmin_xmin_ymax_xmax_yr3   r3   r4   _get_coordinates_of_block   s   	
r   c           	      C   sR   t |||||\}}tdtd|g dtd|  dd}|d r'||d< |S )	z=
    Create a link annotation object for embedding URLs.
    AnnotLinkr   r   r   URI)Sr   )TypeSubtypeRectBorderAr   
QuadPoints)r   rN   get_url)	gcrF   r{   r|   r}   r~   
quadpointsrectlink_annotationr3   r3   r4   _get_link_annotation  s   
r   z\\z\(z\)z\nz\r)\()
c                 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rVt|  rM| d	S tj| d
 S t| trjd| dtd d S t| trtdgdd |  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|  d)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<   r3   r3   r4   
<listcomp>[  s   ( zpdfRepr.<locals>.<listcomp>s   >>   [c                 S      g | ]}t |qS r3   r   r=   valr3   r3   r4   r   a         ]Ns   nullc                 S   r   r3   r   r   r3   r3   r4   r   m  r   z$Don't know a PDF representation for z objects) hasattrr   rC   floatnpfloatingisfinite
ValueErrorrstripboolr[   integerrD   isasciiencodecodecsBOM_UTF16_BEbytesdecode	translate_str_escapesdictr5   ra   listr   r   rv   r   bounds	TypeErrortype)objrt   r3   r3   r4   r   +  sN   





	

r   c                 C   s&   | dkr|dkS | dkr|dkS t  )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.
          *     )NotImplementedError)fonttypeglyphr3   r3   r4   _font_supports_glypht  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   
   || _ d S r;   idselfr   r3   r3   r4   __init__  rH   zReference.__init__c                 C   
   d| j  S )Nz<Reference %d>r   r   r3   r3   r4   __repr__  rH   zReference.__repr__c                 C   r   )Ns   %d 0 Rr   r   r3   r3   r4   r     rH   zReference.pdfReprc                 C   s,   |j }|d| j  |t| |d d S )N	   %d 0 obj
s   
endobj
)writer   r   )r   contentsfiler   r3   r3   r4   r     s   zReference.writeN)__name__
__module____qualname____doc__r   r   r   r   r3   r3   r3   r4   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dd ZdS )rN   zPDF name object.rO   c                 C   s   i | ]}|d | qS )z#%02xr3   r=   r   r3   r3   r4   r@     s    zName.<dictcomp>   !~r"   c                 C   sB   t |tr|j| _d S t |tr|d}|| jd| _d S )Nr   )rC   rN   rO   r   r   r   _hexifyr   )r   rO   r3   r3   r4   r     s
   


zName.__init__c                 C   r   )Nz	<Name %s>r   r   r3   r3   r4   r     rH   zName.__repr__c                 C   s   d| j d S )N/r   )rO   r   r   r3   r3   r4   __str__     zName.__str__c                 C   s   t |to
| j|jkS r;   rM   r   otherr3   r3   r4   __eq__     zName.__eq__c                 C   s   t |to
| j|jk S r;   rM   r   r3   r3   r4   __lt__  r   zName.__lt__c                 C   
   t | jS r;   )hashrO   r   r3   r3   r4   __hash__  rH   zName.__hash__c                 C   s
   d| j  S )N   /r   r   r3   r3   r4   r     rH   zName.pdfReprN)r   r   r   r   	__slots__rangeordr   r   r   r   r   r   r   r   r3   r3   r3   r4   rN     s    $rN   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   rF   r3   r3   r4   r     rH   zVerbatim.__init__c                 C      | j S r;   r  r   r3   r3   r4   r        zVerbatim.pdfReprN)r   r   r   r   r   r   r3   r3   r3   r4   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(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   shc                 C   r  r;   )valuer   r3   r3   r4   r     r	  z
Op.pdfReprc                 C   s$   |r
|r| j S | jS |r| jS | 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.
        )fill_strokestrokefillendpath)clsr!  r   r3   r3   r4   
paint_path  s   zOp.paint_pathN),r   r   r   r   close_fill_stroker  r!  	closepath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_nonstrokesetcolor_strokesetcolor_nonstrokesetdashsetlinejoin
setlinecap	setgstategsavegrestoretextpos
selectfont
textmatrixshowshowkernsetlinewidthclipshadingr   classmethodr$  r3   r3   r3   r4   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   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 )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)FilterDecodeParmspdf.compression)r   r(   rH  fhr   rI  r   rJ  copyupdaterN   
recordXrefr_   rcParamszlibr   _writeHeadertellrK  )r   r   r(   r   rJ  pngr3   r3   r4   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   LengthrO  rL  rM  s   
stream
)	r   r   r   rJ  r(   r_   rT  rN   r   )r   r   r   r3   r3   r4   rV  9  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   getvaluerH  rP  rV  r   rW  rK  writeObject)r   r   r2   r3   r3   r4   endD  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)rI  r   r   compress)r   data
compressedr3   r3   r4   r   T  s   
zStream.writec                 C   s.   | j dur| j  }| j| d| _ dS dS )zFlush the compression object.N)rI  flushr   r   )r   r`  r3   r3   r4   rZ  ]  s
   


zStream._flushNN)
r   r   r   r   r  r   rV  r]  r   rZ  r3   r3   r3   r4   rG  	  s    
'	rG  c                 C   s  t | dd}d|j }i }|D ]}||tj}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"   )hinting_factor  r   g      ?@   r      axis))DejaVuSerif-ItalicM   )ri      r   s    d1
F)r  r      r  r  Tr  )r   units_per_EM
load_glyphr   NO_SCALEr   arrayhoriAdvancebboxastyper[   get_pathnonzerosortedallpostscript_namer*   maprD   r   r!   convert_to_stringr   get_glyph_name)	font_path	glyph_idsfontconvprocsglyph_idgd1r?   r   quadsquads_onquads_mid_onimplicitr3   r3   r4   _get_pdf_charprocsf  sF   
$	$  r  c                       s  e Zd ZdZde 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dfd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ed8e d9d: Z!d;d< Z"d=d> Z#d?d@ Z$dAdB Z%dCdD Z&dEdF Z'dedGdHZ(dIdJ Z)dKdL Z*dMdN Z+dOdP Z,dQdR Z-e.dgdSdTZ/dhdVdWZ0didYdZZ1d[d\ Z2d]d^ Z3d_d` Z4dadb Z5dcdd Z6  Z7S )jPdfFilezPDF file object.Nc                    sD  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 | _*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)return_openeds	   %PDF-1.4
s   % 
rootpagesfontszextended graphics statesztiling patternszGouraud triangleszexternal objects	resourcesCatalog)r   Pagespdfc                 s       | ]
}t d | V  qdS )FNrN   r=   r0   r3   r3   r4   r         z#PdfFile.__init__.<locals>.<genexpr>c                 s   r  )r   Nr  r  r3   r3   r4   r     r  c                 s   r  )SMNr  r  r3   r3   r4   r     r  c                 s   r  )HNr  r  r3   r3   r4   r     r  c                 s   r  )INr  r  r3   r3   r4   r     r  c                 S   r   r3   r  r=   rF   r3   r3   r4   r     r   z$PdfFile.__init__.<locals>.<listcomp>PDF Text ImageB ImageC ImageI)FontXObject	ExtGStatePatternShadingProcSet)6superr   r   count_object_seq	xrefTablepassed_in_file_objectoriginal_file_like	tell_baser   to_filehandlerW  OSErrorr   rP  currentstreamr   reserveObject
rootObjectpagesObjectpageList
fontObject_extGStateObjecthatchObjectgouraudObjectXObjectObjectresourceObjectrN   r\  rk   infoDict	fontNames_internal_font_seqdviFontInfotype1Descriptorsr#   CharacterTracker_character_trackeralphaStates_alpha_state_seq_soft_mask_states_soft_mask_seq_soft_mask_groups_hatch_patterns_hatch_pattern_seqgouraudTriangles_images
_image_seqmarkersmulti_byte_charprocspaths_annotationspageAnnotationssplit)r   filenamerf   rP  openedr  procsetsr  	__class__r3   r4   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annotationsPager   H   )r   Parent	ResourcesMediaBoxContentsAnnotspagezlength of content stream	DeviceRGBround)	endStreamr|   r}   r  rN   r  r  r\  r  r)   r  r  beginStreamr   outputr
  r4  r5  GraphicsContextPdf
joinstylesr9  )r   r|   r}   contentObjectannotsObjectthePage
pageObjectr3   r3   r4   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  r)   )r   textpositionRecttheNoter3   r3   r4   newTextnote  s   zPdfFile.newTextnotec                    sH    fdd t t| tjd d  } |d}|d d d | S )Nc                    s.   | |k r	t j|  S  | | |t j| |   S r;   )stringascii_uppercase)nbasetoStrr3   r4   r  '  s   
z,PdfFile._get_subsetted_psname.<locals>.toStrr"   rf        +)r   	frozensetkeyssysmaxsize)r   ps_namecharmaphashedprefixr3   r  r4   _get_subsetted_psname&  s   	
zPdfFile._get_subsetted_psnamec              
   C   s  |    |   |   |   |   |   |   dd | j D }| j	 D ]
}|d ||d < q+| j
 D ]\}}|||< q;| jD ]\	}}}}}}	}
}}|||< qG| | 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 r3   r3   )r=   imagerO   obr3   r3   r4   r@   @  s    z$PdfFile.finalize.<locals>.<dictcomp>r"   r   r  )r   KidsCountN)r  _write_annotations
writeFontswriteExtGSTates_write_soft_mask_groupswriteHatcheswriteGouraudTrianglesr  valuesr  r  ra   r  r\  r  writeImageswriteMarkerswritePathCollectionTemplatesr  rN   r  r(   writeInfoDict	writeXrefwriteTrailer)r   xobjectstuprO   r  pathtransr  r*   cappaddingfilledstrokedr3   r3   r4   finalize6  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  r  rP  ra  r  r   r[  closer   r3   r3   r4   r  W  s   
zPdfFile.closec                 C   s*   | j d u r| j| d S | j | d S r;   )r  rP  r   r   r_  r3   r3   r4   r   b  s   
zPdfFile.writec                 G   s&   |  tdd |D  |  d d S )Nc                 S   r   r3   r   r  r3   r3   r4   r   i  r   z"PdfFile.output.<locals>.<listcomp>r&   )r   r5   r  r3   r3   r4   r  h  s   zPdfFile.outputc                 C   s$   | j d u sJ t||| ||| _ d S r;   )r  rG  )r   r   r(   rJ  rX  r3   r3   r4   r  l  s   zPdfFile.beginStreamc                 C   s"   | j d ur| j   d | _ d S d S r;   )r  r]  r   r3   r3   r4   r  p  s   


zPdfFile.endStreamrJ  c                C   s(   |  |jd | | j| |   d S r;   )r  r   r  r   r  )r   refr_  rJ  r3   r3   r4   outputStreamu  s   zPdfFile.outputStreamc                 C   s    | j D ]
\}}| || qd S r;   )r  r\  )r   r  r  r3   r3   r4   r  z  s   zPdfFile._write_annotationsc                 C   s   t |tr	|g}ntjd rtj|dtjd}nt|}d}|D ]%}| j	|}|s-|}|du rFt
| j}|| j|< td|| |sF|}q!|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)rC   rD   r_   rT  _fontManager_find_fonts_by_propsRendererPdf_afm_font_dirr  getnextr  _logdebug)r   fontprop	filenamesfirst_FxfnameFxr3   r3   r4   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+  texnamer6  r   
PsfontsMapfind_tex_filer  r   formatpsnamer,  r  r-  r.  typesSimpleNamespaceencodingr:  )r   r5  dvi_infotex_font_mappsfontr6  r3   r3   r4   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.)rx  r  ra   r6  r-  r.  _embedTeXFontr  endswith_write_afm_fontr  usedr+  embedTTFr\  r  )r   r  dvinameri   r3  r  charsr3   r3   r4   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_fontnamerN   r  r\  )r   r  rP  r  fontnamefontdictfontdictObjectr3   r3   r4   rI    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 widthsrS  r  rO  r   r"   )r   r   	FirstCharLastCharWidthsrR  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.rQ  FontNameslant        extend      ?FontDescriptor)r-  r.  r5  r;  __dict__r  r\  widthsrN   r(   r9  r{  r   
_parse_encr7  warningr8  r
   	Type1Fontr:  	transformpropr+  r  createType1Descriptor)r   fontinfowidthsObjectrX  rW  t1fontr:  fontdescr3   r3   r4   rG    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	|j
d d t|j
d t|j
d ddd |S )Nfont descriptorz	font fileItalicAngleisFixedPitchr   r"   rf         re           rd  r_  rd  i  
FamilyName2   )r   r_  FlagsFontBBoxrr  AscentDescent	CapHeightXHeightFontFile
FontFamilyStemVrn  )Length1Length2Length3r   )r  rk  r   rN   rt  ascender	descenderr\  r"  r*   partsr(   )
r   ro  r7  fontdescObjectfontfileObjectitalic_anglefixed_pitchflagsft2font
descriptorr3   r3   r4   rl    sJ   



zPdfFile.createType1Descriptorc                 C   s4   |  |}d|j tjtj|d |gS )N-r   )r4  r*   rO   r   rX   r  splitextbasename)r   r  
glyph_namer3  r3   r3   r4   _get_xobject_glyph_nameU  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                    st  t }tjd |jdfdd  fdd} fdd}|j| d	d
t|	dp@ddd}|	dpIddi}|j
}|j}	d}
d}tj|v r]|
dO }
	 |re|
dO }
n|
dO }
tj|	v rr|
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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.rd  r   )r  rw   floorceil)r2   upenearestr  r3   r3   r4   cvtw  s   

zPdfFile.embedTTF.<locals>.cvtc                    sf   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| |}qt|}i }t|D ]C}|| }i }||v rtdtd|
d}||dd d } d}j|||d  ||v r|}|j|< q|||< qՈ|| || || || |S )!z5The Type 3-specific part of embedding a Truetype fontrY  rq  rS  zcharacter procs)r   r   c                       g | ]} |d dqS Fr  r3   r  r  r3   r4   r         z;PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.<listcomp>r  Type3r_  )MbP?r   r   r  r   r   rR  r]  )r   rQ  rZ  r[  rd  r   rN   r|  
FontMatrix	CharProcsrR  r\  r   )cp1252c                    s.   t  j|  }j|tjtjB dj}|S )Nr  )r  decoding_table	load_charr   rq  
NO_HINTINGrs  )charcoder1   r|   )r  r  r  r3   r4   get_char_width  s   z?PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.get_char_widthignorec                    s   g | ]} |qS r3   r3   )r=   r  )r  r3   r4   r     s    r"   NMaxWidthr   r  Formr   r   BBox   d1rf  charProcr   )r  rt  rN   	encodingsr  warningscatch_warningsfilterwarningsr  r   rd   get_char_indexr)   r}  addsortr  rx  findr"  r  r  r\  )r  
charactersr  rn  r  rX  charprocsObjectdifferencesArray	firstcharlastcharrt  rW  rf  r  differencesmulti_byte_charsr   ccodegindr  last_crO   rawcharprocs	charprocscharnamestreamcharprocDictcharprocObject)r  r  r  r   )r  r  r  r4   embedTTFType3  s   











	


z'PdfFile.embedTTF.<locals>.embedTTFType3c           (         s   d} d} d} d} d} d} d}	dd	d
 |D }
td|
 t|
}t|}W d   n1 sJw   Y  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 ]-}|}| |}| j|tjtjB d}|| |jf |dk rt|||< t||}q|  |d|d  }d}g }d}g }|D ]2\}}||d kr|| ||g |||g n|d  | ||d  d< t||}|}qg }|D ](\}}|d!kr*qtd!|}|d"||d#d$d
 t||d D f  qjt|d%|f }g } |D ]}t|sj||}| | qX fd&d'|jD }!t | }"t!|"D ]4}#|"|# }$td(td)|!d*}%|$|$"d+d, d }$ d-}&j|&|$|%d #|#}'|&j$|'< qd|%d.}|| |	| ||d/< &|| &|| &|| &|| |S )0z6The Type 42-specific part of embedding a Truetype fontrq  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   r3   r3   r4   r     r   z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>zSUBSET %s characters: %sNzSUBSET %s %d -> %dr  CIDFontType2AdobeIdentityr   )RegistryOrdering
Supplement)r   r   rQ  CIDSystemInford  WCIDToGIDMapType0z
Identity-H)r   r   rQ  rR  DescendantFonts	ToUnicode	FontFile2r  r    rv  r  r"   r  rm  r   s   <%04x> <%04x> [%s]r%   c                 s   s    | ]}d | V  qdS )s   <%04x>Nr3   r  r3   r3   r4   r   M  r   r&   c                    r  r  r3   r  r  r3   r4   r   X  r  z<PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<listcomp>r  r  r  r  rf  r  utf-16ber  )'r  r*   r-  r.  r#   get_glyphs_subsetfont_as_filerX   statst_size	getbuffernbytesr   rN   r"  r[  r  r  r   rq  r  r)   rs  r  r   r  r   r  _identityToUnicodeCMapr(   r   rt  r  rx  r  r  r  r   r\  )(r  r  r  r  cidFontDictObjecttype0FontDictObjectcidToGidMapObjectr  wObjecttoUnicodeMapObject
subset_strsubsetfontdata	full_fontcidFontDicttype0FontDictcid_to_gid_maprf  	max_ccoder   r  r  r   
last_ccodew	max_widthunicode_groupsr|   unicode_bfrangestartr]  unicode_cmapr  rt  r  r  r  r  r  rO   r  r  r   r  r   r3   r4   embedTTFType42  s   

















	
z(PdfFile.embedTTF.<locals>.embedTTFType42r   r]   pcltr   )	capHeightxHeightpostitalicAngler   r   Fr"   rf  rt  ru  re  rv  rw  rx  rd  c                    r  r  r3   r  r  r3   r4   r     r  z$PdfFile.embedTTF.<locals>.<listcomp>r  r  r  )
r   r_  r{  r|  r}  r~  r  r  rr  r  r   r   N)r   r_   rT  ro  r  rz  get_charmapr   rN   get_sfnt_table
face_flagsstyle_flagsr   FIXED_WIDTHr   ITALICrt  r  r  )r   r  r  r  r  r  r  r  ffsfr  symbolicr  r3   r  r4   rK  q  sZ   
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   r  r"   )r   CAca)r  r+  r,  r  rN   )r   alphastaterO   r3   r3   r4   
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  r  Transparency
DeviceGray)r   CS)r"   r   r   r"   r   r   r  r   )r   r   r"   r"   )r   r   FormTypeGroupMatrixr  r  )
r  r+  r,  r  r  rN   r  r)   r
  rE  )r   smaskr  rO   groupObr3   r3   r4   _soft_mask_state  s<   



zPdfFile._soft_mask_statec                 C   s*   |  | jtg | j | j  d S r;   )r\  r  r   r  r  r  r   r3   r3   r4   r
    s   zPdfFile.writeExtGSTatesc                 C   s8   | j D ]\}}}| |jd | | j|  |   qd S r;   )r  r  r   r  r  )r   r  
attributescontentr3   r3   r4   r    s
   

zPdfFile._write_soft_mask_groupsc                 C   sj   |\}}}}|d urt |}|d urt |}||||f}| j|d }|d ur)|S t| j}|| j|< |S r;   )r   r  r+  r,  r  )r   hatch_styleedgefacehatchlwpatternrO   r3   r3   r4   hatchPattern  s   

zPdfFile.hatchPattern3.10c                 C   s   dd | j  D S )Nc                 S   s$   i | ]\}\}}}}||||fqS r3   r3   )r=   r>   r   r   hlr3   r3   r4   r@     s    z$PdfFile.<lambda>.<locals>.<dictcomp>)r  ra   r   r3   r3   r4   <lambda>  s    zPdfFile.<lambda>c                 C   s@  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rs| 	|d	 |d |d t
jd	d	||t
jt
j
 | 	|
t
j | j	| jt|	t |dd  | 	t
j |   q
| | j| d S )N      R@zhatch patternProcsetsc                 S   r   r3   r  r  r3   r3   r4   r     r   z(PdfFile.writeHatches.<locals>.<listcomp>r  r  r"   r   r  )	r   PatternType	PaintType
TilingTyper  XStepYStepr  r  rf  Fsimplify)r   r  ra   r  r  r  r   rN   r}   r  r
  r2  r3  r+  r!  rC  pathOperationsr   r#  r   scaler  r  r\  r  )r   	hatchDictsidelenr   rO   r  res
stroke_rgbfill_rgbr#  r$  r3   r3   r4   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   r(   r  r  r)   )r   pointscolorsrO   r  r3   r3   r4   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"   rf  r"   rt  rt  r   rg  r   l    ru     r  r  F)ShadingTypeBitsPerCoordinateBitsPerComponentBitsPerFlag
ColorSpace	AntiAliasDecode)r  u1)r;  z>u4)rf  r<  rG  dtyper  r;  g     o@)r   r  shapereshaper   r   r   r  r   rN   emptyr   tobytesr  r\  r  )r   gouraudDictrO   r  r;  r<  rJ  flat_pointscolordimflat_colors
points_min
points_maxfactor	streamarrr3   r3   r4   r  Q  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  r3   r3   r4   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.
        Nrm  rf  r   C)orderrt  ).Nr   )ndimr   rr  rJ  ry  )r   imrgbr  r3   r3   r4   _unpack  s   
zPdfFile._unpackc           	      C   s   t  }|j|dd |d d}d }}	 td|d\}}|dv rO||}t||kr4td	|d
kr?t|d }n|dkrF|}n|dkrN||7 }n|dkrTn||d |dd q|||fS )zn
        Write the image *img* into the pdf file using png
        predictors with Flate compression.
        rX  )r>  r?  rn  NTs   !L4s)   IHDR   PLTE   IDATztruncated datar^  r_  r`  s   IENDr"   rt  )	r   saveseekstructunpackreadr(   RuntimeErrorr[   )	r   imgbufferpng_data	bit_depthpaletter2   r   r_  r3   r3   r4   	_writePng  s0   


zPdfFile._writePngc                 C   sd  |j \}}}tdtd||tddd| dd}|r ||d< tjd	 r|j d
 dkr3|jd
d}d||d}t|}	|	jdd}
|dkr|
durt|
}t	j
dd |
D t	jd}|ddd t	jd> |ddd t	jd> B |ddd B }|dddddf t	jd> |dddddf t	jd> B |dddddf B }t	|t	j}|t	j|||d }tj|dd}	|	| | |	\}}}|du s|du rtd|d|d  }tdtd|d |g|d< ||d< d|d < ||d< n| |	\}}}nd}| j|| d!||d" |r$| 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.
        r  r   r  r  r"   r   r?  )r   r   WidthHeightrD  rB  r  rO  rm  r"   rg  
   )	PredictorColorsColumnsr   )	maxcolorsr   Nc                 S   s   g | ]\}}|D ]}|qqS r3   r3   )r=   _colorcompr3   r3   r4   r     rA   z%PdfFile._writeImg.<locals>.<listcomp>rH  r      rf  )sorterP)modezinvalid PNG headerIndexedrD  rB  rr  zlength of image stream)rX  )rJ  rN   r_   rT  squeezer   	fromarray	getcolorsr(   r   rr  uint8ru  uint32argsortsearchsorted
putpaletterl  rf  r  r  r  r   rM  r  )r   r_  r   r  r}   r|   color_channelsr   rX  rg  
img_colors
num_colorsrk  	palette24rgb24indicesrgb8ri  rj  ru  r3   r3   r4   	_writeImg  sr   
  

zPdfFile._writeImgc                 C   s^   | j  D ]'\}}}| |\}}|d ur"| d}| ||j nd }| ||j| qd S )Nr  )r  r  r]  r  r  r   )r   rg  rO   r  r_  adatasmaskObjectr3   r3   r4   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.Fr2  NzM%dz	marker %drm  r   )	r4  r   r   r  r+  rN   r(   r  get_extents)r   r  r  r!  r   r$  	joinstylecapstylepathopskeyr/   rO   r  rt  r3   r3   r4   markerObject  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  r  r  )r  ra   paddedr  r   rN   r   extentsr  r  r  r
  r9  	capstylesr:  r$  r  )
r   r  r!  r   r  r  rO   r  rt  r$  r3   r3   r4   r  #  s$   


zPdfFile.writeMarkersc           	      C   sP   t dt| j }| dt| j }| j||||| | |||f	 |S )NzP%dzpath %d)rN   r(   r  r  r)   get_joinstyleget_capstyle)	r   r   r  r  r  r  r  rO   r  r3   r3   r4   pathCollectionObject9  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 )NFr2  r   r   r   r   r  r  r  )r  r4  r  r   ry  r   r  r  r   r  r   rN   r  r  r  r
  r9  r  r:  r$  r  )r   rO   r  r  r  r  r  r  r  r  r  rt  r  r3   r3   r4   r  A  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  rn  T)	r  r!   r|  r
  r-  r  r,  r*  r&  )r  rj  rD  r3  sketchr3   r3   r4   r4  V  s   
zPdfFile.pathOperationsFc                 C   sN   |rdd| j d | jd f}|j}nd }d}| j|||||d}| j|  d S )Nra  r  F)r3  r  )r|   r}   should_simplifyr4  r  )r   r  rj  rD  r  r3  cmdsr3   r3   r4   	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,  r  r  r)   r   )r   rO   r   r3   r3   r4   r  j  s   
zPdfFile.reserveObjectc                 C   s   | j  | j | j| d< d S Nr   )rP  rW  r  r  r   r3   r3   r4   rS  u  s   zPdfFile.recordXrefc                 C   s   |  |j |||  d S r;   )rS  r   r   )r   objectr   r3   r3   r4   r\  x  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 
)	rP  rW  r  	startxrefr   r(   r  r'   AssertionError)r   r0   offset
generationrO   r  r  r3   r3   r4   r  |  s   
zPdfFile.writeXrefc                 C   s    |  d| _| | j| j dS )z8Write out the info dictionary, checking it for good formri   N)r  
infoObjectr\  r  r   r3   r3   r4   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   r   r(   r  r  r  r  r   r3   r3   r4   r    s   
zPdfFile.writeTrailerr;   rb  )NNNFN)r  )8r   r   r   r   r   r  r  r  r  r  r   r  r  r  r"  r  r4  rF  r	  rI  rG  rl  r  r  rK  r  r  r
  r  r&  r   
deprecatedpropertyhatchPatternsr  r=  r  rW  r]  rl  r  r  r  r  r  r  staticmethodr4  r  r  rS  r\  r  r  r  __classcell__r3   r3   r  r4   r    sh    i	!
:?  @4	&,
?


r  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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;   )r  r   r   new_gcr   	image_dpi)r   r   r  r}   r|   r  r3   r4   r     s   

zRendererPdf.__init__c                 C   s   | j j| j   d S r;   )r   r  r   r  r   r3   r3   r4   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ra  ra  ra  _effective_alphasrc  rc  r  T)isRGBArt  r   rc  )getattrr  get_rgbset_foreground_forced_alpha_alphar  r(   _rgbr   deltar   r  )r   r   	fillcolor	orig_fillorig_alphasr  r3   r3   r4   check_gc  s   
zRendererPdf.check_gcc                 C   s
   | j d S )Nr+  )r  r   r3   r3   r4   get_image_magnification  rH   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 )Nrf  r   rc  r+  r"   )rJ  	set_alphar  r  r   rW  r  r
  r<  r.  r/  r=  frozen	to_values)r   r   rF   r{   r[  rj  r(  r  imobtr1tr2tr3tr4tr5tr6r3   r3   r4   
draw_image  s(   





zRendererPdf.draw_imagec                 C   sH   |  || | j|||d u o| d u |  | j| j  d S r;   )r  r   r  get_hatch_pathget_sketch_paramsr  r   paint)r   r   r  rj  rgbFacer3   r3   r4   	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   ra  r   r  r   r"   )r   asarrayr(   	get_hatchry  r   _iter_collection_uses_per_pathr   draw_path_collectionr   r'   _iter_collection_raw_pathsr   r  r)   r  r   push_iter_collectionr  r
  r.  r/  pop)$r   r   master_transformr  all_transformsoffsetsoffset_trans
facecolors
edgecolors
linewidths
linestylesantialiasedsurlsoffset_positioncan_do_optimizationr  r  len_pathuses_per_pathshould_do_optimizationr  
path_codesr0   r  rj  rO   r  lastxlastyxoyopath_idgc0r  dxdyr3   r3   r4   r    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   r  F)rD  r3  r  r"   )r(   r   draw_markersr  r!  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usesr!  r   r  markerr  r  r   coderF   r{   r  r  r3   r3   r4   r  4  sD   

 
zRendererPdf.draw_markersc                 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"   rf  r>  rc  )r   r   r   )r(   rZ  rJ  rK  rj  r   r=  r  r  r  r
  rE  r   allcloser  r<  r;  r=  )r   r   r;  r<  r  rJ  tpointsrO   ru  r  r  smask_obgstater3   r3   r4   draw_gouraud_trianglesZ  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>  rw   rx   rz   ry   r@  )r   rF   r{   r~   oldxoldyoldangler3   r3   r4   _setup_textpos  s   
zRendererPdf._setup_textposc                 C   s  | j j|d|\}}}	}
}| d ur&| 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 ]U\}}}}}| jj|| |j}t||s||||||f qi| ||d|| ||}}||f|kr| j| j||tj ||f}| j| t||tj qi| jtj |D ]\}}}}}|  |||!||| q|D ]\}}}}| jtj||||tj"tj#tj$ q| jtj$ d S )Nr  rm  r"   r  rb  r   r   )%
_text2pathmathtext_parserparser   r   r  r)   r   r_   rT  rw   rx   r  r
  r<  rz   ry   r.  r  r  r(  r  track_glyphr2  r   r  r4  r?  encode_stringr  rA  r)  _draw_xobject_glyphr  r+  r!  r=  )r   r   rF   r{   r1   rk  r~   r|   r}   descentglyphsrectsr   r   	prev_fontr  r  unsupported_charsr  fontsizenumoxoyrV  r3   r3   r4   draw_mathtext  sV   



zRendererPdf.draw_mathtext)mtextc          #   	   C   s  |   }| }	|||	}
t|
d}|\}W d    n1 s"w   Y  | d urA| jjd d t	||||j
|j| d g }}|jD ],\}}}}}||kre| j|}|d||jgg7 }|}|d||t|gg|| gg7 }qId\}}}	|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 = q{|d7 }|t|d k st |||}| ||j | jtj d\}}}}|D ]^}|d dkr>| j|d |d tj q&|d dkr||d |d f\}}| ||||| ||}}t|d dkrw| 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 )Nr  rm  r"   r  r  )r   r   Nrf  r   rt  g?r   g     @@r  ))get_texmanagerget_size_in_pointsmake_dvir   Dvir   r   r  r)   r   r|   r}   r  rF  sizer   r(   absr   
rotate_degr   r  r  r  r
  r(  r?  rj  r  rA  rB  r)  r  copy_propertiesset_linewidthr   MOVETOLINETO	CLOSEPOLYboxesr  )#r   r   rF   r{   r1   rk  r~   r  
texmanagerr  dvifiledvir  oldfontseqx1y1r5  r   r|   r6  r0   curxeltnxtr  mytranscuryr  r  boxgcr  r(  r  r  r3   r3   r4   draw_tex  s~   
"

0$



*zRendererPdf.draw_texc                 C   s    |dv r
| ddS | ddS )Nrm  r  r]   r  )r   )r   r1   r   r3   r3   r4   r
  	  s   zRendererPdf.encode_stringFc	              	      s   ||j |r||||||S |  tjd r$|}	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 d S g }g }d}|	}tj||	tjdD ]E}tt|j r|s|j!|kr||j!|j"g f |j!}|j#r|d d	 |j# |d d	 |j  d
}q||j!|j"|j$f d}qjtj% t&'|}jt&(|t&)|t&)| t&(|||tj* jtj d}|D ]7\}}}j|j+}j| tj |dd|dd j fddt,-|t.D tj/ |}qjtj |D ]\}}}0| ||d qPjtj1 d S )Nr#  r"   r  rm  re  )r   r   T)	kern_moderf  Fr   c                    s:   g | ]\}}|t krd t|   nd|qS )ir  )r   r,  r
  r*   )r=   tpgroupr  r   r   r3   r4   r   n	  s
    z)RendererPdf.draw_text.<locals>.<listcomp>)2r  r  r  r  r_   rT  _get_font_afm_get_font_ttfr   r  trackr   set_textget_width_heightr  r)   r   r  r
  r(  r4  r?  r  r
  rA  r)  r	   layoutr   UNFITTEDr   r  char	ft_objectrF   	prev_kern	glyph_idxr<  rw   rx   rz   ry   r.  r2  r   groupbyr   rB  r  r=  )r   r   rF   r{   r1   rk  r~   ismathr  r  r|   r}   singlebyte_chunksmultibyte_glyphsprev_was_multibyter  itemr   prev_start_xr>  start_xkerns_or_charsft_namer@  r3   r5  r4   	draw_text	  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.r  r   N)r}  r   r  r2  r  r
  r<  r.  rN   r/  r=  )r   r  r  r@  rF   r{   r  rO   r3   r3   r4   r  {	  s   

zRendererPdf._draw_xobject_glyphc                 C   r   r;   )r  r   r   r3   r3   r4   r  	  s   
zRendererPdf.new_gcr;   r   r  )r   r   r   r   _get_data_pathr*  _use_afm_rc_namer   r  r  r  r  r  r  r  r  r  r  r1  r
  rK  r  r  r  r3   r3   r  r4   r)    s(    



	G
&
(
6S
a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  )r  r   r  r  r   parent)r   r   r  r3   r4   r   	  s
   

zGraphicsContextPdf.__init__c                 C   s   t | j}|d= |d= t|S )Nr   rN  )r   re  repr)r   rs   r3   r3   r4   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   ra  )r  r  r(   r  r   r3   r3   r4   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   ra  )r(   r  _hatch)r   argsr  r3   r3   r4   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   r3   r3   r4   r  	  s   zGraphicsContextPdf.paintr   r"   rf  )buttr  
projecting)miterr  bevelc                 C      | j | tjgS r;   )r  r
  r:  r   styler3   r3   r4   capstyle_cmd	  r   zGraphicsContextPdf.capstyle_cmdc                 C   rV  r;   )r  r
  r9  rW  r3   r3   r4   joinstyle_cmd	  r   z GraphicsContextPdf.joinstyle_cmdc                 C   s
   |t jgS r;   )r
  rC  )r   r|   r3   r3   r4   linewidth_cmd	  rH   z GraphicsContextPdf.linewidth_cmdc                 C   s(   |\}}|d u rg }d}t ||tjgS r  )r   r
  r8  )r   dashesr  dashr3   r3   r4   dash_cmd	  s
   zGraphicsContextPdf.dash_cmdc                 C   s   | j |}|tjgS r;   )r   r  r
  r;  )r   r  forcedeffective_alphasrO   r3   r3   r4   	alpha_cmd	  s   
zGraphicsContextPdf.alpha_cmdc                 C   sV   |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  )r  fillcolor_cmdrN   r
  r5  r   r&  r7  )r   r#  hatch_colorhatch_linewidthr   rO   r3   r3   r4   	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"   rf  r   )r_   rT  r
  r0  r2  r   r\  r3   r3   r4   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 rf  )r_   rT  r
  r1  r3  rg  r3   r3   r4   rb  	  s
   $z GraphicsContextPdf.fillcolor_cmdc                 C   s*   t | j}||  | j|_|| _tjgS r;   )r  r   r  rN  r
  r<  )r   rN  r3   r3   r4   r  	  s
   

zGraphicsContextPdf.pushc                 C   s,   | j d usJ | | j  | j j | _ tjgS r;   )rN  r  r
  r=  r   r3   r3   r4   r  	  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()`.NFr2  )	_cliprect	_clippathrN  rb  r  r  r
  r+  rD  r"  get_transformed_path_and_affiner  r4  )r   cliprectclippathr  r  affiner3   r3   r4   clip_cmd	  s&   





zGraphicsContextPdf.clip_cmd)ri  rj  )r  r  r  )	_capstyle)r  )
_joinstyle)r  )_dashes)r  )rP  _hatch_color_hatch_linewidthc           
   
      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|jdkr_|r_d}|r|jdkrhd} fdd|D }	|	|| g|	R   |D ]}t
| |t | q~q|S )z}
        Copy properties of other into self and return PDF commands
        needed to transform *self* into *other*.
        FNre  Trb  c                    s   g | ]}t  |qS r3   )r  )r=   pr   r3   r4   r   =
  s    z,GraphicsContextPdf.delta.<locals>.<listcomp>)commandsr  r   r   r   r  rJ  anyr   rb  setattr)
r   r   r  fill_performedparamscmd	differentru  ourstheirsr3   rv  r4   r  
  sB   





zGraphicsContextPdf.deltac                    s8   t  | t|d| j}t|d| j}|| _|| _dS )z5
        Copy properties of other into self.
        r  r  N)r  r  r  r  r  )r   r   r  r`  r  r3   r4   r  C
  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)rN  rb  r  )r   r  r3   r3   r4   r  N
  s
   

zGraphicsContextPdf.finalize)r   r   r   r   r   r   r!  r  r  r  rY  rZ  r[  r^  ra  re  rh  rb  r  r  ro  rw  r  r  r  r  r3   r3   r  r4   r  	  s@    &r  c                   @   st   e Zd ZdZejdddddddZ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.
    r'  
keep_emptyzThis parameter does nothing.)addendumNc                 C   s   || _ || _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 when a figure is saved for the first time (overwriting
            any older file with the same name).

        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`.
        N)	_filename	_metadata_file)r   r  r  rf   r3   r3   r4   r   m
  s   
zPdfPages.__init__c                 C   s   | S r;   r3   r   r3   r3   r4   	__enter__
     zPdfPages.__enter__c                 C   s   |    d S r;   )r  )r   exc_typeexc_valexc_tbr3   r3   r4   __exit__
  s   zPdfPages.__exit__c                 C   s"   | j d u rt| j| jd| _ | j S )Nrf   )r  r  r  r  r   r3   r3   r4   _ensure_file
  s   
zPdfPages._ensure_filec                 C   s,   | j dur| j   | j   d| _ dS dS )z_
        Finalize this object, making the underlying file a complete
        PDF file.
        N)r  r  r  r   r3   r3   r4   r  
  s
   



zPdfPages.closec                 C   s
   |   jS )z
        Return a modifiable information dictionary object
        (see PDF reference section 10.2.1 'Document Information
        Dictionary').
        )r  r  r   r3   r3   r4   infodict
  s   
zPdfPages.infodictc                 K   s`   t |ts"|du rt }nt|}|du rtd| |jj}|j| fddd| 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  )r>  re   )	rC   r   r   
get_activeget_fig_managerr   canvasfiguresavefig)r   r  kwargsmanagerr3   r3   r4   r  
  s   


zPdfPages.savefigc                 C   s   t |  jS )z=Return the current number of pages in the multipage pdf file.)r(   r  r  r   r3   r3   r4   get_pagecount
  s   zPdfPages.get_pagecountr  c                 C   s   |   || 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  r3   r3   r4   attach_note
  s   zPdfPages.attach_noterb  r;   )r   r   r   r   r   delete_parameterr   r  r  r  r  r  r  r  r  r3   r3   r3   r4   r  X
  s    

r  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 )FigureCanvasPdfr  r  zPortable Document Formatc                 C   s   dS )Nr  r3   r   r3   r3   r4   get_default_filetype
  r  z$FigureCanvasPdf.get_default_filetypeN)bbox_inches_restorerf   c          	   
   C   s   | j j}d| j _| j  \}}t|tr| }nt||d}z;||| t| j |||t	|||||d}| j 
| |  t|tsI|  W t|trU|  d S |  d S t|tre|  w |  w )Nr  r  )r  )r  dpiget_size_inchesrC   r  r  r  r  r   r)  drawr  r  r  )	r   r  r  rf   r  r|   r}   r   rendererr3   r3   r4   	print_pdf
  s0   







zFigureCanvasPdf.print_pdfc                    s   | j   t  S r;   )r  draw_without_renderingr  r  r   r  r3   r4   r  
  s   

zFigureCanvasPdf.draw)	r   r   r   	fixed_dpi	filetypesr  r  r  r  r3   r3   r  r4   r  
  s    r  c                   @   s   e Zd ZeZdS )_BackendPdfN)r   r   r   r  FigureCanvasr3   r3   r3   r4   r  
  s    r  )r$   )r   )_r   r   r   r   enumr   	functoolsr   ior   r   loggingrw   rX   r  rc  r  rp   r@  r  rU  numpyr   PILr   
matplotlibr_   r   r	   r
   r   r   matplotlib._pylab_helpersr   matplotlib.backend_basesr   r   r   r   r   !matplotlib.backends.backend_mixedr   matplotlib.figurer   matplotlib.font_managerr   r   r'  matplotlib._afmr   matplotlib.ft2fontr   r   r   r   r   matplotlib.transformsr   r   matplotlib.pathr   matplotlib.datesr    r!   r  r#   	getLoggerr   r-  r5   rk   rv   r   r   r   rD   	maketransr   r   r   r   rN   r  r
  rG  r  r  RendererPDFPSBaser)  r  r  r  FigureManagerPdfexportr  r3   r3   r3   r4   <module>   s    

2W



I!	D].             s Nq(