
    Ngv                       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l2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z; ddl<m=Z= ddl>m?Z? ddlm@Z@ ddlAmBZB  ejC        eD          ZEd=dZFd ZGd ZHd>dZId>dZJd>dZKeLM                    ddd d!d"d#          ZNd$ ZOd% ZP G d& d'          ZQe G d( d)                      ZR G d* d+          ZS G d, d-e          ZT G d. d/          ZUd0 ZV G d1 d2          ZW G d3 d4eBjX                  ZY G d5 d6e&          ZZ G d7 d8          Z[ G d9 d:e$          Z\e%Z]e#j^         G d; d<e#                      Z_dS )?uO   
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)FIXED_WIDTHITALICLOAD_NO_SCALELOAD_NO_HINTINGKERNING_UNFITTEDFT2Font)Affine2DBboxBase)Path)UTC)_path   )_backend_pdf_psK   c                 l   d}d}g }t          |           D ]Z\  }}t          |          }||z   |k     r	||dz   z  }&|                    d                    | ||                              |}|}[|                    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lengths           [/var/www/html/ai-engine/env/lib/python3.11/site-packages/matplotlib/backends/backend_pdf.py_fillr7   `   s     GEF'""  1QVg%%vz!GGMM$))GE!G$455666EGG
MM$))GEFFO,,---::f    c           
         t          j        d          }|rHt          j        t	          |          t
          j                  }|                    t                    }nt          j	                    }dt          j         dd|  dt          j         |d|}d |                                D             }d	 }d
|_        d }d|_        d }d|_        |||||||||d	}|D ]u}	|	|vr)t          j        d|	dt!          |          d           / ||	         ||	                   s/t          j        d|	 d||	         d||	         j         d           vd|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                     i | ]
\  }}|||S N .0kvs      r6   
<dictcomp>z)_create_pdf_info_dict.<locals>.<dictcomp>   s    ===Vaq}Aq}}}r8   c                 ,    t          | t                    S r@   )
isinstancestrxs    r6   is_string_likez-_create_pdf_info_dict.<locals>.is_string_like   s    !S!!!r8   zan instance of strc                 ,    t          | t                    S r@   )rH   r   rJ   s    r6   is_datez&_create_pdf_info_dict.<locals>.is_date   s    !X&&&r8   z an instance of datetime.datetimec                 F    t          | t                    r	| j        dv S | dv S )N)s   Trues   Falses   Unknown)TrueFalseUnknownrH   NamenamerJ   s    r6   check_trappedz,_create_pdf_info_dict.<locals>.check_trapped   s.    a 	56<<<444r8   z#one of {"True", "False", "Unknown"})	TitleAuthorSubjectKeywordsr<   r=   r>   ModDateTrappedzUnknown infodict keyword: z. Must be one of .zBad value for infodict keyword z. Got z which is not r\   )osgetenvr   fromtimestampintr   utcreplacer"   todaympl__version__itemstext_for_warningr	   warn_externalsetrT   )
backendmetadatasource_date_epochsource_dateinforL   rN   rV   keywordsrD   s
             r6   _create_pdf_info_dictrq   v   s8   @ 	"566 ',S1B-C-CX\RR!)))55n&& L#/KKKF'FFS_FF#  	D >=tzz||===D" " "&:N#' ' 'AG5 5 5
 &KM"   !"!" 
 
H  C CH  DA  D  D14X D  D  D E E E E!T!W%% 	C  B  B  B&*1g B  B"*1+"> B  B  B C C C DtI//YKr8   c                     |                      d          }|                                 }||j        }n%t          j        rt          j        }nt          j        }|dk    r|dz  }n)|dk     r|d| dz  | dz  fz  z  }n|d|dz  |dz  fz  z  }|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zs      r6   _datetime_to_pdfr}      s     	


#$$A	A}I= 	AAAAvv	S	
Q	]rdlaR4K888	]a4iT222Hr8   c                    t          j        |           }t          j        |          }t          j        |          }| ||z  z   }|||z  z   }| ||z  z   ||z  z   }	|||z  z
  ||z  z   }
| ||z  z   }|||z  z
  }| |f||f|	|
f||ffS )zR
    Calculate the coordinates of rectangle when rotated by angle around x, y
    )mathradianssincos)rK   ywidthheightangle	sin_angle	cos_angleabcrz   efs                r6   !_calculate_quad_point_coordinatesr      s    
 L%  EII	FYA	FYA	EI 22A	EI 22A	EIA	EIAFQFQFQF++r8   c                 ~   t          | ||||          }|dz  rdnd}t          d |D                       |z
  }t          d |D                       |z
  }t          d |D                       |z   }	t          d |D                       |z   }
t          t          j                            |                    |||	|
ffS )zg
    Get the coordinates of rotated rectangle and rectangle that covers the
    rotated rectangle.
    Z   gh㈵>r   c              3   &   K   | ]}|d          V  dS r   NrA   rC   rE   s     r6   	<genexpr>z,_get_coordinates_of_block.<locals>.<genexpr>  &      ''!''''''r8   c              3   &   K   | ]}|d          V  dS r$   NrA   r   s     r6   r   z,_get_coordinates_of_block.<locals>.<genexpr>  r   r8   c              3   &   K   | ]}|d          V  dS r   rA   r   s     r6   r   z,_get_coordinates_of_block.<locals>.<genexpr>  r   r8   c              3   &   K   | ]}|d          V  dS r   rA   r   s     r6   r   z,_get_coordinates_of_block.<locals>.<genexpr>	  r   r8   )r   minmaxtuple	itertoolschainfrom_iterable)rK   r   r   r   r   verticespadmin_xmin_ymax_xmax_ys              r6   _get_coordinates_of_blockr      s     1Au17@ @H RZ
&''QC''h'''''#-E''h'''''#-E''h'''''#-E''h'''''#-E)///99::E5%(* *r8   c                     t          |||||          \  }}t          d          t          d          |g dt          d          |                                 dd}|dz  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   rT   get_url)	gcrK   r   r   r   r   
quadpointsrectlink_annotations	            r6   _get_link_annotationr     s     1AufeLLJW<<))e::<<
 
	 	O rz 3(2%r8   z\\z\(z\)z\nz\r)\()
c                 T   t          | d          r|                                 S t          | t          t          j        f          rPt	          j        |           st          d          d| z  }|                    d                              d          S t          | t                    r
ddg|          S t          | t          t          j        f          rd| z  S t          | t                    rXt          |                                 r|                     d	          n!t          j        |                     d
          z             S t          | t"                    rFd|                     d                              t(                                        d          z   dz   S t          | t*                    r0t-          dgd |                                 D             d          S t          | t0          t2          f          rt-          dgd | D             d          S | dS t          | t4                    rt          t7          |                     S t          | t8                    rt-          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                 |    g | ]9\  }}t          |                                          d z   t          |          z   :S )r(   )rT   r   rB   s      r6   
<listcomp>zpdfRepr.<locals>.<listcomp>\  s<    LLL1d1ggoo$&3LLLr8   s   >>   [c                 ,    g | ]}t          |          S rA   r   rC   vals     r6   r   zpdfRepr.<locals>.<listcomp>b  s    :::sgcll:::r8      ]Ns   nullc                 ,    g | ]}t          |          S rA   r   r   s     r6   r   zpdfRepr.<locals>.<listcomp>n  s    999sgcll999r8   z$Don't know a PDF representation for z objects) hasattrr   rH   floatnpfloatingisfinite
ValueErrorrstripboolra   integerrI   isasciiencodecodecsBOM_UTF16_BEbytesdecode	translate_str_escapesdictr7   rg   listr   r   r}   r    bounds	TypeErrortype)objr{   s     r6   r   r   ,  s    sI B#{{}}
 
C%-	.	. <#{3 	FDEEEsNxx~~$$T*** 
C		 4#'"3'' 
C#rz*	+	+ 0#s{ 
C		 ,#ckkmm Iszz'***"/#**Z2H2HHJ J 	J 
C		 ##JJy!!++L99@@KKL	 
C		 #
LL		LLL
 
   	 
C$	'	' #dA::c:::ADABBB 
w 
C	"	" 	#',,--- 
C	"	" #99cj999:::  "tCyy " " " # # 	#r8   c                 N    | 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glyphs     r6   _font_supports_glyphr   u  s6     1}}|2~~~


r8   c                   *    e Zd ZdZd Zd Zd Zd ZdS )	ReferencezV
    PDF reference object.

    Use PdfFile.reserveObject() to create References.
    c                     || _         d S r@   idselfr   s     r6   __init__zReference.__init__  s    r8   c                     d| j         z  S )Nz<Reference %d>r   r   s    r6   __repr__zReference.__repr__  s    $'))r8   c                     d| j         z  S )Ns   %d 0 Rr   r   s    r6   r   zReference.pdfRepr  s    47""r8   c                     |j         } |d| j        z              |t          |                      |d           d S )N	   %d 0 obj
s   
endobj
)writer   r   )r   contentsfiler   s       r6   r   zReference.write  sN    
mdg%&&&gh   mr8   N)__name__
__module____qualname____doc__r   r   r   r   rA   r8   r6   r   r     sZ           * * *# # #    r8   r   c            	           e Zd ZdZdZd h  ed          h  e ed           ed          dz             z
  D             Zd Zd	 Z	d
 Z
d Zd Zd Zd ZdS )rT   zPDF name object.rU   c                     i | ]}|d |z  	S )z#%02xrA   rC   r   s     r6   rF   zName.<dictcomp>  s4     J J J 'A+ J J Jr8      !~r$   c                    t          |t                    r|j        | _        d S t          |t                    r|                    d          }|                    | j                                      d          | _        d S )Nr   )rH   rT   rU   r   r   r   _hexifyr   )r   rU   s     r6   r   zName.__init__  sl    dD!! 	E	DIII$&& ,{{7++t|44;;GDDDIIIr8   c                     d| j         z  S )Nz	<Name %s>r  r   s    r6   r   zName.__repr__  s    TY&&r8   c                 <    d| j                             d          z   S )N/r   )rU   r   r   s    r6   __str__zName.__str__  s    TY%%g....r8   c                 L    t          |t                    o| j        |j        k    S r@   rS   r   others     r6   __eq__zName.__eq__  s     %&&B49
+BBr8   c                 L    t          |t                    o| j        |j        k     S r@   rS   r  s     r6   __lt__zName.__lt__  s     %&&A49uz+AAr8   c                 *    t          | j                  S r@   )hashrU   r   s    r6   __hash__zName.__hash__  s    DIr8   c                     d| j         z   S )N   /r  r   s    r6   r   zName.pdfRepr  s    dir8   N)r   r   r  r  	__slots__rangeordr  r   r   r  r  r  r  r   rA   r8   r6   rT   rT     s        IJ J%%%**(H%%C##c((Q,*G*G(HHJ J JGE E E' ' '/ / /C C CB B B           r8   rT   c                       e Zd ZdZd Zd ZdS )VerbatimzEStore verbatim PDF command content for later inclusion in the stream.c                     || _         d S r@   _x)r   rK   s     r6   r   zVerbatim.__init__  s    r8   c                     | j         S r@   r!  r   s    r6   r   zVerbatim.pdfRepr  s	    wr8   N)r   r   r  r  r   r   rA   r8   r6   r  r    s8        OO      r8   r  c                       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' Z)e*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                     | j         S r@   )valuer   s    r6   r   z
Op.pdfRepr  s
    zr8   c                 F    |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=  s      r6   
paint_pathzOp.paint_path  s;      		# "&z! #x{"r8   N),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   classmethodrA  rA   r8   r6   r%  r%    s       11KDILFGJHGIFFMKNM #OGKJIEHGJJDHLDG   # # [# # #r8   r%  c                   6    e Zd ZdZdZd	dZd Zd Zd Z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                 `   || _         || _        || _        |j        | _        d| _        |t                      | _        n|                                | _        |*| j        	                    t          d          |d           | j                            | j                    t          j        d         r+|s)t          j        t          j        d                   | _        | j        t                      | _        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+   rf  fhr   rg  r   rh  copyupdaterT   
recordXrefre   rcParamszlibr   _writeHeadertellri  )r   r   r+   r   rh  pngs         r6   r   zStream.__init__  s     G	=DJJDJ?Jd=.A.A.13 3 4 4 4 	(((<)* 	13 	1#/./ 1  1D8		DIIIy~~''DHHHr8   c                     | j         j        } |d| j        z             | j        }| j        |d<   t
          j        d         rt          d          |d<    |t          |                      |d           d S )Nr   Lengthrn  rk  rl  s   
stream
)	r   r   r   rh  r+   re   rs  rT   r   )r   r   r   s      r6   ru  zStream._writeHeader:  s    	mdg%&&&zX<)* 	1!-00DNgdmmmr8   c                    |                                   | j        | j                                        }t          |          | _        | j        j        | _        |                                  | j                            |           | j                            d           dS | j                                        | j	        z
  }| j                            d           | j        
                    | j        |           dS )zFinalize stream.Ns   
endstream
endobj
)_flushr+   r   getvaluerf  ro  ru  r   rv  ri  writeObject)r   r   r5   s      r6   endz
Stream.endE  s     	8y))++H8}}DHDIIOOH%%%IOO455555Y^^%%0FIOO4555L$$TXv66666r8   c                     | j         | j                            |           dS | j                             |          }| j                            |           dS )zWrite some data on the stream.N)rg  r   r   compress)r   data
compresseds      r6   r   zStream.writeU  sW     #IOOD!!!!!)22488JIOOJ'''''r8   c                     | j         <| j                                         }| j                            |           d| _         dS dS )zFlush the compression object.N)rg  flushr   r   )r   r  s     r6   r{  zStream._flush^  sK     ')//11JIOOJ'''#D ('r8   NN)
r   r   r  r  r  r   ru  r~  r   r{  rA   r8   r6   re  re  
  sw          PI%( %( %( %(N	 	 	7 7 7 ( ( ($ $ $ $ $r8   re  c                    t          | d          }d|j        z  }i }|D ]=}|                    |t                    }t	          j        |j        dg|j                  |z  dz                       t                    }|
                                \  }}	|dz                      t                    }t	          j        |	dk              \  }
|
dd d         }t	          j        t          h |h |
dz
  z  h |
dz   z            t                    }|||         ||dz
           ||dz            z   dz                      t                    k                        d	                   }|j        |fd
v r|d d dfxx         dz  cc<   ||z  dz                       t                    }||dz
           ||dz            z   dz                      t                    ||<   d                    t!          t"          |                                        d          dz   t'          j        t+          ||	          d d dd dg dd          z   dz   ||                    |          <   ?|S )Nr$   )hinting_factor  r   g      ?@   r      axis))DejaVuSerif-ItalicM   )r      r   s    d1
F)r/  r.  r8   r-  r)  Tr(  )r   units_per_EM
load_glyphr   r   arrayhoriAdvancebboxastypera   get_pathnonzerosortedallpostscript_namer-   maprI   r   r#   convert_to_stringr!   get_glyph_name)	font_path	glyph_idsfontconvprocsglyph_idgd1rE   r   quadsquads_onquads_mid_onimplicits                 r6   _get_pdf_charprocsr  g  so   Ia000D$##DE & &OOHm44 hq216233d:R?GGLL}}1VOOC   AF##A;x;X;EAI/.UQY.@AA3H H|_L1$%,*:(;;q@HHMMNSaS[[  (+ 0
 
 
 aaadGGGqLGGGX]""3''x!|_qA.!3VVC[[ 	
( HHSb\\""))'22X=%Q

D$tR---t5 55
  	d!!(++,, Lr8   c                   X    e Zd ZdZd5 fd	Zd Zg dfdZd Zd Zd	 Z	d
 Z
d Zd6dZd Zdd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#d5d%Z$d& Z%d' Z&d( Z'd) Z(d* Z)e*d7d+            Z+d8d-Z,d9d/Z-d0 Z.d1 Z/d2 Z0d3 Z1d4 Z2 xZ3S ):PdfFilezPDF file object.Nc                 :   t                                                       t          j        d          | _        g dg| _        d| _        d| _        d| _        t          j
        |dd          \  }}|sI	 |                                | _        |}d| _        n%# t          $ r t                      }|| _        Y nw xY w|| _        d| _        |                    d	           |                    d
           |                     d          | _        |                     d          | _        g | _        |                     d          | _        |                     d          | _        |                     d          | _        |                     d          | _        |                     d          | _        |                     d          | _        t7          d          | j        d}|                     | j        |           t;          d|pi           | _        i | _        d t          j        d          D             | _         i | _!        i | _"        tG          j$                    | _%        i | _&        d t          j        d          D             | _'        i | _(        d t          j        d          D             | _)        g | _*        i | _+        d t          j        d          D             | _,        g | _-        i | _.        d t          j        d          D             | _/        i | _0        i | _1        g | _2        g | _3        g | _4        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              3   :   K   | ]}t          d |           V  dS )FNrT   rC   r3   s     r6   r   z#PdfFile.__init__.<locals>.<genexpr>  .      "M"MQ4A=="M"M"M"M"M"Mr8   c              3   :   K   | ]}t          d |           V  dS )r   Nr  r  s     r6   r   z#PdfFile.__init__.<locals>.<genexpr>  s.       K K1g!gg K K K K K Kr8   c              3   :   K   | ]}t          d |           V  dS )SMNr  r  s     r6   r   z#PdfFile.__init__.<locals>.<genexpr>  s.      JJ!tHHH~~JJJJJJr8   c              3   :   K   | ]}t          d |           V  dS )HNr  r  s     r6   r   z#PdfFile.__init__.<locals>.<genexpr>  r  r8   c              3   :   K   | ]}t          d |           V  dS )INr  r  s     r6   r   z#PdfFile.__init__.<locals>.<genexpr>  s.      EEQ4A==EEEEEEr8   c                 ,    g | ]}t          |          S rA   r  rC   rK   s     r6   r   z$PdfFile.__init__.<locals>.<listcomp>      MMMDGGMMMr8   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_filehandlerv  OSErrorr   ro  currentstreamr   reserveObject
rootObjectpagesObjectpageList
fontObject_extGStateObjecthatchObjectgouraudObjectXObjectObjectresourceObjectrT   r}  rq   infoDict	fontNames_internal_font_seqdviFontInfotype1Descriptorsr%   CharacterTracker_character_trackeralphaStates_alpha_state_seq_soft_mask_states_soft_mask_seq_soft_mask_groupshatchPatterns_hatch_pattern_seqgouraudTriangles_images
_image_seqmarkersmulti_byte_charprocspaths_annotationspageAnnotationssplit)	r   filenamerl   ro  openedr  procsetsr  	__class__s	           r6   r   zPdfFile.__init__  s   " 	$?1--7778%*""&(4tLLL
F 	22!)
 -1**  3 3 3YY*2'''3 !
 	())),,V44--g66,,W55 $ 2 23M N N--.?@@!//0CDD!//0BCC"00==Y)+ +$///-eX^DD"M"M)/!:L:L"M"M"M ""1"B"D"D K K	8J8J K K K!#JJyq7I7IJJJ!#"M"M)/!:L:L"M"M"M "EE)/!2D2DEEE$&!

   " NM%D%J%J%L%LMMM
 "_ $ 2"&"7 $ 0 $ 2 (* *	 	,i88888s   7B B<;B<c                 >   |                                   ||c| _        | _        |                     d          }|                     d          }t	          d          | j        | j        ddd|z  d|z  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  rT   r  r  r}  r  r,   r  r  beginStreamr   outputr%  rQ  rR  GraphicsContextPdf
joinstylesrV  )r   r   r   contentObjectannotsObjectthePage
pageObjects          r6   newPagezPdfFile.newPage  s   "'
DK**?;;))-88<<!- $ 3 !1b5j"v+>,)  ''//
W---Z(((  ,0D!EFFF)++,FGG	I 	I 	I 	D%%r'>???D%%r'ABBB&1':BNKKK  "r8   r  r   r   c                 |    t          d          t          d          ||d}| j                            |           d S )Nr   Text)r   r   r  r   )rT   r  r,   )r   textpositionRecttheNotes       r6   newTextnotezPdfFile.newTextnote  sE    =="6ll#' 
 	##G,,,,,r8   c                     fdt          t          |                                                    t          j        dz   dz  z  } |d          }|d d         dz   |z   S )Nc                 ~    | |k     rt           j        |          S  | |z  |          t           j        | |z           z   S r@   )stringascii_uppercase)nbasetoStrs     r6   r#  z,PdfFile._get_subsetted_psname.<locals>.toStr(  sE    4xx-a00 E!t)T**V-CAH-MMr8   r$   r        +)r  	frozensetkeyssysmaxsize)r   ps_namecharmaphashedprefixr#  s        @r6   _get_subsetted_psnamezPdfFile._get_subsetted_psname'  sv    	 	 	 	 	 i//00S[1_4IJvr"" bqbzC'))r8   c           
         |                                   |                                  |                                  |                                  |                                  |                                  |                                  d | j                                        D             }| j	                                        D ]}|d         ||d         <   | j
                                        D ]
\  }}|||<   | j        D ]\	  }}}}}}	}
}}|||<   |                     | j        |           |                                  |                                  |                                  |                     | j        t'          d          | j        t+          | j                  d           |                                  |                                  |                                  dS )z>Write out the various deferred objects and the pdf end matter.c                     i | ]	\  }}}||
S rA   rA   )rC   imagerU   obs       r6   rF   z$PdfFile.finalize.<locals>.<dictcomp>A  s3     C C C(bD"C C Cr8   r$   r   r  )r   KidsCountN)r  _write_annotations
writeFontswriteExtGSTates_write_soft_mask_groupswriteHatcheswriteGouraudTrianglesr  valuesr  r  rg   r  r}  r  writeImageswriteMarkerswritePathCollectionTemplatesr  rT   r  r+   writeInfoDict	writeXrefwriteTrailer)r   xobjectstuprU   r:  pathtransr3  r-   cappaddingfilledstrokeds                r6   finalizezPdfFile.finalize7  s    	!!!$$&&&""$$$C C,0L,?,?,A,AC C C<&&(( 	& 	&C"1vHSV4::<< 	# 	#KD%"HTNN:	  	 FD$r4gvwHTNN+X666))+++)"&w--"&-#&t}#5#57 7	8 	8 	8 	 	r8   c                    |                                   | j        r| j                                         dS | j        1| j                            | j                                                   | j                                         dS )z)Flush all buffers and free all resources.N)r  r  ro  r  r  r   r|  closer   s    r6   rM  zPdfFile.closeX  ss     	% 	GMMOOOOO&2'--dg.>.>.@.@AAAGMMOOOOOr8   c                     | j         | j                            |           d S | j                             |           d S r@   )r  ro  r   r   r  s     r6   r   zPdfFile.writec  sB    %GMM$$$T*****r8   c                     |                      t          d |D                                  |                      d           d S )Nc                 ,    g | ]}t          |          S rA   r   r  s     r6   r   z"PdfFile.output.<locals>.<listcomp>j  s    333'!**333r8   r)   )r   r7   rO  s     r6   r  zPdfFile.outputi  sC    

533d33344555

5r8   c                 H    | j         J t          ||| ||          | _         d S r@   )r  re  )r   r   r+   rh  rw  s        r6   r  zPdfFile.beginStreamm  s/    !)))#BT5#>>r8   c                 X    | j         "| j                                          d | _         d S d S r@   )r  r~  r   s    r6   r  zPdfFile.endStreamq  s6    )""$$$!%D *)r8   rh  c                    |                      |j        d |           | j                            |           |                                  d S r@   )r  r   r  r   r  )r   refr  rh  s       r6   outputStreamzPdfFile.outputStreamv  sI    u---  &&&r8   c                 L    | j         D ]\  }}|                     ||           d S r@   )r  r}  )r   r  r   s      r6   r6  zPdfFile._write_annotations{  s<    )-): 	8 	8%L+\;7777	8 	8r8   c                    t          |t                    r|g}nHt          j        d         r"t	          j        |dt          j                  }nt	          j        |          }d}|D ]`}| j        	                    |          }|s|}|>t          | j                  }|| j        |<   t                              d||           |s|}a|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)rH   rI   re   rs  _fontManager_find_fonts_by_propsRendererPdf_afm_font_dirr  getnextr  _logdebug)r   fontprop	filenamesfirst_FxfnameFxs         r6   fontNamezPdfFile.fontName  s     h$$ 	D!
II\./ 	D$9%;3L  II %9(CCI 		" 		"E##E**B z$122(*u%

3R??? "!H r8   c                    | j                             |j                  }||j        S t	          j        t	          j        d                    }||j                 }|j        -t          d	                    |j
        |j                            t          | j                  }t                              d||j                   t          j        |||j        |j
        |j        |j                  | 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  rb  texnamern  r   
PsfontsMapfind_tex_filer  r   formatpsnamerc  r  rd  re  typesSimpleNamespaceencodingrr  )r   rm  dvi_infotex_font_mappsfontrn  s         r6   dviFontNamezPdfFile.dviFontName  s     #''88##)'*?*M*MNNgo.?"5w779 9 9
 t.//

17GOLLL,1,A_]N-$ -$ -$) r8   c                    i }t          | j                                                  D ]?\  }}|j        }t                              d|           |                     |          ||<   @t          | j                  D ]}| j        |         }t                              d|           |                    d          r3t                              d           | 	                    |          ||<   rt                              d           | j
        j                            |          }|r|                     ||          ||<   |                     | 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  rg   rn  rd  re  _embedTeXFontr  endswith_write_afm_fontr  usedrb  embedTTFr}  r  )r   r  dvinamero   rj  r  charss          r6   r7  zPdfFile.writeFonts  sN   #D$4$:$:$<$<== 	1 	1MGTBJJ;WEEE**400E"IIt~.. 	? 	?H)BJJ+X666  (( 	?

./// 00::b		 

3444/488BB ? $h > >E"I%00000r8   c                 h   t          |d          5 }t          |          }d d d            n# 1 swxY w Y   |                                }t          d          t          d          t          |          t          d          d}|                     d          }|                     ||           |S )Nrbr  Type1WinAnsiEncoding)r   r   BaseFontEncodingfont dictionary)openr   get_fontnamerT   r  r}  )r   r  ro  r  fontnamefontdictfontdictObjects          r6   r  zPdfFile._write_afm_font  s    (D!! 	Rr77D	 	 	 	 	 	 	 	 	 	 	 	 	 	 	$$&& LL#G}} $X $%6 7 79 9 ++,=>>222s   -11c                    t                               d|j        j        |j                   |                     d          }|                     ||j        j                   |                     d          }t          d          t          d          dt          |j        j                  dz
  |d}|j
        Bt          d	          dgt          t          t          j        |j
                            d
|d	<   |j        Ot                               d|j                   t          |j                  |d<   |                     ||           |S t#          j        |j                  }|j        r|                    |j                  }t          |j        d                   |d<   |j                            dd          |j                            dd          f}| j                            |j        |f          }|,|                     ||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)rd  re  rm  rs  __dict__r  r}  widthsrT   r+   rq  r  r   
_parse_encro  warningrp  r   	Type1Fontrr  	transformproprb  r  createType1Descriptor)r   fontinfowidthsObjectr  r  t1fontrr  fontdescs           r6   r  zPdfFile._embedTeXFont  s\   

8#+X->	@ 	@ 	@ ))-88x'7'>??? ++,=>>fgX-4559%   ,Z(( ND'"4X5J"K"KLL N$ $HZ  $LLG !# # # $((9#:#:HZ ^X666!! %h&788 	8%%h&677F#FK
$;<<
 #''55#''#668(,,h.?-IJJ11&(:KLLHBJD!8#4g">?%-!"222r8   c                    |                      d          }|                      d          }|j        d         }|j        d         }d}|r|dz  }	 	 |dz  }|r|d
z  }	 	 	 t          |          }t          d          t          |j        d                   ||j        ||j        |j        dd||j        d         dd}	|                     ||	           |                     |d	                    |j
        d d                   t          |j
        d                   t          |j
        d                   dd           |S )Nfont descriptorz	font fileItalicAngleisFixedPitchr   r$   r         r           r  r  r  i  
FamilyName2   )r   r  FlagsFontBBoxr  AscentDescent	CapHeightXHeightFontFile
FontFamilyStemVr8   )Length1Length2Length3rT  )r  r  r   rT   r  ascender	descenderr}  rW  r-   partsr+   )
r   r  ro  fontdescObjectfontfileObjectitalic_anglefixed_pitchflagsft2font
descriptors
             r6   r  zPdfFile.createType1Descriptor  s}    ++,=>>++K88{=1k.1 	VOE		VOE
  	VOE			 8$$   011J 788 "<'"+",)!;|4 
" 	444.#((6<3C*D*D,/Q,@,@,/Q,@,@,-!/ !/ 	 	0 	0 	0
 r8   c                 
   |                      |          }d                    |j                                        t          j                            t          j                            |                    d         |g          S )N-r   )rk  r-   rU   r   r^   rE  splitextbasename)r   r  
glyph_namerj  s       r6   _get_xobject_glyph_namezPdfFile._get_xobject_glyph_nameV  sh    ]]8$$xxGNNGRW--h7788;   	r8   sO  /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                 P    t                    }t          j        d         |j        dfd fd} fd}                     |j        |                                                              dd          t                    |	                    d          pd	d	d
}|	                    d          pddi}|j
        }|j        }	d	}
d}|t          z  r|
dz  }
	 |r|
dz  }
n|
dz  }
|	t          z  r|
dz  }
	 	 	 t          d          |
fd|j        D              |j        d           |j        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                     | |z  dz  }|rt          |          S |dk     rt          j        |          S t          j        |          S )z2Convert font coordinates to PDF glyph coordinates.r  r   )r
  r   floorceil)r5   upenearestr:  s       r6   cvtzPdfFile.embedTTF.<locals>.cvtx  sM    SL4'E $U||#qyyz%(((y'''r8   c                 ~    !                     d          }!                     d          }!                     d          }!                     d          }g }d\  }}	fd j        D             }
t          d           ||	|t          d          |d	         |
g d
|t          d          |d|d}ddlm  fdt          j                    5  t          j        d           fdt          ||	dz             D             }ddd           n# 1 swxY w Y   t          |          |d<   g }g }t                      }|D ]v}|}                     |          }|                    |                                |          }|dk    r|                    ||f           a|                    |           w|                                 d}|D ]G\  }}||dz   k    r|                    |           |                    t          |                     |}Ht!          |          }i }t#          |          D ]}||         }i }||v r@t          d          t          d          |
d}||                    d          dz   d         }!                     d          }!                    |||           ||v r!!                    |          }|!j        |<   |||<   !                    ||           !                    ||           !                    ||           !                    ||           |S )z5The Type 3-specific part of embedding a Truetype fontr  r  r  zcharacter procs)r   r   c                 *    g | ]} |d           S Fr  rA   rC   rK   r  s     r6   r   z;PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.<listcomp>  s(    ===aCC5)))===r8   r  Type3r  )MbP?r   r   r  r   r   r  r  )r   r  r  r  r  r   rT   r  
FontMatrix	CharProcsr  r  r   )cp1252c                     t          j        |                    }                    |t          t          z            j        } |          S )Nr  )r  decoding_table	load_charr   r   r  )charcoder4   r   r  r  r  s      r6   get_char_widthz?PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.get_char_width  sN    -h788]_< ' > >>I s5zz!r8   ignorec                 &    g | ]} |          S rA   rA   )rC   r  r  s     r6   r   z;PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.<listcomp>  s9     H H H& ).22 H H Hr8   r$   NMaxWidthr   r  Formr   r   BBox   d1r  charProcrT  )r  r  rT   	encodingsr  warningscatch_warningsfilterwarningsr  r   rj   get_char_indexr,   r  addsortr  r  findrW  r  r  r}  )"r  
charactersr  r  r  r  charprocsObjectdifferencesArray	firstcharlastcharr  r  r  r  differencesmulti_byte_charsr   ccodegindr  last_crU   rawcharprocs	charprocscharnamestreamcharprocDictcharprocObjectr  r  r  r  r+  r   s"   `                           @@r6   embedTTFType3z'PdfFile.embedTTF.<locals>.embedTTFType3  sX   --m<<L!//0ABBN!//0ABBN"001BCCO!"(Ix====49===D V#&$"0==":. 666, ,,#35 5 ' H" )(((((" " " " " " "
 (** H H '111H H H H*/	8A:*F*FH H HH H H H H H H H H H H H H H H &)[[Jz"
 IK"uu 5 5**511  &&&!0066
C<<&&z':;;;;$((4444F&  4
??$++A... ''T

333 .h	BBLI"<00 9 9%h/! ///,0OO/3F||,0$2 $2L $FKK$6$6$:$;$;<F!%!3!3J!?!?!!.&!MMM ///77(KKD6DD-d33*8Ih'' ^X666^Z888\6222_i888!!s   4DDDc                    +                     d          }+                     d          }+                     d          }+                     d          }+                     d          }+                     d          }+                     d          }	d                    d	 |D                       }
t                              d
(|
           t	          j        (|
          }t                              d(t          j        (          j        |	                                j
                   | }t          |          } t          d          t          d          *dddd|||d}t          d          t          d          *t          d          |g|	d}||d<   +                    ||                                d|	                                j
        i           dgdz  }g }d}|D ]}|}|                     |          }|                     |t"          t$          z            }|                    | '|j                  f           |dk     rt+          |          ||<   t-          ||          }|                                 |d|dz            }d}g }d}g }|D ]\  }}||dz   k    rC|                    |           |                    |g           |                    ||g           n&|d                             |           ||d         d<   t-          ||          }|}g }|D ]e\  }}|d k    rt1          d |          }|                    d!||d"                    d# t3          ||dz             D                       fz             f+j        t7          |          d$                    |          fz  }g }|D ]<}t9          )|          s*|                    |          }|                    |           ='fd%|j        D             } t=          (|          }!t?          |!          D ]}"|!|"         }#t          d&          t          d'          | d(}$|#|#                     d)          d*z   d         }#+                     d+          }%+                    |%|#|$           +!                    (|"          }&|%+j"        |&<   d                    |          #                    d,          }+                    ||           +                    |	|           ||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 map c              3   4   K   | ]}t          |          V  d S r@   )chrr  s     r6   r   z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>  s(       < <AQ < < < < < <r8   zSUBSET %s characters: %szSUBSET %s %d -> %dr  CIDFontType2AdobeIdentityr   )RegistryOrdering
Supplement)r   r   r  CIDSystemInfor  WCIDToGIDMapType0z
Identity-H)r   r   r  r  DescendantFonts	ToUnicode	FontFile2r  rT   r  r  Nr$   r  r  r   s   <%04x> <%04x> [%s]r(   c              3       K   | ]	}d |z  V  
dS )s   <%04x>NrA   r  s     r6   r   z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>M  s&      JJy1}JJJJJJr8   r)   c                 *    g | ]} |d           S r  rA   r  s     r6   r   z<PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<listcomp>X  s(    BBBaCC5)))BBBr8   r  r  r  r  r  r  utf-16ber  )%r  r-   rd  re  r%   get_glyphs_subsetr^   statst_size	getbuffernbytesr   rT   rW  r|  r  r  r   r   r,   r  r  r   r  r   r  _identityToUnicodeCMapr+   r   r  r  r  r  r  r  r   r}  ),r  r  r  r  cidFontDictObjecttype0FontDictObjectcidToGidMapObjectr  wObjecttoUnicodeMapObject
subset_strfontdata	full_fontcidFontDicttype0FontDictcid_to_gid_mapr  	max_ccoder   r  r  r   
last_ccodew	max_widthunicode_groupsr   unicode_bfrangestartr~  unicode_cmapr  r  r  r  r	  r
  r  rU   r  r  r   r+  r   s,                                          r6   embedTTFType42z(PdfFile.embedTTF.<locals>.embedTTFType42  s)   !//0ABBN $ 2 23H I I"&"4"45M"N"N $ 2 23G H H!//0BCCN((99G!%!3!3O!D!D < < < < <<<JJJ18ZHHH&8:NNHJJ$h!!)8+=+=+?+?+F   I
 8$$D V//# ' *"#"% "% #10 K V==# ..$5#6/ M '5J{# 1 1 3 3 ("4"4"6"6"=>  @ @ @ #Ve^NFI 2 2**511u-:_-L ' N Nucc%*;&<&<=>>>5==,/IIN5)y11		KKMMM+NY]N;NJAIN & 	# 	#uJN**HHUOOOHHeW%%%"))5%.9999bELL''',1N2&q)	511	"

 O, 	M 	M
s5==%oo&&)CYYJJeE3q56I6IJJJJJLLM M M M !7 00%**_2M2MNOL I# + ++He<< +$33E::D$$T***BBBB9>BBBD-h	BBL"<00 A A%h/(,Y+/<<(, .  .  E 2 2Q 6 7 78!%!3!3J!?!?!!.&!MMM33HhGG2@)$//  WW^44;;JGGN/@@@ 0,???%.Jz" .<<<0-@@@^Z888Wa(((&&r8   r   rc   pcltr   )	capHeightxHeightpostitalicAngler   r   Fr$   r  r  r  r  r  r  r  r  c                 *    g | ]} |d           S r  rA   r  s     r6   r   z$PdfFile.embedTTF.<locals>.<listcomp>  s(    BBB1Q...BBBr8   r  r=  r>  )
r   r  r  r  r  r  r  r  r  r  r   r   N)r   re   rs  r  r/  r  get_charmapr   rT   get_sfnt_table
face_flagsstyle_flagsr   r   r  r  r  )r   r  r  r  r  r;  r<  r?  ffsfr  symbolicr  r  r   r+  s   ``           @@@r6   r  zPdfFile.embedTTFr  s    !!</ -t 		( 		( 		( 		(h	" h	" h	" h	" h	" h	" h	" h	"TN	' N	' N	' N	' N	' N	' N	' N	' N	'd ,, 
 
 ..)44w--""6**LA!.L.L""6**E}f.E_ 	VOE	 	VOEEVOE; 	VOE			 )**BBBB	BBBc$-777s4>5999T+.>>>s4	?++.q1 
 q== =z:>>>^^!>$
J??? ^r8   c                     | j                             |d          }||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  rb  rc  r  rT   )r   alphastaterU   s       r6   
alphaStatezPdfFile.alphaState  sx      $$UD118OD)**D--(%(4 4 5 	 r8   c                    | j                             |d          }||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  rb  rc  r  r  rT   r  r,   r%  rb  )r   smaskrN  rU   groupObs        r6   _soft_mask_statezPdfFile._soft_mask_state  s:    &**5$778OD'(($$%GHH[)) LLl++# 	 	 	)
u% 	%%Y<<n--|,,  -,,'#u6$  #YY
#'
 	 	 	  r8   c                     |                      | j        t          g | j                                        | j                                                             d S r@   )r}  r  r   r  r<  r  r   s    r6   r8  zPdfFile.writeExtGSTates  sj    ! !((**'..00  	
 	
 	
 	
 	
r8   c                     | j         D ]@\  }}}|                     |j        d |            | j        |  |                                  Ad S r@   )r  r  r   r  r  )r   r3  
attributescontents       r6   r9  zPdfFile._write_soft_mask_groups  sa    '+'= 	 	#B
GRUD*555DK!!NN	 	r8   c                     |-|\  }}}|t          |          }|t          |          }|||f}| j                            |d           }||S t          | j                  }|| j        |<   |S r@   )r   r  rb  rc  r  )r   hatch_styleedgefacehatchpatternrU   s          r6   hatchPatternzPdfFile.hatchPattern  s    " +D$T{{T{{u-K$((d;;ND+,,*.;'r8   c                    t                      }d}| j                                        D ]\  }}|                     d          }|||<   dd d                                D             i}|                     |j        d t          d          ddddd||g|||ddddd| j        d	z  gd
	           |\  }}}	| 	                    |d         |d         |d         t          j                   |N| 	                    |d         |d         |d         t          j        dd||t          j        t          j        
  
         | 	                    t          j        d         t          j                    | j	        |                     t'          j        |	          t+                                          |          d            | 	                    t          j                   |                                  |                     | j        |           d S )N      R@zhatch patternProcsetsc                 ,    g | ]}t          |          S rA   r  r  s     r6   r   z(PdfFile.writeHatches.<locals>.<listcomp>  r  r8   r  r  r$   r   r  )	r   PatternType	PaintType
TilingTyper  XStepYStepr  r\  r  zhatch.linewidthFsimplify)r   r  rg   r  r  r  r   rT   r   r  r%  rO  rP  rH  r>  re   rs  r`  pathOperationsr!   rh  r   scaler<  r  r}  r  )
r   	hatchDictsidelenre  rU   r3  res
stroke_rgbfill_rgbrh  s
             r6   r:  zPdfFile.writeHatches  s   FF	!%!3!9!9!;!;  	  	K##O44B IdOMM%D%J%J%L%LMMMOCti !Q1!G!q!Q4;+;<> >? ? ? +6'J%KK
1z!}jm(* * *#HQK!hqk/q'7BLG% % %
 KK%67IIIDK,,
5!!

  )) -     ! ! KK'''NN)955555r8   c                     t          dt          | j                  z            }|                     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 )rT   r+   r  r  r,   )r   pointscolorsrU   r3  s        r6   addGouraudTriangleszPdfFile.addGouraudTriangles7  sf    $ FS!677788 :D : :;;$$dB%?@@@Rxr8   c                    t                      }| j        D ]\  }}}}|||<   |j        }|                    |d         |d         z  df          }|j        d         }|dv sJ |                    |d         |d         z  |f          }	|dk    rd}t	          j        |d          dz
  }
t	          j        |d          dz   }d	||
z
  z  }|                     |j        d dd
ddt          |dk    rdnd          d|
d         |d         |
d         |d         gddg|z  z   d           t	          j
        |d         |d         z  fdddd|ffg          }d|d<   ||
z
  |z  |d<   |	d d d |f         dz  |d<   |                     |                                           |                                  |                     | j        |           d S )Nr   r$   r  r$   r  r  r   r  r  l    r     r	  rX  F)ShadingTypeBitsPerCoordinateBitsPerComponentBitsPerFlag
ColorSpace	AntiAliasDecode)r  u1)r~  z>u4)r  r  r  dtyper  r~  g     o@)r   r  shapereshaper   r   r   r  r   rT   emptyr   tobytesr  r}  r  )r   gouraudDictrU   r3  r~  r  r  flat_pointscolordimflat_colors
points_min
points_maxfactor	streamarrs                 r6   r;  zPdfFile.writeGouraudTrianglesN  s@   ff(,(= '	 '	$D"ff "KLE ..%(U1X*=q)ABBK|AHv%%%% ..%(U1X*=x)HIIK1}}!444?J!444?J:
#:;Ft !&(%& !#$,MM[[|    $']JqM']JqM; !fx/0    qE!H$&&. $467 7 7I
 "#Ig#.#;v"EIh"-aaa(l";e"CIhJJy((**+++NN+[99999r8   c                     | j                             t          |          d          }||d         S t          | j                  }|                     d|           }|||f| j         t          |          <   |S )z=Return name of an image XObject representing the given image.Nr$   zimage )r  rb  r   rc  r  r  )r   r2  entryrU   r3  s        r6   imageObjectzPdfFile.imageObjectz  sv       ED118ODO$$00#($"3RYYr8   c                 @   |ddd         }|j         dk    r|dfS |ddddddf         }t          j        |d          }|j        d         dk    rG|dddddf         d         }t          j        |d	k              rd}nt          j        |d          }n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  ).Nr   )ndimr   r  r  r  )r   imrgbrM  s       r6   _unpackzPdfFile._unpack  s     "X7a<<t8OQQQ2A2X,C(3c***Cx{a111aaa7I.6%3,'' 7 EEHU#666EE:r8   c                 $   t                      }|                    |d           |                    d           d}dx}}	 t          j        d|                    d                    \  }}|dv rh|                    |          }t          |          |k    rt          d	          |d
k    rt          |d                   }n2|dk    r|}n)|dk    r||z  }n|dk    rn-|                    |d           |                    dd           |||fS )zn
        Write the image *img* into the pdf file using png
        predictors with Flate compression.
        rw  )rv  r  r8   NTs   !L4s)   IHDR   PLTE   IDATztruncated datar  r  r  s   IENDr$   r  )	r   saveseekstructunpackreadr+   RuntimeErrorra   )	r   imgbufferpng_data	bit_depthpaletter5   r   r  s	            r6   	_writePngzPdfFile._writePng  s(   
 &&&A""	G	!=&++a..AALFD222{{6**t99&&&'78887?? #DGIIW__"GGW__$HFA&&&KK1!	" G++r8   c           	         |j         \  }}}t          d          t          d          ||t          ddd|                   dd}|r||d<   t          j        d	         rn|j         d
         dk    r|                    d
          }d||d}t          j        |          }	|	                    d          }
|dk    r|
t          |
          }t          j
        d |
D             t          j                  }|ddd                             t          j                  dz  |ddd                             t          j                  dz  z  |ddd         z  }|dddddf                             t          j                  dz  |dddddf                             t          j                  dz  z  |dddddf         z  }t          j        |                              t          j                  }|t          j        |||                   }t          j        |d          }	|	                    |           |                     |	          \  }}}||t%          d          |d|dz           }t          d          t          d          |dz
  |g|d<   ||d<   d|d<   ||d<   n|                     |	          \  }}}n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   rX  r	  r$   r   r  )r   r   WidthHeightr  r  rV  rn  r  r$   r  
   )	PredictorColorsColumnsr  )	maxcolorsr   Nc                 "    g | ]\  }}|D ]}|S rA   rA   )rC   _colorcomps       r6   r   z%PdfFile._writeImg.<locals>.<listcomp>  s*    #V#V#VXQPU#V#VD#V#V#V#Vr8   r  r      r  )sorterP)modezinvalid PNG headerIndexedr  r  r  zlength of image stream)rw  )r  rT   re   rs  squeezer   	fromarray	getcolorsr+   r   r  uint8r  uint32argsortsearchsorted
putpaletter  r  r  r  r  r   r  r  )r   r  r   r]  r   r   color_channelsr   rw  r  
img_colors
num_colorsr  	palette24rgb24indicesrgb8r  r  r  s                       r6   	_writeImgzPdfFile._writeImg  s    )-
%~Iw--!l{"C"CN"STT#$& &  	! CL<)* "	z"~""|||,, "nOOC/$''C55J""z'= !__
(#V#V#V#V#V)+3 3 3%addm2229==C%addm2229==BD$QTT]+	 qqq!!!Qw-..ry99R?qqq!!!Qw-..ry99Q>@aaaAg' *Y//66rx@@ry%PPPQod555w'''/3~~c/B/B,)W$&';<<<!/:>/2%))__d;6G6G%/!^W%>L!*3&' !H*3&''!%!4!4!QQC788	 	 	 	 	  	5$$X....$$T\\^^444r8   c                    | j                                         D ]o\  }}}|                     |          \  }}|1|                     d          }|                     ||j                   nd }|                     ||j        |           pd S )Nr]  )r  r<  r  r  r  r   )r   r  rU   r3  r  adatasmaskObjects          r6   r=  zPdfFile.writeImages  s    !\0022 	5 	5MCr,,s++KD% "0099ukn5555"NN44444	5 	5r8   c                    |                      ||d          }t          |          t          |          t          |          ||f}	| j                            |	          }
|
rt          dt          | j                  z            }|                     dt          | j                  z            }|                    |          }||||g| j        |	<   n|
d         |k     r||
d<   |
d         }|S )z<Return name of a marker XObject representing the given path.Frt  NzM%dz	marker %dr  r   )	rv  r   r   r  rb  rT   r+   r  get_extents)r   rE  rF  r>  r=  lw	joinstylecapstylepathopskeyr2   rU   r3  r  s                 r6   markerObjectzPdfFile.markerObject  s     %%dEE%BBW~~tDzz4<<HM!!#&&>DL 1 1122D##K#dl2C2C$CDDB##E**D!%r4 4DLbzBr
!9Dr8   c           
      ~   | j                                         D ]!\  \  }}}}}\  }}}}	|                    |	dz            }|                     |j        d t          d          t          d          t          |j                  d           |                     t          j
        |         t          j                   |                     t          j        |         t          j                    | j        |  |                     t                              ||                     |                                  #d S )N   r  r  r  )r  rg   paddedr  r   rT   r   extentsr  r  r  r%  rV  	capstylesrW  rA  r  )
r   r  r>  r=  r  r  rU   r3  r  r  s
             r6   r>  zPdfFile.writeMarkers   s+   &*l&8&8&:&:	 	 #9gtVY!dBb ;;rAv&&DtiT&\\dl++- -. . . KK*5i@( ( (KK*4X>NNNDK!!KKdF33444NN'	 	r8   c                 0   t          dt          | j                  z            }|                     dt          | j                  z            }| j                            |||||                                |                                |||f	           |S )NzP%dzpath %d)rT   r+   r  r  r,   get_joinstyleget_capstyle)	r   r   rE  rF  rH  rI  rJ  rU   r3  s	            r6   pathCollectionObjectzPdfFile.pathCollectionObject6  s    EC
OO+,,	C
OO ;<<
4B$4$4$6$68I8Ifg'	( 	( 	( r8   c           
      
   | j         D ]y\	  }}}}}}}}}	|                     ||d          }
|                    |          }t          j        t          j        |j                            sg d}n)|                    |          }t          |j                  }| 	                    |j
        d t          d          t          d          |d           |                     t          j        |         t          j                   |                     t          j        |         t          j                    | j        |
  |                     t                              ||	                     |                                  {d S )NFrt  r   r   r   r   r  r  r  )r  rv  r  r   r  r   r  r  r   r  r   rT   r  r  r  r%  rV  r  rW  rA  r  )r   rU   rE  rF  r3  r  r  rH  rI  rJ  r  r  r  s                r6   r?  z$PdfFile.writePathCollectionTemplates>  so   	 	 T4Ix&))$)FFG##E**D6"+dl3344 -&,,{{7++t|,,tiT&\\ " "# # # KK*5i@( ( (KK*4X>NNNDK!!KKfg66777NN%	 	r8   c                     t          t          j        | ||||dt          j        j        t          j        j        dt          j        j        t          j        j        gd                    gS )Nr%  r8   T)	r  r#   r  r%  rJ  r:  rI  rG  rC  )rE  r  ra  ru  sketchs        r6   rv  zPdfFile.pathOperationsS  s\    0)T8VY_biosBJ4D\!     	r8   Fc                     |rdd| j         dz  | j        dz  f}|j        }nd }d}|                     |||||          } | j        |  d S )Nr  r  F)ru  r  )r   r   should_simplifyrv  r  )r   rE  r  ra  r  ru  cmdss          r6   	writePathzPdfFile.writePath\  ss     	dj2ot{R/?@D+HHDH""4D8*0 # 2 2Tr8   r  c                     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   )rc  r  r  r,   r   )r   rU   r   s      r6   r  zPdfFile.reserveObjectg  s<     $"##tQo...}}r8   c                 d    | j                                         | j        z
  | j        |         d<   d S Nr   )ro  rv  r  r  r   s     r6   rr  zPdfFile.recordXrefr  s*     $ ?r1r8   c                 f    |                      |j                   |                    ||            d S r@   )rr  r   r   )r   objectr   s      r6   r}  zPdfFile.writeObjectu  s0    	"""Xt$$$$$r8   c                 \   | j                                         | j        z
  | _        |                     dt          | j                  z             t          | j                  D ]F\  }\  }}}|t          d||fz            |dk    rdnd}d|||fz  }|                     |           Gd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 
)	ro  rv  r  	startxrefr   r+   r  r*   AssertionError)r   r3   offset
generationrU   r  r  s          r6   rA  zPdfFile.writeXrefy  s    $.8

?S%8%88999-6t~-F-F 	! 	!)A)
D~$2aY>@ @ @ #&777ddT*fj#-FF

4    	! 	!r8   c                 z    |                      d          | _        |                     | j        | j                   dS )z8Write out the info dictionary, checking it for good formro   N)r  
infoObjectr}  r  r   s    r6   r@  zPdfFile.writeInfoDict  s9     ,,V44$-88888r8   c                     |                      d           |                      t          t          | j                  | j        | j        d                     |                      d| j        z             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   s    r6   rB  zPdfFile.writeTrailer  s{     	

<   

7((__& &' ' 	( 	( 	(
 	

04>ABBBBBr8   r@   r  )NNNFN)r  )4r   r   r  r  r   r  r  r/  rK  rM  r   r  r  r  rW  r6  rk  r~  r7  r  r  r  r  r'  r  rO  r_  r8  r9  rj  r:  r  r;  r  r  r  r  r=  r  r>  r  r?  staticmethodrv  r  r  rr  r}  rA  r@  rB  __classcell__r  s   @r6   r  r    sC       g9 g9 g9 g9 g9 g9R" " ": .@-?-? - - - -* * *   B	 	 	+ + +  ? ? ? ?& & &
 04     
8 8 8  >  <1 1 1*
 
 
8 8 8t= = =~  *{@ {@ {@z	  2 2 2h
 
 
    $$6 $6 $6L  .*: *: *:X
 
 
  ., , ,:= = = =~5 5 5  :  ,    *    \	 	 	 		 	 	 	@ @ @% % %! ! !9 9 9	C 	C 	C 	C 	C 	C 	Cr8   r  c                        e Zd Z ej        d          ZdZ fdZd ZddZ	d Z
ddZdd	Zd
 Z	 ddZd ZddZd ZdddZd ZddZd Zd Z xZS )r`  zfonts/pdfcorefontsrZ  c                     t                                          ||           || _        |                                 | _        || _        d S r@   )r  r   r   new_gcr   	image_dpi)r   r   r	  r   r   r  s        r6   r   zRendererPdf.__init__  s>    '''	++--"r8   c                 R     | j         j        | j                                          d S r@   )r   r  r   rK  r   s    r6   rK  zRendererPdf.finalize  s(    	$'**,,----r8   Nc                    t          |dd          }||_        t          |dd          }|                                |                    dd           |j        r|j        |j        f|_        nD|t          |          dk     r|j        d	         d
f|_        n|j        d	         |d	         f|_        | j	        
                    |          }|r | j        j        |  ||_        ||_        d S )N
_fillcolorr  r  r  _effective_alphasr  r  r  T)isRGBAr  r   r  )getattrr  get_rgbset_foreground_forced_alpha_alphar  r+   _rgbr   deltar   r  )r   r   	fillcolor	orig_fillorig_alphasr  s         r6   check_gczRendererPdf.check_gc  s    Bl;;	!b"5zBB::<< l4888 	>$&Iry#9B  #i..1"4"4$&GAJ#4B  $&GAJ	!#=B b!! 	%DIe$$ "*r8   c                     | j         dz  S )Nrl  )r	  r   s    r6   get_image_magnificationz#RendererPdf.get_image_magnification  s    ~d""r8   c                    |j         d d         \  }}|dk    s|dk    rd S ||                    d           |                     |           d|z  | j        z  }d|z  | j        z  }| j                            |          }|N| 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  rl  r$   )r  	set_alphar  r	  r   r  r  r%  rY  rK  rL  rZ  frozen	to_values)r   r   rK   r   r  r  hr5  imobtr1tr2tr3tr4tr5tr6s                  r6   
draw_imagezRendererPdf.draw_image  sd    x|166Q!VVFLLb1Ht~%1Ht~%y$$R((IRX1aAr/?!2>2;@ @ @ @ @ ,5+;+;+=+=+G+G+I+I(Cc3SIRX1aAr/? #sCc2;K!2>2;@ @ @ @ @r8   c                 "   |                      ||           | j                            |||d u o|                                d u |                                           | j                            | j                                                   d S r@   )r  r   r  get_hatch_pathget_sketch_paramsr  r   paint)r   r   rE  r  rgbFaces        r6   	draw_pathzRendererPdf.draw_path  s    b'"""	)tO; 1 1 3 3t ;  ""	$ 	$ 	$ 		)))))r8   c                 `   d}t          j        |          }t          j        |          }t          |          sd}|                                 }n7t          j        |d d df         |d         k              r|d         dk    }nd}t          |          sd}ndt          j        t          j        |	          dk              rd}n7t          j        |d d df         |d         k              r|d         dk    }nd}t          |          dk    rt          |d         j                  nd}|                     |||||          }||z   dz   ||z  k     }|r|s!t          j        | |||||||||	|
|||          S t          j	        |	          }g }t          |                     |||                    D ]<\  }\  }}| j                            ||||||          }|                    |           =| j        j        } || j                                          d\  }}|                     |||||||	|
|||          D ]S\  }}}} }!|                     | |!           ||z
  ||z
  }#}" |d	ddd	|"|#t(          j        |t(          j        	  	         ||}}T || j                                          d S )
NTFr   )r   r   r  r   r  rA  r$   )r   asarrayr+   	get_hatchr  r   _iter_collection_uses_per_pathr   draw_path_collectionr   r*   _iter_collection_raw_pathsr   r  r,   r  r   push_iter_collectionr  r%  rK  rL  pop)$r   r   master_transformr  all_transformsoffsetsoffset_trans
facecolors
edgecolors
linewidths
linestylesantialiasedsurlsoffset_positioncan_do_optimizationrI  rJ  len_pathuses_per_pathshould_do_optimizationrH  
path_codesr3   rE  r  rU   r  lastxlastyxoyopath_idgc0r/  dxdys$                                       r6   r5  z RendererPdf.draw_path_collection  s2    #Z
++
Z
++
: 	,F&(llnn"4vjA&*T*::;; ,#D)S0&+#: 	,GGvbj,,344 ,
111a4(Jt,<<== ,$T*c1&+# .1ZZ!^^3uQx()));;>7J
D D }$q(8m+CC 	 $ 	!-C 	!4b*E>z:Jd	! ! ! &$$
$-d.M.M %/9 /9 %: %: 	$ 	$ A i911D)Wfg? ?Dd####!u-1-B-BJJ
JdO.5 .5 		" 		")BGS'
 MM#w'''%ZeBF1aAr2r'7># # #r5EEr8   c                    t          |          }t          |          }||z  ||z   dz   k     rt          j        | ||||||           d S |                     ||           |                    |          }	|                                }
| j        j        }| j                            |||	|
| j	        j
        |                                |                                          } |t          j                   d\  }}|                    |dd| j        j        dz  | j        j        dz  fd          D ]\  }}t          |          r||dd          \  }}d|cxk    r| j        j        dz  k    rn nd|cxk    r| j        j        dz  k    sn [||z
  ||z
  }} |dddd||t          j        |t          j        	  	         ||}} |t          j                   d S )	Nr  rA  r   r  F)ra  ru  r  r$   )r+   r   draw_markersr  r>  r=  r   r  r  r   
_linewidthr  r  r%  rY  iter_segmentsr   r   rK  rL  rZ  )r   r   marker_pathmarker_transrE  rF  r/  len_marker_pathusesr>  r=  r  markerrJ  rK  r   coderK   r   rP  rQ  s                        r6   rS  zRendererPdf.draw_markers1  s   
 k**4yyT!Od$:Q$>>>%dB\&*E7< < <Fb'"""www!''tVTW5G 1 13 3 	rxu"00DIOB.	0@0CD 1     	$ 	$NHd 8}} $}1Q6666$)/B"666666;;;;di&6&;;;;;UAIBq!Q2r2+;r~/ / / !ur{r8   c                    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    sJ |j        d         dk    sJ |j        d         dv sJ |j        }|                    |d         |d         z  df          }|                    |          }|                    |          }| j                            ||          \  }}| j        j        }	|j        d         dk    rB|                    d           | 	                    |            |	|t          j                   d S |d         }
t          j        |
|d d d d df                   rB|                    |
           | 	                    |            |	|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  r  r  r%  rb  r   allcloser_  rY  rX  rZ  )r   r   r~  r  rF  r  tpointsrU   r  r  rM  smask_obgstates                r6   draw_gouraud_trianglesz"RendererPdf.draw_gouraud_trianglesW  ss   6{{c&kk))))v;;!F{a|A!####|A!####{a|A!####|A&((((qE!H!4a 899//&))//%(()//@@a!<?aLLMM"F4$$$Fw;ufQQQ1Wo.. 	 LLMM"F4$$$$$ 111aaa7OAAAqqq$J/E)77GGKAxY//99FF28VR\;         r8   r   c           	         ||cxk    rdk    r1n n.| j                             ||z
  ||z
  t          j                   d S t	          j        |          }| j                             t	          j        |          t	          j        |          t	          j        |           t	          j        |          ||t          j                   | j                             ddt          j                   d S r  )	r   r  r%  r[  r   r   r   r   r]  )r   rK   r   r   oldxoldyoldangles          r6   _setup_textposzRendererPdf._setup_textpos  s    H!!!!!!!!!IQXq4x<<<<<L''EITXe__dhuoo"huoo-tx2=2 2 2 IQ2:.....r8   c                    | j         j                            |d|          \  }}}	}
}|                                =| j        j        d         d                             t          ||||||                     t          j	        d         }t          j        |          }| j                            t          j                   | j                            t          j        |          t          j        |          t          j        |           t          j        |          ||t          j                   |                     ||j                   d}d\  }}g }| j                            t          j                   |
D ]\  }}}}}| j        j                            ||           |j        }t1          ||          s|                    |||||f           [|                     ||d||           ||}}||f|k    rB| j                            | j                            |          |t          j                   ||f}| j                            |                     t;          |          |          t          j                   
| j                            t          j                   |D ]4\  }}}}}|                      |||!                    |          ||           5|D ]P\  }}}}| j                            t          j        ||||t          j"        t          j#        t          j$                   Q| j                            t          j$                   d S )Nr  r  r$   r  r  rA  r   )%
_text2pathmathtext_parserparser   r   r  r,   r   re   rs  r   r   r  r%  rY  r   r   rK  r  r  rE  r  track_glyphri  r   rf  rk  r\  encode_stringr  r^  rF  _draw_xobject_glyphr  rH  r>  rZ  )r   r   rK   r   r4   r  r   r   r   descentglyphsrectsr   r   	prev_fontrc  rd  unsupported_charsr  fontsizenumoxoyr  s                           r6   draw_mathtextzRendererPdf.draw_mathtext  sN    O+11!R>> 	.vw ::<<#I"2&q)001EAq%20 20 1 1 1 </ L	"""	!dhqkk(1++tx{{Ar/	1 	1 	1 	b"'"""	
d	'''+1 	* 	*'D(CRI(44T3???zH'#66 * "(($"b#)FGGGG##BAtT:::dh'944I$$TY%7%7%A%A8%']4 4 4 (( 2I	  !3!3CHHh!G!G!#* * * *	%%%+< 	B 	B'D(BC$$h 3 3C 8 8"bB B B B &+ 	A 	A!BE6IRXr2uf\27BKA A A A 		%%%%%r8   )mtextc          
      	   |                                  }|                                }	|                    ||	          }
t          j        |
d          5 }|\  }d d d            n# 1 swxY w Y   |                                G| j        j        d         d                             t          ||||j
        |j        |                     d g }}|j        D ]U\  }}}}}||k    r*| j                            |          }|d||j        ggz  }|}|d||t          |g          g||z   ggz  }Vd\  }}}	|t!          |          dz
  k     r|||dz            \  }}|d         dk    r	|d         }	n|d         |d         cxk    rdk    rn n|d         |d         k    r|d	         |d         z
  }t#          |          d
k     rB|d         dxx         |d         d         z  cc<   |d	xx         |d	         |d         z
  z  cc<   n/|dxx         |dz  |	z  |d         d         gz  cc<   |d	         |d	<   ||dz   = |dz  }|t!          |          dz
  k     t%                                          |                              ||          }|                     ||j                   | j                            t0          j                   d\  }}}}|D ]	}|d         dk    r3| j                            |d         |d         t0          j                   B|d         dk    r|                    |d         |d         f          \  }}|                     |||||           ||}}t!          |d                   dk    r2| j                            |d         d         t0          j                   | j                            |d         t0          j                   	J | j                            t0          j                   |                                  }|!                    |           |"                    d           tF          j$        tF          j%        tF          j%        tF          j%        tF          j&        g}|j'        D ]O\  }}} }!tG          ||g||!z   |g||!z   || z   g||| z   gddgg|          }"| (                    ||"||j                   Pd S )Nr  r  r$   r  r  )r   r   Nr  r   r  g?r   g     @@r  ))get_texmanagerget_size_in_pointsmake_dvir   Dvir   r   r  r,   r   r   r   r  r~  sizer   r+   absr   
rotate_degr   r  r  r  r%  rE  r\  r  rf  r^  r_  rF  r  copy_propertiesset_linewidthr!   MOVETOLINETO	CLOSEPOLYboxesr0  )#r   r   rK   r   r4   r  r   rx  
texmanagerrs  dvifiledvir  oldfontseqx1y1rm  r   r   rn  r3   curxeltnxtr  mytranscuryrc  rd  boxgcr  r"  r5  rE  s#                                      r6   draw_texzRendererPdf.draw_tex  s5   ((**
**,,%%a22["%% 	ED	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ::<<#I"2&q)001EAq$*dk52: 2: ; ; ; R-1Y 	B 	B)BGUE'!!)//88',788!VReUGnn%5r%x@AACC
 '4#c((1*nn1QqS5zHC1vq6Q3q6++++V+++++A#a&0@0@Q#a&v;;$$F2JJJ#a&)+JJJFFFc!fSVm+FFFFFFFvf}X5s1vayAAFFF VCF!HFA #c((1*nn" **''..88A>> 	b"'"""	'''!+dD$ 	 	C1v	  QQ????Q6!!$..AA/?@@
d##D$tTBBB!4ds1v;;!##I$$SVAY8888I$$SVR[9999	%%% b!!!A;T[$+># J 	: 	:LBAq"bBqD":1bd|b"Q$ZQ!")+ +DNN5$9999	: 	:s   A%%A),A)c                 b    |dv r|                     dd          S |                     dd          S )Nr  r  rc   r!  )r   )r   r4   r   s      r6   rl  zRendererPdf.encode_string	  s5    v88Hi000xx
I...r8   Fc	           
      	                          ||j                   |r                     ||||||          S |                                t          j        d         r                     |          }	dnG                     |          }	 j        j	        
                    |	|           t          j        d         |                                o|	                    |           |	                                \  }
} j        j        d         d                             t!          ||||
dz  |dz  |                     dvr j                            t$          j         j                            |          t$          j                                        |||            j                                                 |          t$          j        t$          j                   d S g }g }d}|	}t5          j        ||	t8                    D ]}t;          t=          |j                            r|s|j         |k    r)|                    |j         |j!        g f           |j         }|j"        r&|d         d	                             |j"                   |d         d	                             |j                   d
}|                    |j         |j!        |j#        f           d}ډ j                            t$          j$                   tK          j&        |          } j                            tK          j'        |          tK          j(        |          tK          j(        |           tK          j'        |          ||t$          j)                    j                            t$          j                   d}|D ]\  }}} j                            |j*                  } j                            |t$          j                                        |dd|dd            j                             fdtW          j,        |tZ                    D             t$          j.                   |} j                            t$          j                   |D ]\  }}} /                    |||d             j                            t$          j0                   d S )NrZ  r$   r  r  r  )r   r   T)	kern_moder  Fr   c                     g | ]N\  }}|t           k    rd t          |          z  z  n(                    d                    |                    OS )ir  )r   rc  rl  r-   )rC   tpgrouprs  r   r   s      r6   r   z)RendererPdf.draw_text.<locals>.<listcomp>k	  sk     O O O"U 8:U{{UT%[[(833,,RWWU^^XFFO O Or8   )1r  r  rw  r{  re   rs  _get_font_afm_get_font_ttfr   r  trackr   set_textget_width_heightr  r,   r   r  r%  rE  rk  r\  rf  rl  r^  rF  r
   layoutr   r   r  char	ft_objectrK   	prev_kern	glyph_idxrY  r   r   r   r   rK  ri  r   groupbyr   r_  rm  rZ  )r   r   rK   r   r4   r  r   ismathrx  r  r   r   singlebyte_chunksmultibyte_glyphsprev_was_multibyterq  itemr   prev_start_xr  start_xkerns_or_charsft_namer  rs  r   s   `                       @@r6   	draw_textzRendererPdf.draw_text	  s   
 	b"'""" 	@%%b!Q4???**,,<,- 	4%%d++DHH%%d++DI(..tQ777|N3H::<<#MM! 1133ME6I"2&q)001EAq%"*frk52: 2: ; ; ;
 7""IR]!Y//55xP P P1e,,,IT//8<<Wbk3 3 3 3 3$ !#!!%I%,Q@PQQQ . .'#di..AA 
.) 3T^y-H-H)00$.$&"1MNNN$(N	~ H)"-a077GGG%b)!,33DI>>>).&&$++T^TVT^,TUUU)-&& IRX&&&U##AITXa[[$(1++"hqkk\48A;;2#35 5 5
 IR]+++L6G ' '2	7N),,Y_==	  (BMBBB##GQ<AFFF	  O O O O O O&/&7&M&MO O O K! ! !  'IR[)))1A  -	7I((xGQ    IR[)))))r8   c                 .   |                     |          }| j                            |j        |          }| j                            t
          j        d|z  ddd|z  ||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  ri  r  r%  rY  rK  rT   rL  rZ  )r   r  rs  r  rK   r   r  rU   s           r6   rm  zRendererPdf._draw_xobject_glyphx	  s    ((33
y00ZHH	HHaEH$4aB<LJJK		
 	
 	
 	
 	
r8   c                 *    t          | j                  S r@   )r  r   r   s    r6   r  zRendererPdf.new_gc	  s    !$),,,r8   r@   r   r  )r   r   r  r   _get_data_pathra  _use_afm_rc_namer   rK  r  r  r*  r0  r5  rS  ra  rf  rw  r  rl  r  rm  r  r  r  s   @r6   r`  r`    sz       (E()=>>M+# # # # #. . .+ + + +6# # #@ @ @ @<* * * *D D DN "$ $ $ $L&  &  & P/ / / /4& 4& 4&l ;? Q: Q: Q: Q: Q:f/ / /
_* _* _* _*B	
 	
 	
- - - - - - -r8   r`  c            
            e Zd Z fdZd Zd Zd Zd Zdddd	Zddd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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 Z fd Zd! Z xZS )"r  c                     t                                                       d| _        d| _        || _        d | _        d S )Nr  r  )r  r   r  r  r   parent)r   r   r  s     r6   r   zGraphicsContextPdf.__init__	  s:    )!+	r8   c                 T    t          | j                  }|d= |d= t          |          S )Nr   r  )r   r  repr)r   rz   s     r6   r   zGraphicsContextPdf.__repr__	  s*    fIhKAwwr8   c                     | j         dk    o3| 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  )rT  r  r+   r  r   s    r6   r=  zGraphicsContextPdf.stroke	  sE     !# =a =TY1$;	!(;	>r8   c                     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+   r  _hatch)r   argsr  s      r6   r>  zGraphicsContextPdf.fill	  s_     t99 	)aJJJ A4' @j//Q&>*Q-3*>	Br8   c                     t                               |                                 |                                           S )zo
        Return the appropriate pdf operator to cause the path to be
        stroked, filled, or both.
        )r%  rA  r>  r=  r   s    r6   r.  zGraphicsContextPdf.paint	  s(    
 }}TYY[[$++--888r8   r   r$   r  )buttr
  
projecting)miterr
  bevelc                 4    | j         |         t          j        gS r@   )r  r%  rW  r   styles     r6   capstyle_cmdzGraphicsContextPdf.capstyle_cmd	  s    u%r}55r8   c                 4    | j         |         t          j        gS r@   )r  r%  rV  r  s     r6   joinstyle_cmdz GraphicsContextPdf.joinstyle_cmd	  s    &77r8   c                     |t           j        gS r@   )r%  r`  )r   r   s     r6   linewidth_cmdz GraphicsContextPdf.linewidth_cmd	  s    r''r8   c                 P    |\  }}|g }d}t          |          |t          j        gS r  )r   r%  rU  )r   dashesr  dashs       r6   dash_cmdzGraphicsContextPdf.dash_cmd	  s/    <DFT

FBJ//r8   c                 R    | j                             |          }|t          j        gS r@   )r   rO  r%  rX  )r   rM  forcedeffective_alphasrU   s        r6   	alpha_cmdzGraphicsContextPdf.alpha_cmd	  s%    y##$455bl##r8   c                    |s<| j         |                     | j                   S t          d          t          j        gS || j         |f}| j                            |          }t          d          t          j        |t          j        gS )Nr	  r  )r  fillcolor_cmdrT   r%  rR  r   rj  rT  )r   rh  hatch_colorre  rU   s        r6   	hatch_cmdzGraphicsContextPdf.hatch_cmd	  s     		1*))$/:::[))2+EFF&?K9))+66DOOR%?"/1 1r8   c                     t           j        d         rg S |d         |d         cxk    r|d         k    rn n|d         t          j        gS g |d d         t          j        S Nzpdf.inheritcolorr   r$   r  r   )re   rs  r%  rM  rO  r   r  s     r6   rgb_cmdzGraphicsContextPdf.rgb_cmd	  sr    <*+ 	Iq6SV%%%%s1v%%%%%FB-../S!W/b.//r8   c                     |t           j        d         rg S |d         |d         cxk    r|d         k    rn n|d         t          j        gS g |d d         t          j        S r  )re   rs  r%  rN  rP  r  s     r6   r  z GraphicsContextPdf.fillcolor_cmd	  ss    ;#,'9:;IVs1v''''Q'''''FB0112S!W2b122r8   c                     t          | j                  }|                    |            | j        |_        || _        t          j        gS r@   )r  r   r  r  r%  rY  )r   r  s     r6   r7  zGraphicsContextPdf.push	  s?    #DI..t$$$zr8   c                     | j         J |                     | j                    | j         j         | _         t          j        gS r@   )r  r  r%  rZ  r   s    r6   r9  zGraphicsContextPdf.pop	  s<    {&&&T[)))k(}r8   c                    g }| j         | j        f||fk    rI| j        B|                    |                                            | j         | j        f||fk    r| j        B| j         | j        f||fk    s| j        |                    |                                            | j         |k    r7|                    |t          j        t          j        t          j	        g           | j        |k    r`|
                                \  }}|                    t                              ||d          t          j        t          j	        gz              |S )z1Set clip rectangle. Calls `.pop()` and `.push()`.NFrt  )	_cliprect	_clippathr  r  r9  r7  r%  rH  ra  r?  get_transformed_path_and_affiner  rv  )r   cliprectclippathr  rE  affines         r6   clip_cmdzGraphicsContextPdf.clip_cmd	  s8   /Hh3GGGK+KK

### /Hh3GGGK+ ^T^,80DDD#KK		$$$~))Xr|RWbjIJJJ~))'GGIIf**4%*HHWbj)*+ + + r8   )r  r  )r  r  r  )	_capstyler  )
_joinstyle)rT  )_dashes)r  r  _hatch_colorc           
      D   g }d}| j         D ]\  }}d}|D ]}t          | |          }t          |          }		 ||	||	u}nt          ||	k              }n`# t          $ rS t	          j        |          }t	          j        |	          }	|j        |	j        k    pt	          j        ||	k              }Y nw xY w|r n|dk    r|rd}|rV|dk    rd}fd|D             }	|                     || g|	R             |D ]!}t          | |t          |                     "|S )z}
        Copy properties of other into self and return PDF commands
        needed to transform *self* into *other*.
        FNr  Tr  c                 0    g | ]}t          |          S rA   )r  )rC   pr  s     r6   r   z,GraphicsContextPdf.delta.<locals>.<listcomp>:
  s#    <<<'%++<<<r8   )
commandsr  r   r   r   r2  r  anyr  setattr)
r   r  r  fill_performedparamscmd	differentr  ourstheirss
    `        r6   r  zGraphicsContextPdf.delta
  s   
 = 	8 	8KFCI  tQ'' **	9|v~$($6		$($8$8	! 9 9 9:d++DZ//F!%v|!; "8!#!7!7 II9
  E 3333 	 8_,,%)N<<<<V<<<CC.v.../// 8 8AD!WUA%6%67777s   AAB43B4c                     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  s       r6   r  z"GraphicsContextPdf.copy_properties@
  s`     	&&&E<AA	"5*=#'#9; ;#!1r8   c                 t    g }| j         .|                    |                                            | j         .|S )zB
        Make sure every pushed graphics state is popped.
        )r  r  r9  )r   r  s     r6   rK  zGraphicsContextPdf.finalizeK
  s:     k%KK

### k%r8   )r   r   r  r   r   r=  r>  r.  r  r  r  r  r  r  r  r  r  r  r7  r9  r  r  r  r  rK  r  r  s   @r6   r  r  	  s             	> 	> 	>B B B9 9 9 Qa88Iq155J6 6 68 8 8( ( (0 0 0$ $ $
1 
1 
10 0 03 3 3      , 
$X.	99E	&	-(	-(	-(	x 	G	#Y/
H$ $ $L	2 	2 	2 	2 	2      r8   r  c                       e Zd ZdZ e            ZedfdZ ej        d          Z	d Z
d Zd Zd Zd	 Zdd
Zd Zg df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.
    Nc                     || _         || _        d| _        |r|| j        urt	          j        d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).

        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`.
        N3.8^Keeping empty pdf files is deprecated since %(since)s and support will be removed %(removal)s.message)	_filename	_metadata_file_UNSETr	   warn_deprecated_keep_empty)r   r  
keep_emptyrl   s       r6   r   zPdfPages.__init__l
  s^    2 "!
 	1*DK77 /1 1 1 1 &r8   r  c                     | S r@   rA   r   s    r6   	__enter__zPdfPages.__enter__
  s    r8   c                 .    |                                   d S r@   )rM  )r   exc_typeexc_valexc_tbs       r6   __exit__zPdfPages.__exit__
  s    

r8   c                 ^    | j          t          | j        | j                  | _         | j         S )Nrl   )r  r  r   r  r   s    r6   _ensure_filezPdfPages._ensure_file
  s*    : $.IIIDJzr8   c                 "   | j         ;| j                                          | j                                          d| _         dS | j        rEt	          j        dd           t          | j        | j                                                   dS dS )z_
        Finalize this object, making the underlying file a complete
        PDF file.
        Nr  r  r  r  )	r  rK  rM  r  r	   r  r  r   r  r   s    r6   rM  zPdfPages.close
  s    
 :!J!!!JDJJJ 	E /1 1 1 1 DNT^<<<BBDDDDD		E 	Er8   c                 4    |                                  j        S )z
        Return a modifiable information dictionary object
        (see PDF reference section 10.2.1 'Document Information
        Dictionary').
        )r  r  r   s    r6   infodictzPdfPages.infodict
  s       ""++r8   c                     t          |t                    sJ|t          j                    }nt          j        |          }|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  )rv  rk   )	rH   r   r   
get_activeget_fig_managerr   canvasfiguresavefig)r   r  kwargsmanagers       r6   r  zPdfPages.savefig
  s     &&)) 	+~.**-f55 !6f!6!6777^*FtCE5CCFCCCCCr8   c                 N    t          |                                 j                  S )z=Return the current number of pages in the multipage pdf file.)r+   r  r  r   s    r6   get_pagecountzPdfPages.get_pagecount
  s    4$$&&/000r8   r  c                 V    |                                                      ||           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  s      r6   attach_notezPdfPages.attach_note
  s,     	''l;;;;;r8   r@   )r   r   r  r  r  r  r   r	   deprecate_privatize_attributer  r  r  r  rM  r  r  r  r  rA   r8   r6   r  r  U
  s         ( VXXF,2T  &  &  &  &D 43E::J      
E E E, , ,D D D D,1 1 1 .@-?-? < < < < < <r8   r  c                   >     e Zd ZdZddiZd ZddddZ fdZ xZS )	FigureCanvasPdfr  r  zPortable Document Formatc                     dS )Nr  rA   r   s    r6   get_default_filetypez$FigureCanvasPdf.get_default_filetype
  s    ur8   N)bbox_inches_restorerl   c                   | j         j        }d| j         _        | j                                         \  }}t          |t                    r|                                }nt          ||          }	 |                    ||           t          | j         |||t          ||||          |          }| j         
                    |           |                                 t          |t                    s|                                 t          |t                    r|                                 d S |                                 d S # t          |t                    r|                                 w |                                 w xY w)Nr  r  )r%  )r  dpiget_size_inchesrH   r  r  r  r  r   r`  drawrK  r  rM  )	r   r  r%  rl   r'  r   r   r   renderers	            r6   	print_pdfzFigureCanvasPdf.print_pdf
  sl    ko3355vh)) 	8((**DD8h777D	LL'''(UFCD#vu55$79 9 9H KX&&&h11  (H--      

 (H--     

s   1BE	 	A F	c                 v    | j                                          t                                                      S r@   )r  draw_without_renderingr  r)  )r   r  s    r6   r)  zFigureCanvasPdf.draw
  s)    **,,,ww||~~r8   )	r   r   r  	fixed_dpi	filetypesr$  r+  r)  r  r  s   @r6   r"  r"  
  sy         I23I   '+T    4        r8   r"  c                       e Zd ZeZdS )_BackendPdfN)r   r   r  r"  FigureCanvasrA   r8   r6   r1  r1    s        "LLLr8   r1  )r&   )r   )`r  r   r   r   enumr   	functoolsr   ior   r   loggingr   r^   r  r  r)  rw   rx  r  rt  numpyr   PILr   
matplotlibre   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   r   matplotlib.transformsr   r    matplotlib.pathr!   matplotlib.datesr"   r#   r  r%   	getLoggerr   rd  r7   rq   r}   r   r   r   rI   	maketransr   r   r   r   rT   r  r%  re  r  r  RendererPDFPSBaser`  r  r  r"  FigureManagerPdfexportr1  rA   r8   r6   <module>rI     s                       $ $ $ $ $ $             				   



                   F F F F F F F F F F F F F F ) ) ) ) ) )              @ ? ? ? ? ? $ $ $ $ $ $ I I I I I I I I      L L L L L L L L L L L L L L L L 4 4 4 4 4 4 4 4                                    w""d   ,T T Tn  0, , , ,"* * * *0   4 }}
u5UD D E EF# F# F#R            .                B       A# A# A# A# A# A# A# A#HZ$ Z$ Z$ Z$ Z$ Z$ Z$ Z$z+ + +\@C @C @C @C @C @C @C @CF(m- m- m- m- m-/3 m- m- m-`J J J J J, J J JZ~< ~< ~< ~< ~< ~< ~< ~<B% % % % %& % % %P %  
# # # # #( # # # # #r8   