
    EVf                    N   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j                  eD      ZEd<dZFd ZGd ZHd=dZId=dZJd=dZKeLj                  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.      ZUd/ ZV G d0 d1      ZW G d2 d3eBj                        ZY G d4 d5e&      ZZ G d6 d7      Z[ G d8 d9e$      Z\e%Z]e#j                   G d: d;e#             Z_y)>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_psc                 "   d}d}g }t        |       D ]H  \  }}t        |      }||z   |k  r	||dz   z  }"|j                  dj                  | ||              |}|}J |j                  dj                  | |d              dj                  |      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           h/var/www/html/software/conda/envs/catlas/lib/python3.12/site-packages/matplotlib/backends/backend_pdf.py_fillr6   `   s     GEF'" 1QVg%vz!GMM$))GE!$456EG MM$))GEFO,-::f    c           
         t        j                  d      }|rDt        j                  t	        |      t
        j                        }|j                  t              }nt        j                         }dt        j                   dd|  dt        j                   |d|}|j                         D ci c]  \  }}|	|| }}}d }d	|_        d
 }d|_        d }	d|	_        |||||||||	d	}
|D ]j  }||
vr&t        j                  d|dt!        |
      d       - |
|   ||         r<t        j                  d| d||   d|
|   j                   d       l d|v rt#        |d         |d<   |S c c}}w )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                 "    t        | t              S N)
isinstancestrxs    r5   is_string_likez-_create_pdf_info_dict.<locals>.is_string_like   s    !S!!r7   zan instance of strc                 "    t        | t              S r?   )r@   r   rB   s    r5   is_datez&_create_pdf_info_dict.<locals>.is_date   s    !X&&r7   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r@   NamenamerB   s    r5   check_trappedz,_create_pdf_info_dict.<locals>.check_trapped   s(    a66<<<444r7   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 rT   )osgetenvr   fromtimestampintr   utcreplacer"   todaympl__version__itemstext_for_warningr	   warn_externalsetrL   )backendmetadatasource_date_epochsource_dateinfokvrD   rF   rN   keywordss              r5   _create_pdf_info_dictrk   v   s   @ 		"56,,S1B-CX\\R!)))5nn& "#//!22JK!'*S__4EF# 	D  $zz|=Vaq}AqD=D="&:N#'AG5
 &KM"   !"!" 
H  CH!;A5 A114X0A D E!T!W%!@ D&&*1g["*1+">">!?q B CC DtI/YKO >s   1
E4<E4c                 2   | j                  d      }| j                         }||j                  }n1t        j                  rt        j
                  }nt        j                  }|dk(  r|dz  }|S |dk  r|d| dz  | dz  fz  z  }|S |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%Sr   Zz+%02d'%02d'i  z-%02d'%02d')strftime	utcoffsetsecondstimedaylightaltzoner   )drzs      r5   _datetime_to_pdfrw      s     	


#$A	A}II==AAAv	S
 H	 
Q	]rdlaR4K888 H 	
]a4iT222Hr7   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)rC   ywidthheightangle	sin_angle	cos_angleabcrt   efs                r5   !_calculate_quad_point_coordinatesr      s    
 LL% EII	FYA	FYA	EI 22A	EI 22A	EIA	EIAFQFQFQF++r7   c                 6   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
                  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      ywr   N .0ri   s     r5   	<genexpr>z,_get_coordinates_of_block.<locals>.<genexpr>       '!'   c              3   &   K   | ]	  }|d      ywr$   Nr   r   s     r5   r   z,_get_coordinates_of_block.<locals>.<genexpr>  r   r   c              3   &   K   | ]	  }|d      ywr   r   r   s     r5   r   z,_get_coordinates_of_block.<locals>.<genexpr>  r   r   c              3   &   K   | ]	  }|d      ywr   r   r   s     r5   r   z,_get_coordinates_of_block.<locals>.<genexpr>	  r   r   )r   minmaxtuple	itertoolschainfrom_iterable)rC   r}   r~   r   r   verticespadmin_xmin_ymax_xmax_ys              r5   _get_coordinates_of_blockr      s     1Au17@H RZ'QC'h''#-E'h''#-E'h''#-E'h''#-E)////9:E5%(* *r7   c                     t        |||||      \  }}t        d      t        d      |g dt        d      | j                         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   rL   get_url)	gcrC   r}   r~   r   r   
quadpointsrectlink_annotations	            r5   _get_link_annotationr     sd     1AufeLJW<e::<
	O rz(2%r7   z\\z\(z\)z\nz\r)\()
c                 ,   t        | d      r| j                         S t        | t        t        j
                  f      rEt	        j                  |       st        d      d| z  }|j                  d      j                  d      S t        | t              rddg|    S t        | t        t        j                  f      rd| z  S t        | t              rPt        | j                         r| j                  d	            S t        j                   | j                  d
      z         S t        | t"              r9d| j%                  d      j'                  t(              j                  d      z   dz   S t        | t*              rWt-        dg| j/                         D cg c]-  \  }}t1        |      j                         dz   t        |      z   / c}}d      S t        | t2        t4        f      r't-        dg| D cg c]  }t        |       c}d      S | yt        | t6              rt        t9        |             S t        | t:              r,t-        | j<                  D cg c]  }t        |       c}      S t?        dtA        |        d      c c}}w c c}w c c}w )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   <<r'   s   >>   [   ]s   nullz$Don't know a PDF representation for z objects)!hasattrr   r@   floatnpfloatingisfinite
ValueErrorrstripboolrY   integerrA   isasciiencodecodecsBOM_UTF16_BEbytesdecode	translate_str_escapesdictr6   r_   rL   listr   r   rw   r    bounds	TypeErrortype)objru   rh   ri   vals        r5   r   r   ,  sW    sI{{}
 
C%-	.{{3DEEsNxx~$$T** 
C	'"3'' 
C#rzz*	+s{ 
C	ckkmszz'* J 	J"//#**Z2HHJ 	J 
C	JJy!++L9@@KL	 
C	
@C		L1d1goo$&3L
 
  	 
C$	'dAc:sgcl:ADABB 
 
C	"',-- 
C	"cjj9sgcl9:: >tCyk J" " # 	#+ M ; :s   2J/J
Jc                 >    | 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     r5   _font_supports_glyphr   u  s/     1}|2~~

r7   c                   (    e Zd ZdZd Zd Zd Zd Zy)	ReferencezV
    PDF reference object.

    Use PdfFile.reserveObject() to create References.
    c                     || _         y r?   idselfr   s     r5   __init__zReference.__init__  s	    r7   c                      d| j                   z  S )Nz<Reference %d>r   r   s    r5   __repr__zReference.__repr__  s    $''))r7   c                      d| j                   z  S )Ns   %d 0 Rr   r   s    r5   r   zReference.pdfRepr  s    477""r7   c                 x    |j                   } |d| j                  z          |t        |              |d       y )N	   %d 0 obj
s   
endobj
)writer   r   )r   contentsfiler   s       r5   r   zReference.write  s1    

mdgg%&gh mr7   N)__name__
__module____qualname____doc__r   r   r   r   r   r7   r5   r   r     s    *#r7   r   c                       e Zd ZdZdZh  ed      h  e ed       ed      dz         z
  D  ci c]  }|d|z  
 c}} Zd Zd	 Z	d
 Z
d Zd Zd Zd Zyc c}} w )rL   zPDF name object.rM      !~r$   z#%02xc                     t        |t              r|j                  | _        y t        |t              r|j	                  d      }|j                  | j                        j                  d      | _        y )Nr   )r@   rL   rM   r   r   r   _hexifyr   )r   rM   s     r5   r   zName.__init__  sN    dD!		DI$&{{7+t||4;;GDDIr7   c                      d| j                   z  S )Nz	<Name %s>r   r   s    r5   r   zName.__repr__  s    TYY&&r7   c                 >    d| j                   j                  d      z   S )N/r   )rM   r   r   s    r5   __str__zName.__str__  s    TYY%%g...r7   c                 X    t        |t              xr | j                  |j                  k(  S r?   rK   r   others     r5   __eq__zName.__eq__  s!    %&B499

+BBr7   c                 X    t        |t              xr | j                  |j                  k  S r?   rK   r  s     r5   __lt__zName.__lt__  s!    %&A499uzz+AAr7   c                 ,    t        | j                        S r?   )hashrM   r   s    r5   __hash__zName.__hash__  s    DIIr7   c                      d| j                   z   S )N   /r   r   s    r5   r   zName.pdfRepr  s    diir7   N)r   r   r   r   	__slots__rangeordr   r   r   r  r  r
  r  r   r   r   s   00r5   rL   rL     s~    I%%*(H%C#c(Q,*G(HHJ 'A+~ JGE'/CB 5Js   ArL   c                       e Zd ZdZd Zd Zy)VerbatimzEStore verbatim PDF command content for later inclusion in the stream.c                     || _         y r?   _x)r   rC   s     r5   r   zVerbatim.__init__  s	    r7   c                     | j                   S r?   r  r   s    r5   r   zVerbatim.pdfRepr  s    wwr7   N)r   r   r   r   r   r   r   r7   r5   r  r    s    Or7   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+y))*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    r5   r   z
Op.pdfRepr  s    zzr7   c                 n    |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)clsr4  r3  s      r5   
paint_pathzOp.paint_path  s4     &zz!xx{{"r7   N),r   r   r   r   close_fill_stroker2  r4  	closepathclose_stroker3  r5  
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   classmethodr7  r   r7   r5   r  r    s    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 # #r7   r  c                   4    e Zd ZdZdZd	dZd Zd Zd Zd Z	y)
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                         | _        |'| j                  j                  t        d      |d       | j                  j                  | j                          t        j                  d   r-|s+t        j
                  t        j                  d         | _        | j                  t               | _        y| j!                          | j                  j#                         | _        y)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*   r\  fhr   r]  r   r^  copyupdaterL   
recordXrefr]   rcParamszlibr   _writeHeadertellr_  )r   r   r*   r   r^  pngs         r5   r   zStream.__init__  s      GG	=DJDJ?JJd=.A.13 4 	(<<)*3#//./ 1D88	DIyy~~'DHr7   c                    | j                   j                  } |d| j                  z         | j                  }| j                  |d<   t
        j                  d   rt        d      |d<    |t        |              |d       y )Nr   Lengthrd  ra  rb  s   
stream
)	r   r   r   r^  r*   r]   ri  rL   r   )r   r   r   s      r5   rk  zStream._writeHeader:  se    		mdgg%&zzX<<)*!-0DNgdmmr7   c                 $   | j                          | j                  | j                  j                         }t        |      | _        | j                  j
                  | _        | j                          | j                  j                  |       | j                  j                  d       y| j                  j                         | j                  z
  }| j                  j                  d       | j                  j                  | j                  |       y)zFinalize stream.Ns   
endstream
endobj
)_flushr*   r   getvaluer\  re  rk  r   rl  r_  writeObject)r   r   r4   s      r5   endz
Stream.endE  s     	88yy))+H8}DHDIIIOOH%IIOO45YY^^%0FIIOO45LL$$TXXv6r7   c                     | j                   | j                  j                  |       y| j                   j                  |      }| j                  j                  |       y)zWrite some data on the stream.N)r]  r   r   compress)r   data
compresseds      r5   r   zStream.writeU  sF     #IIOOD!))2248JIIOOJ'r7   c                     | j                   =| j                   j                         }| j                  j                  |       d| _         yy)zFlush the compression object.N)r]  flushr   r   )r   rx  s     r5   rq  zStream._flush^  sA     '))//1JIIOOJ'#D (r7   NN)
r   r   r   r   r  r   rk  rt  r   rq  r   r7   r5   r[  r[  
  s)     PI%(N	7 ($r7   r[  c                 :   t        | d      }d|j                  z  }i }|D ]  }|j                  |t              }t	        j
                  |j                  dg|j                        |z  dz   j                  t              }|j                         \  }}	|dz  j                  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  j                  t              k(  j                  d	         }|j                  |fd
v r|d d dfxx   dz  cc<   ||z  dz   j                  t              }||dz
     ||dz      z   dz  j                  t              ||<   dj                  t!        t"        |            j%                  d      dz   t'        j(                  t+        ||	      d d dd dg dd      z   dz   ||j-                  |      <    |S )Nr$   )hinting_factor  r   g      ?@   r      axis))DejaVuSerif-ItalicM   )r      r   s    d1
F)r%  r$  r7   r#  r  Tr  )r   units_per_EM
load_glyphr   r   arrayhoriAdvancebboxastyperY   get_pathnonzerosortedallpostscript_namer,   maprA   r   r#   convert_to_stringr!   get_glyph_name)	font_path	glyph_idsfontconvprocsglyph_idgd1ri   r   quadsquads_onquads_mid_onimplicits                 r5   _get_pdf_charprocsr  g  s.   Ia0D$###DE &OOHm4 hhq216623d:R?GGL}}1VOOC  AF#A;xx;X;EAI/.UQY.@A3H|_L1$%,*:(;;q@HHMNSaS[   (+ 0
 
 adGqLGX]""3'x!|_qA.!3VVC[ 	
( HHSb\"))'2X=%%Q
D$tR-t55
  	d!!(+,A&N Lr7   c                   R    e Zd ZdZd3 fd	Zd Zg dfdZd Zd Zd	 Z	d
 Z
d Zd4d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#d3d%Z$d& Z%d' Z&d( Z'd) Z(d* Z)e*d5d+       Z+d6d,Z,d7d-Z-d. Z.d/ Z/d0 Z0d1 Z1d2 Z2 xZ3S )8PdfFilezPDF file object.Nc                    t         	|           t        j                  d      | _        g dg| _        d| _        d| _        d| _        t        j                  |dd      \  }}|s	 |j                         | _        |}d| _        || _        d| _        |j!                  d	       |j!                  d
       | j#                  d      | _        | j#                  d      | _        g | _        | j#                  d      | _        | j#                  d      | _        | j#                  d      | _        | j#                  d      | _        | j#                  d      | _        | j#                  d      | _        t7        d      | j&                  d}| j9                  | j$                  |       t;        d|xs i       | _        i | _        d t        j                  d      D        | _         i | _!        i | _"        tG        jH                         | _%        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jk                         D cg c]  }t7        |       }}| j*                  | j2                  | j,                  | j.                  | j0                  |d}| j9                  | j4                  |       y# t        $ r t               }|| _        Y w xY wc c}w )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   8   K   | ]  }t        d |         yw)FNrL   r   r2   s     r5   r   z#PdfFile.__init__.<locals>.<genexpr>       "MQ4!A3="M   c              3   8   K   | ]  }t        d |         yw)r   Nr  r  s     r5   r   z#PdfFile.__init__.<locals>.<genexpr>  s      K1!g Kr  c              3   8   K   | ]  }t        d |         yw)SMNr  r  s     r5   r   z#PdfFile.__init__.<locals>.<genexpr>  s     J!tbH~Jr  c              3   8   K   | ]  }t        d |         yw)HNr  r  s     r5   r   z#PdfFile.__init__.<locals>.<genexpr>  r  r  c              3   8   K   | ]  }t        d |         yw)INr  r  s     r5   r   z#PdfFile.__init__.<locals>.<genexpr>  s     EQ4!A3=Er  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_filehandlerl  OSErrorr   re  currentstreamr   reserveObject
rootObjectpagesObjectpageList
fontObject_extGStateObjecthatchObjectgouraudObjectXObjectObjectresourceObjectrL   rs  rk   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   filenamerd   re  openedr  rC   procsetsr  	__class__s
            r5   r   zPdfFile.__init__  s   " 	$??1-78%*""&((4tL
F2!)
 -1*!
 	(),,V4--g6,,W5 $ 2 23M N--.?@!//0CD!//0BC"00=Y))+$/-eX^D"M)//!:L"M ""1"B"B"D K	8J K!#Jyq7IJ!#"M)//!:L"M "E)//!2DE$&!

   " &E%J%J%LMDGMM
 "__ $ 2 2"&"7"7 $ 0 0 $ 2 2 (*	 	,,i8W  3Y*2'3@ Ns   'M 'M4M10M1c                    | j                          ||c| _        | _        | j                  d      }| j                  d      }t	        d      | j
                  | j                  ddd|z  d|z  g||d}| j                  d      }| j                  ||       | j                  j                  |       | j                  j                  || j                  f       | j                  |j                  | j                  d             | j                  t	        d	      t        j                          | j                  t	        d	      t        j"                         | j                  t$        j&                  d
   t        j(                         g | _        y )Nzpage contentsannotationsPager   H   )r   Parent	ResourcesMediaBoxContentsAnnotspagezlength of content stream	DeviceRGBround)	endStreamr~   r   r  rL   r  r  rs  r  r+   r  r  beginStreamr   outputr  rG  rH  GraphicsContextPdf
joinstylesrL  )r   r~   r   contentObjectannotsObjectthePage
pageObjects          r5   newPagezPdfFile.newPage  sK   "'
DK**?;))-8<!-- $ 3 3 !1b5j"v+>,) ''/
W-Z(  ,0D0D!EF))++,FG	I 	D%r'>'>?D%r'A'AB&11':BNNK  "r7   r
  r   r   c                 l    t        d      t        d      ||d}| j                  j                  |       y )Nr   Text)r   r   r  r   )rL   r  r+   )r   textpositionRecttheNotes       r5   newTextnotezPdfFile.newTextnote  s3    ="6l#'
 	##G,r7   c                     fdt        t        |j                                     t        j                  dz   dz  z  } |d      }|d d dz   |z   S )Nc                 z    | |k  rt         j                  |    S  | |z  |      t         j                  | |z     z   S r?   )stringascii_uppercase)nbasetoStrs     r5   r  z,PdfFile._get_subsetted_psname.<locals>.toStr(  sD    4x--a00 !t)T*V-C-CAH-MMr7   r$   r        +)r  	frozensetkeyssysmaxsize)r   ps_namecharmaphashedprefixr  s        @r5   _get_subsetted_psnamezPdfFile._get_subsetted_psname'  sU    	 i/0S[[1_4IJvr" bqzC'))r7   c           
         | j                          | j                          | j                          | j                          | j	                          | j                          | j                          | j                  j                         D ci c]	  \  }}}|| }}}}| j                  j                         D ]  }|d   ||d   <    | j                  j                         D ]
  \  }}|||<    | j                  D ]  \	  }}}}}	}
}}}|||<    | j                  | j                  |       | j                          | j!                          | j#                          | j                  | j$                  t'        d      | j(                  t+        | j(                        d       | j-                          | j/                          | j1                          yc c}}}w )z>Write out the various deferred objects and the pdf end matter.r$   r   r  )r   KidsCountN)r  _write_annotations
writeFontswriteExtGSTates_write_soft_mask_groupswriteHatcheswriteGouraudTrianglesr  valuesr  r  r_   r  rs  r  writeImageswriteMarkerswritePathCollectionTemplatesr  rL   r  r*   writeInfoDict	writeXrefwriteTrailer)r   imagerM   obxobjectstupr0  pathtransr,   cappaddingfilledstrokeds                 r5   finalizezPdfFile.finalize7  s    	!$$&""$,0LL,?,?,AC C(bD"HC C<<&&( 	&C"1vHSV	&44::< 	#KD%"HTN	# ::	 FD$r4gvwHTN	  	++X6))+))"&w-"&--#&t}}#57	8 	 	+Cs   Gc                 $   | j                          | j                  r| j                  j                          y| j                  3| j                  j                  | j                  j                                | j                  j                          y)z)Flush all buffers and free all resources.N)r  r  re  rz  r  r   rr  closer   s    r5   r@  zPdfFile.closeX  s^     	%%GGMMO&&2''--dgg.>.>.@AGGMMOr7   c                     | j                   | j                  j                  |       y | j                   j                  |       y r?   )r  re  r   )r   rw  s     r5   r   zPdfFile.writec  s2    %GGMM$$$T*r7   c           
          | j                  t        |D cg c]  }t        |       c}             | j                  d       y c c}w )Nr(   )r   r6   r   )r   rw  rC   s      r5   r  zPdfFile.outputi  s3    

5d3'!*345

5 4s   Ac                 H    | j                   J t        ||| ||      | _         y r?   )r  r[  )r   r   r*   r^  rm  s        r5   r   zPdfFile.beginStreamm  s)    !!)))#BT5#>r7   c                 `    | j                   "| j                   j                          d | _         y y r?   )r  rt  r   s    r5   r  zPdfFile.endStreamq  s-    )""$!%D *r7   r^  c                    | j                  |j                  d |       | j                  j                  |       | j	                          y r?   )r   r   r  r   r  )r   refrw  r^  s       r5   outputStreamzPdfFile.outputStreamv  s6    u-  &r7   c                 P    | j                   D ]  \  }}| j                  ||        y r?   )r  rs  )r   r  r  s      r5   r'  zPdfFile._write_annotations{  s,    )-):): 	8%L+\;7	8r7   c                    t        |t              r|g}nOt        j                  d   r't	        j
                  |dt        j                        }nt	        j
                  |      }d}|D ]d  }| j                  j                  |      }|s|}|%t        | j                        }|| j                  |<   t        j                  d||       |rc|}f |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)r@   rA   r]   ri  _fontManager_find_fonts_by_propsRendererPdf_afm_font_dirr  getnextr  _logdebug)r   fontprop	filenamesfirst_FxfnameFxs         r5   fontNamezPdfFile.fontName  s     h$!
I\\./$99%;3L3LI %99(CI 		"E##E*Bz$112(*u%

3R?!H		" r7   c                 p   | j                   j                  |j                        }||j                  S t	        j
                  t	        j                  d            }||j                     }|j                  /t        dj                  |j                  |j                              t        | j                        }t        j                  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.
        z
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  rS  texnamer_  r   
PsfontsMapfind_tex_filer  r   formatpsnamerT  r  rU  rV  typesSimpleNamespaceencodingrc  )r   r^  dvi_infotex_font_mappsfontr_  s         r5   dviFontNamezPdfFile.dviFontName  s     ##''8###))'*?*?*MNgoo.??"5w79 9
 t../

17GOOL,1,A,A__]]NN-$) r7   c                    i }t        | j                  j                               D ];  \  }}|j                  }t        j                  d|       | j                  |      ||<   = t        | j                        D ]  }| j                  |   }t        j                  d|       |j                  d      r*t        j                  d       | j                  |      ||<   ct        j                  d       | j                  j                  j                  |      }|s| j                  ||      ||<    | j                  | j                  |       y )Nz"Embedding Type-1 font %s from dvi.zEmbedding font %s.z.afmzWriting AFM font.zWriting TrueType font.)r  r  r_   r_  rU  rV  _embedTeXFontr  endswith_write_afm_fontr  usedrS  embedTTFrs  r  )r   r  dvinamerg   r[  r  charss          r5   r(  zPdfFile.writeFonts  s   #D$4$4$:$:$<= 	1MGTBJJ;WE**40E"I	1 t~~. 	?H)BJJ+X6  (

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

34//4488B $h >E"I	? 	%0r7   c                    t        |d      5 }t        |      }d d d        j                         }t        d      t        d      t        |      t        d      d}| j	                  d      }| j                  ||       |S # 1 sw Y   ixY w)Nrbr  Type1WinAnsiEncoding)r   r   BaseFontEncodingfont dictionary)openr   get_fontnamerL   r  rs  )r   r  re  r  fontnamefontdictfontdictObjects          r5   rs  zPdfFile._write_afm_font  s    (D! 	Rr7D	$$& L#G} $X $%6 79 ++,=>2	 	s   BB
c                    t         j                  d|j                  j                  |j                         | j                  d      }| j                  ||j                  j                         | j                  d      }t        d      t        d      dt        |j                  j                        dz
  |d}|j                  ?t        d	      dgt        t        t        j                  |j                              d
|d	<   |j                  Lt         j                  d|j                          t        |j                         |d<   | j                  ||       |S t#        j$                  |j                        }|j&                  r|j)                  |j&                        }t        |j*                  d         |d<   |j&                  j-                  dd      |j&                  j-                  dd      f}| j.                  j-                  |j                  |f      }|7| j1                  ||j                        }|| j.                  |j                  |f<   ||d<   | j                  ||       |S )Nz#Embedding TeX font %s - fontinfo=%sfont widthsr~  r  rz  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)rU  rV  r^  rd  __dict__r  rs  widthsrL   r*   rb  r  r   
_parse_encr`  warningra  r   	Type1Fontrc  	transformproprS  r  createType1Descriptor)r   fontinfowidthsObjectr  r  t1fontrc  fontdescs           r5   rq  zPdfFile._embedTeXFont  sA   

8##++X->->	@ ))-8x'7'7'>'>? ++,=>fgX--4459%   ,Z( ND'"4"4X5J5J"KL N$HZ  $LLG !!# $((9(9#:HZ ^X6!! %%h&7&78%%h&6&67F#FKK
$;<
 ##''5##''#68((,,h.?.?-IJ11&(:K:KLHBJD!!8#4#4g">?%-!"2r7   c                 f   | j                  d      }| j                  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}	| j                  ||	       | j                  |dj                  |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StemVr7   )Length1Length2Length3rE  )r  r  r   rL   r  ascender	descenderrs  rH  r,   partsr*   )
r   r  r`  fontdescObjectfontfileObjectitalic_anglefixed_pitchflagsft2font
descriptors
             r5   r  zPdfFile.createType1Descriptor  sQ    ++,=>++K8{{=1kk.1VOE VOE
 VOE   8$   01J 78 "<<'"++",,)!;;|4
" 	4.#((6<<3C*D,/Q,@,/Q,@,-!/ 	 	0
 r7   c                     | j                  |      }dj                  |j                  j                         t        j
                  j                  t        j
                  j                  |            d   |g      S )N-r   )r\  r,   rM   r   rV   r8  splitextbasename)r   r  
glyph_namer[  s       r5   _get_xobject_glyph_namezPdfFile._get_xobject_glyph_nameV  s]    ]]8$xxGGNNGGRWW--h78;  	r7   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                 8    t              }t        j                  d   |j                  dfd fd} fd} j	                  |j
                  |j                               j                  dd      t              |j                  d      xs d	d	d
}|j                  d      xs 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      |
|j                  D cg c]  } |d       c} |j                  d       |j                   d       |d   d       |d         |d   d   d	d
}dk(  r
 ||||      S dk(  r
 ||||      S yc c}w )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  ry   floorceil)r4   upenearestr0  s       r5   cvtzPdfFile.embedTTF.<locals>.cvtx  sB    SL4'EU|#qyzz%((yy''r7   c                     #j                  d      }#j                  d      }#j                  d      }#j                  d      }g }d\  }}	 j                  D 
cg c]  }
  |
d       }}
t        d      "||	|t        d	      |d
   |g d|t        d      |d|d}ddlm   fd}t        j                         5  t        j                  d       t        ||	dz         D cg c]
  } ||       }}ddd       t              |d<   g }g }t               }|D ]a  }|} j                  |      }|j                  |        j                  |      }|dk  r|j                  ||f       Q|j                  |       c |j                          d}|D ]:  \  }}||dz   k7  r|j                  |       |j                  t        |             |}< t!        !|      }i }t#        |      D ]  }||   }i }||v r/t        d      t        d      |d}||j%                  d      dz   d }#j                  d      }#j'                  |||       ||v r"#j)                  !|      }|#j*                  |<   |||<    #j-                  ||       #j-                  ||       #j-                  ||       #j-                  ||       |S c c}
w c c}w # 1 sw Y   xY w)z5The Type 3-specific part of embedding a Truetype fontr  r  r~  zcharacter procs)r   r   Fr  r  Type3r  )MbP?r   r   r  r   r   r}  r  )r   r|  r  r  r  r   rL   r  
FontMatrix	CharProcsr}  r  r   )cp1252c                     t        j                  |          }j                  |t        t        z        j
                  } |      S )Nr  )r  decoding_table	load_charr   r   r  )charcoder3   r~   r  r  r  s      r5   get_char_widthz?PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.get_char_width  sG    --h78]_< ' >>Ik 5z!r7   ignorer$   NMaxWidthr   r  Formr   r   BBox   d1r  charProcrE  )r  r  rL   	encodingsr  warningscatch_warningsfilterwarningsr  r   rb   get_char_indexr+   r  addsortr  r  findrH  r  r  rs  )$r  
charactersr  r  r  r  charprocsObjectdifferencesArray	firstcharlastcharrC   r  r  r  r  r  r  differencesmulti_byte_charsr   ccodegindr  last_crM   rawcharprocs	charprocscharnamestreamcharprocDictcharprocObjectr  r  r  r  r   s$   `                              @r5   embedTTFType3z'PdfFile.embedTTF.<locals>.embedTTFType3  s9   --m<L!//0ABN!//0ABN"001BCO!"(Ix3799=aC5)=D= V#&$"0=":. 6, ,#35 'H" )"
 ((* H ''1*/	8A:*FH& )2 H HH &)[Jz"
 IK"u 5**51  &!006
C<&&z':;$((45 F& 4
?$++A. ''T
3	 .h	BLI"<0 9%h/! //,0O/3F|,0$2L $FKK$6$:$;<F!%!3!3J!?!!.&!M //77(KD6DD--d3*8Ih'398 ^X6^Z8\62_i8!!A >@HH Hs$   K'K*K9KKKc                 z	   ,j                  d      },j                  d      },j                  d      },j                  d      },j                  d      },j                  d      },j                  d      }	dj                  d	 |D              }
t        j                  d
)|
       t	        j
                  )|
      }t        j                  d)t        j                  )      j                  |j                         j                         | }t        |      } t        d      t        d      +dddd|||d}t        d      t        d      +t        d      |g|	d}||d<   ,j                  ||j                         d|j                         j                  i       dgdz  }g }d}|D ]u  }|}| j                  |      }| j!                  |t"        t$        z        }|j'                  | (|j(                        f       |dk  rt+        |      ||<   t-        ||      }w |j/                          |d|dz    }d}g }d}g }|D ]n  \  }}||dz   k7  r7|j'                  |       |j'                  |g       |j'                  ||g       n|d   j'                  |       ||d   d<   t-        ||      }|}p g }|D ]Q  \  }}|d kD  rt1        d |      }|j'                  d!||d"j                  d# t3        ||dz         D              fz         S ,j4                  t7        |      d$j                  |      fz  }g }|D ]1  }t9        *|      r|j                  |      }|j'                  |       3 |j:                  D  cg c]  }  (| d%&       }!} t=        )|      }"t?        |"      D ]|  }#|"|#   }$t        d'      t        d(      |!d)}%|$|$jA                  d*      d+z   d }$,j                  d,      }&,j                  |&|$|%       ,jC                  )|#      }'|&,jD                  |'<   ~ dj                  |      jG                  d-      },j                  ||       ,j                  |	|       ||d.<   ,jI                  ||       ,jI                  ||       ,jI                  ||       ,jI                  ||       |S c c} w )/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   2   K   | ]  }t        |        y wr?   )chrr  s     r5   r   z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>  s      <AQ <s   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  rE   i   r  Nr$   r  r  r   s   <%04x> <%04x> [%s]r'   c              3   &   K   | ]	  }d |z    yw)s   <%04x>Nr   )r   rC   s     r5   r   z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>M  s     Jy1}Jr   r(   Fr  r  r  r  r  r  r  utf-16ber  )%r  r,   rU  rV  r%   get_glyphs_subsetrV   statst_size	getbuffernbytesr   rL   rH  rr  r  r  r   r   r+   r  r  r   r  r   r  _identityToUnicodeCMapr*   r   r  r  r  r  r  r  r   rs  )-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startrt  unicode_cmapr  rC   r  r  r  r  r  r  rM   r  r  r   r  r   s-                                           r5   embedTTFType42z(PdfFile.embedTTF.<locals>.embedTTFType42  s   !//0ABN $ 2 23H I"&"4"45M"N $ 2 23G H!//0BCN((9G!%!3!3O!D < <<JJJ18ZH&88:NHJJ$h!))8+=+=+?+F+F I
 8$D V/# ' *"#"% #10K V=# .$5#6/M '5J{# 1 1 3 ("4"4"6"="=>  @ #Ve^NFI 2**51u-:_-L ' Nuc%*;*;&<=>5=,/IN5)y1	2 KKM+NY];NJAIN & 	#uJN*HHUOHHeW%"))5%.9bELL',1N2&q)	51	"
	# !O, 	M
s5=%o&&)CYYJeE3q56IJJLLM	M !77 0%**_2MNOL I# ++He<$33E:D$$T*+
 4=>>BaC5)BDB-h	BL"<0 A%h/(,Y+/<(, .  E 2Q 6 78!%!3!3J!?!!.&!M33HhG2@))$/!A&  WW^4;;JGN/@ 0,?%.Jz" .<0-@^Z8Wa(&&G Cs   <R8r   r[   pcltr   )	capHeightxHeightpostitalicAngler   r   Fr$   r      r  r  r  r%  r&  )
r   r  r  r  r  r  r  r  r  r  r   r   N)r   r]   ri  r  r#  r  get_charmapr   rL   get_sfnt_table
face_flagsstyle_flagsr   r   r  r  r  )r   r  r  r  r  r#  r$  r'  ffsfr  symbolicrC   r  r  r   r  s   ``            @@@r5   ru  zPdfFile.embedTTFr  s    !<</ --t 		(h	"TN	' N	'd ,,  
 ..)4w-""6*LA!.L""6*E}f.E__VOEVOEVOE;VOE )*8<		B1Q.B$--74>>59T+.>4	?+.q1
 q= z:>>^!$
J??  Cs   F
c                     | j                   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  rS  rT  r  rL   )r   alphastaterM   s       r5   
alphaStatezPdfFile.alphaState  ss       $$UD18OD))*D-(%(4 5 	 r7   c                    | j                   j                  |d      }||d   S t        | j                        }| j	                  d      }|t        d      dt        d      t        d      dg|d	d
f| j                   |<   | 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  rS  rT  r  r  rL   r  r+   r  rX  )r   smaskr6  rM   groupObs        r5   _soft_mask_statezPdfFile._soft_mask_state  s    &&**5$78OD''($$%GH[) Ll+# 		)
u% 	%%Y<n-|, -'#u6$ #Y

#'
 	  r7   c                     | j                  | j                  t        g | j                  j	                         | j
                  j	                                      y r?   )rs  r  r   r  r-  r  r   s    r5   r)  zPdfFile.writeExtGSTates  sT    !! !!((*''..0 	
r7   c                     | j                   D ]B  \  }}}| j                  |j                  d |        | j                  |  | j	                          D y r?   )r  r   r   r  r  )r   r5  
attributescontents       r5   r*  zPdfFile._write_soft_mask_groups  sL    '+'='= 	#B
GRUUD*5DKK!NN	r7   c                     |%|\  }}}|t        |      }|t        |      }|||f}| j                  j                  |d       }||S t        | j                        }|| j                  |<   |S r?   )r   r  rS  rT  r  )r   hatch_styleedgefacehatchpatternrM   s          r5   hatchPatternzPdfFile.hatchPattern  s    " +D$T{T{u-K$$((d;ND++,*.;'r7   c                    t               }d}| j                  j                         D ]  \  }}| j                  d      }|||<   ddj	                         D cg c]  }t        |       c}i}| j                  |j                  d t        d      ddddd||g|||ddddd| j                  dz  gd		       |\  }}	}
| j                  |d   |d   |d
   t        j                         |	M| j                  |	d   |	d   |	d
   t        j                  dd||t        j                  t        j                  
       | j                  t        j                   d   t        j"                          | j                  | j%                  t'        j(                  |
      t+               j-                  |      d        | j                  t        j.                         | j1                           | j3                  | j4                  |       y c c}w )N      R@zhatch patternProcsetsr  r  r$   r   r  )	r   PatternType	PaintType
TilingTyper  XStepYStepr  rD  r  zhatch.linewidthFsimplify)r   r  r_   r  r  rL   r   r   r   r  r  rE  rF  r>  r4  r]   ri  rV  pathOperationsr!   rP  r   scaler2  r  rs  r  )r   	hatchDictsidelenrM  rM   r5  rC   res
stroke_rgbfill_rgbrP  s              r5   r+  zPdfFile.writeHatches  s   F	!%!3!3!9!9!;  	K##O4B IdO%D%J%J%LMDGMOCti !Q1!G!q!Q4;;+;<>? +6'J%KK
1z!}jm((*#HQK!hqk//q'7BLLGG%
 KK%67IDKK,,

5!
  ) -   ! KK'NNA 	B 	))95; Ns   G?c                     t        dt        | j                        z        }| j                  d|       }| j                  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 )rL   r*   r  r  r+   )r   pointscolorsrM   r5  s        r5   addGouraudTriangleszPdfFile.addGouraudTriangles7  s\    $ FS!6!6778"3D6 :;$$dB%?@Rxr7   c                 L   t               }| j                  D ]n  \  }}}}|||<   |j                  }|j                  |d   |d   z  df      }|j                  d   }|dv sJ |j                  |d   |d   z  |f      }	|dk(  rd}t	        j
                  |d      dz
  }
t	        j                  |d      dz   }d	||
z
  z  }| j                  |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                  |j                                | j                          q | j                  | j                  |       y )Nr   r$   r  r$   r  r  r   r  r   l    r*     r  r@  F)ShadingTypeBitsPerCoordinateBitsPerComponentBitsPerFlag
ColorSpace	AntiAliasDecode)r  u1)re  z>u4)r  rf  rr  dtyper  re  g     o@)r   r  shapereshaper   r   r   r   r   rL   emptyr   tobytesr  rs  r  )r   gouraudDictrM   r5  re  rf  ru  flat_pointscolordimflat_colors
points_min
points_maxfactor	streamarrs                 r5   r,  zPdfFile.writeGouraudTrianglesN  s   f(,(=(= '	$D"ff "KLLE ..%(U1X*=q)ABK||AHv%%% ..%(U1X*=x)HIK1}!4?J!4?J:
#:;Ft !&(%& !#$,M[|  $']JqM']JqM; !fx/0 qE!H$&&. $467I
 "#Ig#.#;v"EIh"-a(l";e"CIhJJy((*+NNO'	P 	++[9r7   c                     | j                   j                  t        |      d      }||d   S t        | j                        }| j                  d|       }|||f| j                   t        |      <   |S )z=Return name of an image XObject representing the given image.Nr$   zimage )r  rS  r   rT  r  r  )r   r4  entryrM   r5  s        r5   imageObjectzPdfFile.imageObjectz  so       ED18ODOO$&0#($"3RYr7   c                 B   |ddd   }|j                   dk(  r|dfS |ddddddf   }t        j                  |d      }|j                  d   dk(  rH|dddddf   d   }t        j                  |d	k(        rd}||fS t        j                  |d      }||fS d}||fS )
z
        Unpack image array *im* into ``(data, alpha)``, which have shape
        ``(height, width, 3)`` (RGB) or ``(height, width, 1)`` (grayscale or
        alpha), except that alpha is None if the image is fully opaque.
        Nr  r  r   C)orderr  ).Nr   )ndimr   r  ru  r  )r   imrgbr5  s       r5   _unpackzPdfFile._unpack  s     "X77a<t8OQ2A2X,C((3c*Cxx{a1a7I.66%3,' E
 : HHU#6E : :r7   c                    t               }|j                  |d       |j                  d       d}dx}}	 t        j                  d|j                  d            \  }}|dv rQ|j                  |      }t        |      |k7  rt        d      |d	k(  rt        |d         }n+|d
k(  r|}n#|dk(  r||z  }n|dk(  rn%|j                  |d       |j                  dd       |||fS )zn
        Write the image *img* into the pdf file using png
        predictors with Flate compression.
        rm  )rg  rj  r7   Ns   !L4s)   IHDR   PLTE   IDATztruncated datar  r  r  s   IENDr$   r  )	r   saveseekstructunpackreadr*   RuntimeErrorrY   )	r   imgbufferpng_data	bit_depthpaletter4   r   rw  s	            r5   	_writePngzPdfFile._writePng  s    
 &A""	G!==&++a.ALFD22{{6*t9&&'7887? #DGIW_"GW_$HFA&KK1! " G++r7   c           	      L   |j                   \  }}}t        d      t        d      ||t        ddd|         dd}|r||d<   t        j                  d	   rK|j                   d
   dk(  r|j	                  d
      }d||d}t        j                  |      }	|	j                  d      }
|dk(  r|
t        |
      }t        j                  |
D cg c]  \  }}|D ]  }|  c}}}t        j                        }|ddd   j                  t        j                        dz  |ddd   j                  t        j                        dz  z  |ddd   z  }|dddddf   j                  t        j                        dz  |dddddf   j                  t        j                        dz  z  |dddddf   z  }t        j                  |      j                  t        j                        }|t        j                  |||         }t        j                  |d      }	|	j!                  |       | j#                  |	      \  }}}||t%        d      |d|dz   }t        d      t        d      |dz
  |g|d<   ||d<   d|d<   ||d<   n| j#                  |	      \  }}}nd}| j'                  || j)                  d      ||        |r| j*                  j-                         n)| j*                  j-                  |j/                                | j1                          yc c}}}w )!a  
        Write the image *data*, of shape ``(height, width, 1)`` (grayscale) or
        ``(height, width, 3)`` (RGB), as pdf object *id* and with the soft mask
        (alpha channel) *smask*, which should be either None or a ``(height,
        width, 1)`` array.
        r  r   r@  r  r$   r   rj  )r   r   WidthHeightro  rm  r>  rd  r  r$   r  
   )	PredictorColorsColumnsr   )	maxcolorsr   Nrs  r      r  )sorterP)modezinvalid PNG headerIndexedro  rm  r  zlength of image stream)rm  )ru  rL   r]   ri  squeezer   	fromarray	getcolorsr*   r   r  uint8r  uint32argsortsearchsorted
putpaletter  r  r   r  r  r   rx  r  )r   rw  r   rE  r   r~   color_channelsr   rm  r  
img_colors
num_colors_colorcompr  	palette24rgb24indicesrgb8r  r  s                         r5   	_writeImgzPdfFile._writeImg  s    )-

%~Iw-!l{"CN"ST#$&  CL<<)*zz"~"|||, "nOC//$'C5J"z'= !_
((#V#VXQPU#VD#VD#V)+3%addm22299=C%addm22299=BD$QTT]+	 q!Qw-..ryy9R?q!Qw-..ryy9Q>@aAg' **Y/66rxx@ry%PQood5w'/3~~c/B,)W$&';<<!/:>2%))_d;6G%/!^W%>L!*3&' !H*3&'!%!4!QC78	 	 	 $$X.$$T\\^4G $Ws   Lc                    | j                   j                         D ]i  \  }}}| j                  |      \  }}|.| j                  d      }| j	                  ||j
                         nd }| j	                  ||j
                  |       k y )NrE  )r  r-  r  r  r  r   )r   r  rM   r5  rw  adatasmaskObjects          r5   r.  zPdfFile.writeImages  sw    !\\002 	5MCr,,s+KD% "009uknn5"NN44	5r7   c                    | j                  ||d      }t        |      t        |      t        |      ||f}	| j                  j	                  |	      }
|
nt        dt        | j                        z        }| j                  dt        | j                        z        }|j                  |      }||||g| j                  |	<   |S |
d   |k  r||
d<   |
d   }|S )z<Return name of a marker XObject representing the given path.Fr[  zM%dz	marker %dr  r   )	r]  r   r   r  rS  rL   r*   r  get_extents)r   r8  r9  r4  r3  lw	joinstylecapstylepathopskeyr1   rM   r5  r  s                 r5   markerObjectzPdfFile.markerObject  s     %%dEE%BW~tDz4<HM!!#&>DLL 112D##K#dll2C$CDB##E*D!%r4 4DLL
  bzBr
!9Dr7   c           
      b   | j                   j                         D ]  \  \  }}}}}\  }}}}	|j                  |	dz        }| j                  |j                  d t        d      t        d      t        |j                        d       | j                  t        j                  |   t        j                         | j                  t        j                  |   t        j                          | j                  |  | j                  t        j                  ||             | j!                           y )N   r  r  r  )r  r_   paddedr   r   rL   r   extentsr  r  r  r  rL  	capstylesrM  r7  r  )
r   r  r4  r3  r  r  rM   r5  r  r  s
             r5   r/  zPdfFile.writeMarkers   s    &*ll&8&8&:	 #9gtVY!dBb ;;rAv&DtiT&\dll+-. KK*55i@(KK*44X>NDKK!KKdF34NN'	r7   c                    t        dt        | j                        z        }| j                  dt        | j                        z        }| j                  j	                  |||||j                         |j                         |||f	       |S )NzP%dzpath %d)rL   r*   r  r  r+   get_joinstyleget_capstyle)	r   r   r8  r9  r;  r<  r=  rM   r5  s	            r5   pathCollectionObjectzPdfFile.pathCollectionObject6  sx    EC

O+,	C

O ;<

4B$4$4$68Ifg'	( r7   c           
         | j                   D ]h  \	  }}}}}}}}}	| j                  ||d      }
|j                  |      }t        j                  t        j
                  |j                              sg d}n&|j                  |      }t        |j                        }| j                  |j                  d t        d      t        d      |d       | j                  t        j                  |   t        j                          | j                  t        j"                  |   t        j$                          | j                  |
  | j                  t        j'                  ||	             | j)                          k y )NFr[  r   r   r   r   r  r  r  )r  r]  r  r   r  r   r  r  r   r   r   rL   r  r  r  r  rL  r  rM  r7  r  )r   rM   r8  r9  r5  r  r  r;  r<  r=  r  r  r  s                r5   r0  z$PdfFile.writePathCollectionTemplates>  s(   	 T4Ix&))$)FG##E*D66"++dll34&{{7+t||,tiT&\ "# KK*55i@(KK*44X>NDKK!KKfg67NN%	r7   c                    t        t        j                  | ||||dt        j                  j
                  t        j                  j
                  dt        j                  j
                  t        j                  j
                  gd            gS )Nr  r7   T)	r  r#   r  r  r@  r0  r?  r=  r9  )r8  r  rW  r\  sketchs        r5   r]  zPdfFile.pathOperationsS  sg    00)T8VYY__biioosBJJ4D4D\\!   	r7   c                     |r-dd| j                   dz  | j                  dz  f}|j                  }nd }d}| j                  |||||      } | j                  |  y )Nr  r  F)r\  r  )r~   r   should_simplifyr]  r  )r   r8  r  rW  r  r\  cmdss          r5   	writePathzPdfFile.writePath\  sg    djj2ot{{R/?@D++HDH""4D8*0 # 2Tr7   c                 ~    t        | j                        }| 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   )rT  r  r  r+   r   )r   rM   r   s      r5   r  zPdfFile.reserveObjectg  s6     $""#tQo.}r7   c                 r    | j                   j                         | j                  z
  | j                  |   d<   y Nr   )re  rl  r  r  r   s     r5   rh  zPdfFile.recordXrefr  s(     $ ?r1r7   c                 ^    | j                  |j                         |j                  ||        y r?   )rh  r   r   )r   objectr   s      r5   rs  zPdfFile.writeObjectu  s     		"Xt$r7   c                 T   | j                   j                         | j                  z
  | _        | j	                  dt        | j                        z         t        | j                        D ]=  \  }\  }}}|t        d||fz        |dk(  rdnd}d|||fz  }| j	                  |       ? y)zWrite out the xref table.s
   xref
0 %d
NzNo offset for object %d (%s)r  r  r"  s   %010d %05d %b 
)	re  rl  r  	startxrefr   r*   r  r)   AssertionError)r   r2   offset
generationrM   r  r  s          r5   r2  zPdfFile.writeXrefy  s    $..8

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

4 	!r7   c                 |    | j                  d      | _        | j                  | j                  | j                         y)z8Write out the info dictionary, checking it for good formrg   N)r  
infoObjectrs  r  r   s    r5   r1  zPdfFile.writeInfoDict  s.     ,,V4$--8r7   c                     | j                  d       | j                  t        t        | j                        | j                  | j
                  d             | j                  d| j                  z         y)zWrite out the PDF trailer.s   trailer
)SizeRootInfos   
startxref
%d
%%%%EOF
N)r   r   r*   r  r  r  r  r   s    r5   r3  zPdfFile.writeTrailer  sZ     	

< 

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

04>>ABr7   r?   r{  )NNNFN)r  )4r   r   r   r   r   r  r  r#  r>  r@  r   r  r   r  rH  r'  r\  ro  r(  rs  rq  r  r  r  ru  r7  rG  r)  r*  rR  r+  rg  r,  r  r  r  r  r.  r  r/  r  r0  staticmethodr]  r  r  rh  rs  r2  r1  r3  __classcell__r  s   @r5   r  r    s   g9R": .@ -* B	+?&
 04 
8><1*
8t=~*{@z	2h
$$6L.*:X
.,:=~5:,*  		@%!9	Cr7   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 ZddZd ZdddZd ZddZd Zd Z xZS )rQ  zfonts/pdfcorefontsrK  c                 l    t         |   ||       || _        | j                         | _        || _        y r?   )r  r   r   new_gcr   	image_dpi)r   r   r  r   r~   r  s        r5   r   zRendererPdf.__init__  s-    '	++-"r7   c                 f     | j                   j                  | j                  j                           y r?   )r   r  r   r>  r   s    r5   r>  zRendererPdf.finalize  s#    		$''**,-r7   Nc                    t        |dd      }||_        t        |dd      }|j                         |j                  dd       |j                  r|j
                  |j
                  f|_        n@|t        |      dk  r|j                  d	   d
f|_        n|j                  d	   |d	   f|_        | j                  j                  |      }|r | j                  j                  |  ||_        ||_        y )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         r5   check_gczRendererPdf.check_gc  s    Bl;	!b"5zB::< l48$&IIryy#9B #i.1"4$&GGAJ#4B $&GGAJ	!#=B b!DIIe$ "*r7   c                      | j                   dz  S )NrT  )r  r   s    r5   get_image_magnificationz#RendererPdf.get_image_magnification  s    ~~d""r7   c                    |j                   d d \  }}|dk(  s|dk(  ry ||j                  d       | j                  |       d|z  | j                  z  }d|z  | j                  z  }| j                  j                  |      }|^| j                  j                  t        j                  |dd|||t        j                  |t        j                  t        j                         y |j                         j                         \  }	}
}}}}| j                  j                  t        j                  dddd||t        j                  |	|
||||t        j                  |t        j                  t        j                         y )Nr  r   r  rT  r$   )ru  	set_alphar  r  r   r  r  r  rO  rA  rB  rP  frozen	to_values)r   r   rC   r}   r  r  hr  imobtr1tr2tr3tr4tr5tr6s                  r5   
draw_imagezRendererPdf.draw_image  s8    xx|16Q!VLLb1Ht~~%1Ht~~%yy$$R(IIRXX1aAr/?/?!2>>2;;@ ,5+;+;+=+G+G+I(Cc3SIIRXX1aAr/?/? #sCc2;K;K!2>>2;;@r7   c                    | j                  ||       | j                  j                  |||d u xr |j                         d u |j	                                | j                  j                  | j                  j                                y r?   )r  r   r  get_hatch_pathget_sketch_paramsr  r   paint)r   r   r8  r  rgbFaces        r5   	draw_pathzRendererPdf.draw_path  sk    b'"		)tO; 1 1 3t ;  "	$ 			)r7   c                    d}t        j                  |      }t        j                  |      }t        |      sd}|j                          }n-t        j                  |d d df   |d   k(        r	|d   dk7  }nd}t        |      sd}n[t        j                  t        j                  |	      dk(        rd}n-t        j                  |d d df   |d   k(        r	|d   dk7  }nd}t        |      dkD  rt        |d   j
                        nd}| j                  |||||      }||z   dz   ||z  k  }|r|s"t        j                  | |||||||||	|
|||      S t        j                  |	      }g }t        | j                  |||            D ]9  \  }\  }}| j                  j                  ||||      }|j                  |       ; | j                  j                  } || j                   j#                           d\  }}| j%                  |||||||	|
|||      D ]T  \  }}}} }!| j'                  | |!       ||z
  ||z
  }#}" |d	ddd	|"|#t(        j*                  |t(        j,                  	       ||}}V  || j                   j/                           y )
NTFr   )r   r   r  r   r  r)  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  rA  rB  pop)$r   r   master_transformr  all_transformsoffsetsoffset_trans
facecolors
edgecolors
linewidths
linestylesantialiasedsurlsoffset_positioncan_do_optimizationr<  r=  len_pathuses_per_pathshould_do_optimizationr;  
path_codesr2   r8  r  rM   r  lastxlastyxoyopath_idgc0r  dxdys$                                       r5   r  z RendererPdf.draw_path_collection  s    #ZZ
+
ZZ
+
:F&(lln"4vvjA&*T*::;#D)S0&+#:Gvvbjj,34
1a4(Jt,<<=$T*c1&+# .1Z!^3uQx(();;>7J
D }$q(8m+CC 	 $-C44b*E>z:Jd	! ! &&$
$-d.M.M %/9 %: 	$ A i9911D)Wfg?Dd#		$ !!u-1-B-BJJ
JdO.5 		")BGS'
 MM#w'%ZeB1aAr2r'7'7>>#r5E		" 	r7   c                    t        |      }t        |      }||z  ||z   dz   k  rt        j                  | ||||||       y | j                  ||       |j	                  |      }	|j                         }
| j                  j                  }| j                  j                  |||	|
| j                  j                  |j                         |j                               } |t        j                         d\  }}|j                  |dd| j                  j                   dz  | j                  j"                  dz  fd      D ]  \  }}t        |      s|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 d||z
  ||z
  }} |dddd||t        j$                  |t        j&                  	       ||}}  |t        j(                         y )	Nr  r)  r   r  F)rW  r\  r  r$   )r*   r   draw_markersr  r4  r3  r   r  r  r   
_linewidthr  r  r  rO  iter_segmentsr~   r   rA  rB  rP  )r   r   marker_pathmarker_transr8  r9  r  len_marker_pathusesr4  r3  r  markerr0  r1  r   coderC   r}   r6  r7  s                        r5   r9  zRendererPdf.draw_markers1  s   
 k*4yT!Od$:Q$>>%%dB\&*E7<b'"www!!''tVTWW5G5G 13 	rxxu"00DIIOOB.		0@0@0CD 1   	$NHd 8}}1Q6$))//B"66;dii&6&6&;;UAIBq!Q2r2+;+;r~~/ !u	$ 	r{{r7   c                 h    | j                  ||j                  d      |j                  d      |       y )N)r$   r   r  )r$   r   r  )draw_gouraud_trianglesrv  )r   r   re  rf  r9  s        r5   draw_gouraud_trianglez!RendererPdf.draw_gouraud_triangleW  s,    ##By(A$*NN9$=u	Fr7   c                    t        |      t        |      k(  sJ t        |      dk(  ry |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                  }|j                  |d   |d   z  df      }|j	                  |      }|j                  |      }| j
                  j                  ||      \  }}| j
                  j                  }	|j                  d   dk(  r:|j                  d       | j                  |        |	|t        j                         y |d   }
t        j                  |
|d d d d df         r:|j                  |
       | j                  |        |	|t        j                         y |d d d d df   d d d d d f   }
| j
                  j                  ||
      \  }}| j
                  j                  |      } |	t        j                  |t        j                   |t        j                  t        j"                         y )Nr   r   r$   r  ri  r  )r   r   r   )r*   r  ru  rv  r  r   rg  r  r  r  r  rX  r   allcloserG  rO  rN  rP  )r   r   re  rf  r9  ru  tpointsrM   r  r  r5  smask_obgstates                r5   rC  z"RendererPdf.draw_gouraud_triangles[  s   6{c&k)))v;!{{a||A!###||A!###{{a||A!###||A&(((qE!H!4a 89//&)//%())//@a!!<<?aLLMM"4$w;;ufQ1Wo.LLMM"4$ 1a7OAq$J/E))77GKAxYY//9F288VR\\;; r7   c           	         ||cxk(  rdk(  r5n n2| j                   j                  ||z
  ||z
  t        j                         y t	        j
                  |      }| j                   j                  t	        j                  |      t	        j                  |      t	        j                  |       t	        j                  |      ||t        j                         | j                   j                  ddt        j                         y r  )	r   r  r  rQ  ry   rz   r|   r{   rS  )r   rC   r}   r   oldxoldyoldangles          r5   _setup_textposzRendererPdf._setup_textpos  s    H!!IIQXq4x<LL'EIITXXe_dhhuo"hhuo-txx2==2 IIQ2::.r7   c                    | j                   j                  j                  |d|      \  }}}	}
}|j                         9| j                  j
                  d   d   j                  t        ||||||             t        j                  d   }t        j                  |      }| j                  j                  t        j                         | j                  j                  t        j                  |      t        j                   |      t        j                   |       t        j                  |      ||t        j"                         | j%                  ||j&                         d}d\  }}g }| j                  j                  t        j(                         |
D ]	  \  }}}}}| j                  j*                  j-                  ||       |j.                  }t1        ||      s|j                  |||||f       _| j3                  ||d||       ||}}||f|k7  rH| j                  j                  | j                  j5                  |      |t        j6                         ||f}| j                  j                  | j9                  t;        |      |      t        j<                          | j                  j                  t        j>                         |D ],  \  }}}}}| jA                  |||jC                  |      ||       . |D ]a  \  }}}}| j                  j                  t        j                  ||||t        jD                  t        jF                  t        jH                         c | j                  j                  t        jH                         y )Nr  r  r$   r  r{  r)  r   )%
_text2pathmathtext_parserparser   r   r  r+   r   r]   ri  ry   rz   r  r  rO  r|   r{   rA  r  r  r;  r  track_glyphrZ  r   rN  r\  rR  encode_stringr  rT  r<  _draw_xobject_glyphr  r>  r4  rP  )r   r   rC   r}   r3   r  r   r~   r   descentglyphsrectsr   r   	prev_fontrK  rL  unsupported_charsr  fontsizenumoxoyr  s                           r5   draw_mathtextzRendererPdf.draw_mathtext  s    OO++11!R> 	.vw ::<#II""2&q)001EAq%20 1 <</ LL		"		!dhhqk((1+txx{Ar//	1 	b"''"	
d		'+1 	*'D(CRII((44T3?zzH'#6 "(($"b#)FG##BAtT:dh'94II$$TYY%7%7%A8%']]4 (( 2I		  !3!3CHh!G!#*	*  			%+< 	B'D(BC$$h 3 3C 8"bB	B
 &+ 	A!BE6IIRXXr2uf\\277BKKA	A
 			%r7   )mtextc          
         | j                         }|j                         }	|j                  ||	      }
t        j                  |
d      5 }|\  }d d d        |j                         M| j                  j                  d   d   j                  t        |||j                  |j                  |             d g }}j                  D ]V  \  }}}}}||k7  r0| j                  j                  |      }|d||j                  ggz  }|}|d||t        |g      g||z   ggz  }X d\  }}}	|t!        |      dz
  k  r|||dz    \  }}|d   dk(  r|d   }	n|d   |d   cxk(  rdk(  r~n n{|d   |d   k(  rp|d	   |d   z
  }t#        |      d
k  r-|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  rt%               j'                  |      j)                  ||      }| j+                  ||j,                         | j                  j/                  t0        j2                         d\  }}}}|D ]  }|d   dk(  r2| j                  j/                  |d   |d   t0        j4                         =|d   dk(  r|j7                  |d   |d   f      \  }}| j9                  |||||       ||}}t!        |d         dk(  r1| j                  j/                  |d   d   t0        j:                         | j                  j/                  |d   t0        j<                         J  | j                  j/                  t0        j>                         | jA                         }|jC                  |       |jE                  d       tF        jH                  tF        jJ                  tF        jJ                  tF        jJ                  tF        jL                  g}|jN                  D ]L  \  }}} }!tG        ||g||!z   |g||!z   || z   g||| z   gddgg|      }"| jQ                  ||"||j,                         N y # 1 sw Y   xY w)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  ro  sizer   r*   absr   
rotate_degr   r  r  r  r  r;  rR  r  rN  rT  rU  r<  r  copy_propertiesset_linewidthr!   MOVETOLINETO	CLOSEPOLYboxesr  )#r   r   rC   r}   r3   r  r   r`  
texmanagerr[  dvifiledvir  oldfontseqx1y1r^  r   r~   r_  r2   curxeltnxtr  mytranscuryrK  rL  boxgcr  r  r  r8  s#                                      r5   draw_texzRendererPdf.draw_tex  sS   ((*
**,%%a2[["% 	ED	 ::<#II""2&q)001EAq$**dkk52: ; R-1YY 	B)BGUE'!))//8',,788!VReUGn%5r%x@AAC	B '4#c(1*n1QqSzHC1vq6Q3q6+V+A#a&0@Q#a&v;$F2J#a&)+JFc!fSVm+FFvf}X5s1vayAAF VCF!HFA #c(1*n" *''.88A> 	b"''"		'!+dD$ 	C1v		  QQ?Q6!$..AA/?@
d##D$tTB!4ds1v;!#II$$SVAY8II$$SVR[[9u	 			% b!A;;T[[$++>># JJ 	:LBAq"bBqD":1bd|b"Q$ZQ!")+DNN5$9	:S	 	s   	QQ$c                 R    |dv r|j                  dd      S |j                  dd      S )Nr  r  r[   r	  )r   )r   r3   r   s      r5   rT  zRendererPdf.encode_string	  s,    v88Hi00xx
I..r7   c	                 
   | j                  ||j                         |r| j                  ||||||      S |j                         }	t        j
                  d   r| j                  |      }
d}nJ| j                  |      }
| j                  j                  j                  |
|       t        j
                  d   }|j                         c|
j                  |       |
j                         \  }}| j                  j                  d   d   j                  t!        ||||dz  |dz  |             |dvr| j                  j#                  t$        j&                  | j                  j)                  |      |	t$        j*                         | j-                  |||       | j                  j#                  | j/                  ||      t$        j0                  t$        j2                         y g }g }d}|
}t5        j6                  ||
t8              D ]  }t;        |t=        |j>                              r|s|j@                  |k7  r4|j                  |j@                  |jB                  g f       |j@                  }|jD                  r!|d   d	   j                  |jD                         |d   d	   j                  |j>                         d
}|j                  |j@                  |jB                  |jF                  f       d} | j                  j#                  t$        jH                         tK        jL                  |      }| j                  j#                  tK        jN                  |      tK        jP                  |      tK        jP                  |       tK        jN                  |      ||t$        jR                         | j                  j#                  t$        j&                         d}|D ]  \  }}}| j                  j)                  |jT                        }| j                  j#                  ||	t$        j*                         | j-                  |dd|dd       | j                  j#                  tW        jX                  |tZ              D cg c]@  \  }}|t\        k(  rdt_        |      z  |	z  n | j/                  dja                  |      |      B c}}t$        jb                         |} | j                  j#                  t$        j2                         |D ]  \  }}}| je                  ||	||d        | j                  j#                  t$        jf                         y c c}}w )NrK  r$   r  r  r  )r   r   T)	kern_moder  Fr   ir  )4r  r  r_  rc  r]   ri  _get_font_afm_get_font_ttfr   r  trackr   set_textget_width_heightr  r+   r   r  r  r;  r\  rR  rN  rT  rT  r<  r
   layoutr   r   r  char	ft_objectrC   	prev_kern	glyph_idxrO  ry   rz   r|   r{   rA  rZ  r   groupbyr   r   rT  r,   rU  rU  rP  )r   r   rC   r}   r3   r  r   ismathr`  r[  r  r   r~   r   singlebyte_chunksmultibyte_glyphsprev_was_multibyterY  itemr   prev_start_xr  start_xkerns_or_charsft_nametpgroupr  s                               r5   	draw_textzRendererPdf.draw_text	  sE   
 	b"''"%%b!Q4??**,<<,-%%d+DH%%d+DII((..tQ7||N3H::<#MM! 113ME6II""2&q)001EAq%"*frk52: ;
 7"IIR]]!YY//5xP1e,IIT//8<WWbkk3$ !#!!%I%,,t'79 .'#dii.A)T^^y-H)00$..$&&"1MN$(NN	~~)"-a077G%b)!,33DII>).&$++@ *.&." IIRXX&U#AIITXXa[$((1+"hhqk\488A;2#3#35
 IIR]]+L6G '2	7N)),,Y__=		  (BMMB##GQ<AF		  
 '0&7&7&MO"U 8:U{UT%[(83,,RWWU^XFG O KK!  '' IIR[[)1A -	7I((xGQ IIR[[)Os   5AUc                 J   |j                  |      }| j                  j                  |j                  |      }| j                  j	                  t
        j                  d|z  ddd|z  ||t
        j                  t        |      t
        j                  t
        j                         y)z<Draw a multibyte character from a Type 3 font as an XObject.r  r   N)r  r   r  rZ  r  r  rO  rA  rL   rB  rP  )r   r  r[  r  rC   r}   r  rM   s           r5   rU  zRendererPdf._draw_xobject_glyph	  sx    ((3
yy00ZH		HHHaEH$4aB<L<LJKK		
r7   c                 ,    t        | j                        S r?   )r  r   r   s    r5   r  zRendererPdf.new_gc	  s    !$)),,r7   r?   r   r  )r   r   r   r   _get_data_pathrR  _use_afm_rc_namer   r>  r  r  r  r  r  r9  rD  rC  rN  r_  r|  rT  r  rU  r  r  r  s   @r5   rQ  rQ    s    (E(()=>M+#.+6#@<*DN "$LF& P/4&l ;? Q:f/
b*H	
-r7   rQ  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                 Z    t         |           d| _        d| _        || _        d | _        y )Nr  r  )r  r   r  r  r   parent)r   r   r  s     r5   r   zGraphicsContextPdf.__init__	  s+    )!+	r7   c                 N    t        | j                        }|d= |d= t        |      S )Nr   r  )r   r  repr)r   rt   s     r5   r   zGraphicsContextPdf.__repr__	  s'    fIhKAwr7   c                     | j                   dkD  xr= | j                  dkD  xr, t        | j                        dk  xs | j                  d   dk7  S )z
        Predicate: does the path need to be stroked (its outline drawn)?
        This tests for the various conditions that disable stroking
        the path, in which case it would presumably be filled.
        r   r   r  )r:  r  r*   r  r   s    r5   r3  zGraphicsContextPdf.stroke	  sK     !# =a =TYY1$;		!(;	>r7   c                     t        |      r|d   }n| j                  }| j                  xs |duxr t        |      dk  xs |d   dk7  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      r5   r4  zGraphicsContextPdf.fill	  sX     t9aJJ A4' @j/Q&>*Q-3*>	Br7   c                 f    t         j                  | j                         | j                               S )zo
        Return the appropriate pdf operator to cause the path to be
        stroked, filled, or both.
        )r  r7  r4  r3  r   s    r5   r  zGraphicsContextPdf.paint	  s!    
 }}TYY[$++-88r7   r   r$   r  )buttr  
projecting)miterr  bevelc                 @    | j                   |   t        j                  gS r?   )r  r  rM  r   styles     r5   capstyle_cmdzGraphicsContextPdf.capstyle_cmd	  s    u%r}}55r7   c                 @    | j                   |   t        j                  gS r?   )r  r  rL  r  s     r5   joinstyle_cmdz GraphicsContextPdf.joinstyle_cmd	  s    &77r7   c                 &    |t         j                  gS r?   )r  rV  )r   r~   s     r5   linewidth_cmdz GraphicsContextPdf.linewidth_cmd	  s    r''r7   c                 P    |\  }}|g }d}t        |      |t        j                  gS r  )r   r  rK  )r   dashesr  dashs       r5   dash_cmdzGraphicsContextPdf.dash_cmd	  s/    <DFT
FBJJ//r7   c                 \    | j                   j                  |      }|t        j                  gS r?   )r   r7  r  rN  )r   r5  forcedeffective_alphasrM   s        r5   	alpha_cmdzGraphicsContextPdf.alpha_cmd	  s&    yy##$45bll##r7   c                 4   |sB| j                   | j                  | j                         S t        d      t        j                  gS || j                   |f}| j
                  j                  |      }t        d      t        j                  |t        j                  gS )Nr  r  )r  fillcolor_cmdrL   r  rH  r   rR  rJ  )r   rP  hatch_colorrM  rM   s        r5   	hatch_cmdzGraphicsContextPdf.hatch_cmd	  s    *))$//::[)2+E+EFF&?K99))+6DOR%?%?"//1 1r7   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   )r]   ri  r  rC  rE  r   r  s     r5   rgb_cmdzGraphicsContextPdf.rgb_cmd	  s^    <<*+Iq6SV%s1v%FB--../S!W/b..//r7   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  )r]   ri  r  rD  rF  r  s     r5   r  z GraphicsContextPdf.fillcolor_cmd	  sb    ;#,,'9:IVs1v'Q'FB00112S!W2b1122r7   c                     t        | j                        }|j                  |        | j                  |_        || _        t        j
                  gS r?   )r  r   ri  r  r  rO  )r   r  s     r5   r  zGraphicsContextPdf.push	  s<    #DII.t$zr7   c                     | j                   J | j                  | j                          | j                   j                   | _         t        j                  gS r?   )r  ri  r  rP  r   s    r5   r  zGraphicsContextPdf.pop	  sA    {{&&&T[[)kk((}r7   c                    g }| j                   | j                  f||fk7  rU| j                  I|j                  | j	                                | j                   | j                  f||fk7  r| j                  I| j                   | j                  f||fk7  s| j                  |j                  | j                                | j                   |k7  r?|j                  |t        j                  t        j                  t        j                  g       | j                  |k7  r[|j                         \  }}|j                  t        j                  ||d      t        j                  t        j                  gz          |S )z1Set clip rectangle. Calls `.pop()` and `.push()`.Fr[  )	_cliprect	_clippathr  r  r  r  r  r>  rW  r5  get_transformed_path_and_affiner  r]  )r   cliprectclippathr  r8  affines         r5   clip_cmdzGraphicsContextPdf.clip_cmd	  s#   /Hh3GGKK+KK
# /Hh3GGKK+ ^^T^^,80DD#KK		$~~)Xr||RWWbjjIJ~~)'GGIf**4%*HWWbjj)*+ r7   )r  r  )r  r  r  )	_capstyler  )
_joinstyle)r:  )_dashes)r  r  _hatch_colorc           
      V   g }d}| j                   D ]  \  }}d}|D ]6  }t        | |      }t        ||      }		 ||	||	u}nt        ||	k7        }|s6 n |dk(  r|rd}|sO|dk(  rd}|D cg c]  }t        ||       }	}|j                   || g|	        |D ]  }t        | |t        ||               |S # t        $ r` t	        j
                  |      }t	        j
                  |	      }	|j                  |	j                  k7  xs t	        j                  ||	k7        }Y w xY wc c}w )z}
        Copy properties of other into self and return PDF commands
        needed to transform *self* into *other*.
        Fr  Tr  )
commandsr  r   r   r   r  ru  anyr  setattr)
r   r  r  fill_performedparamscmd	differentpourstheirss
             r5   r  zGraphicsContextPdf.delta!
  sU   
 == 	8KFCI tQ' *	9|v~$($6	$($8	 " 33 	_,%)N5;<'%+<<C.v./ 8AD!WUA%6787	8: ' " 9::d+DZZ/F!%v||!; "8!#!7 9 =s   B:+D&:A&D#"D#c                     t         |   |       t        |d| j                        }t        |d| j                        }|| _        || _        y)z5
        Copy properties of other into self.
        r  r  N)r  ri  r  r  r  )r   r  r  r  r  s       r5   ri  z"GraphicsContextPdf.copy_propertiesG
  sL     	&E<A	"5*=#'#9#9;#!1r7   c                 z    g }| j                   ,|j                  | j                                | j                   ,|S )zB
        Make sure every pushed graphics state is popped.
        )r  r  r  )r   r  s     r5   r>  zGraphicsContextPdf.finalizeR
  s6     kk%KK
# kk%r7   )r   r   r   r   r   r3  r4  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  ri  r>  r  r  s   @r5   r  r  	  s    	>B9 Qa8Iq15J68(0$
103, 
$X.	99E	&	-(	-(	-(	x 	G	#Y/
H$L	2r7   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y)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       || _        y)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_emptyrd   s       r5   r   zPdfPages.__init__s
  sF    2 "!
*DKK7  /1 &r7   r  c                     | S r?   r   r   s    r5   	__enter__zPdfPages.__enter__
  s    r7   c                 $    | j                          y r?   )r@  )r   exc_typeexc_valexc_tbs       r5   __exit__zPdfPages.__exit__
  s    

r7   c                 ~    | j                   &t        | j                  | j                        | _         | j                   S )Nrd   )r  r  r  r  r   s    r5   _ensure_filezPdfPages._ensure_file
  s,    :: $..IDJzzr7   c                    | j                   <| j                   j                          | j                   j                          d| _         y| j                  r9t	        j
                  dd       t        | j                  | j                         yy)z_
        Finalize this object, making the underlying file a complete
        PDF file.
        Nr  r  r  r  )	r  r>  r@  r  r	   r  r  r  r  r   s    r5   r@  zPdfPages.close
  sl    
 ::!JJ!JJDJ  /1 DNNT^^<	 r7   c                 6    | j                         j                  S )z
        Return a modifiable information dictionary object
        (see PDF reference section 10.2.1 'Document Information
        Dictionary').
        )r  r  r   s    r5   infodictzPdfPages.infodict
  s       "+++r7   c                 \   t        |t              sR|t        j                         }nt        j                  |      }|t        d|       |j                  j                  }t        j                  |t        |            5   |j                  | fddi| ddd       y# 1 sw Y   yxY w)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 )canvasrg  r  )r@   r   r   
get_activeget_fig_managerr   r  figurer   _setattr_cmFigureCanvasPdfsavefig)r   r  kwargsmanagers       r5   r  zPdfPages.savefig
  s     &&)~..*--f5 :fX!677^^**Fvof.EF 	9FNN4888	9 	9 	9s   B""B+c                 H    t        | j                         j                        S )z=Return the current number of pages in the multipage pdf file.)r*   r  r  r   s    r5   get_pagecountzPdfPages.get_pagecount
  s    4$$&//00r7   r	  c                 D    | j                         j                  ||       y)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      r5   attach_notezPdfPages.attach_note
  s     	''l;r7   r?   )r   r   r   r   r  r  r   r	   deprecate_privatize_attributer  r  r  r  r@  r  r  r  r  r   r7   r5   r  r  \
  s]    ( XF,2T  &D 433E:J
=,9.1 .@ <r7   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 )	r   r  r  zPortable Document Formatc                      y)Nr  r   r   s    r5   get_default_filetypez$FigureCanvasPdf.get_default_filetype
  s    r7   N)bbox_inches_restorerd   c                   | j                   j                  }d| j                   _        | j                   j                         \  }}t        |t              r|j                         }nt        ||      }	 |j                  ||       t        | j                   |||t        ||||      |      }| j                   j                  |       |j                          t        |t              s|j                          t        |t              r|j                          y |j                          y # t        |t              r|j                          w |j                          w xY w)Nr  r  )r  )r  dpiget_size_inchesr@   r  r  r  r  r   rQ  drawr>  r  r@  )	r   r  r  rd   r  r~   r   r   renderers	            r5   	print_pdfzFigureCanvasPdf.print_pdf
  s    kkoo335vh)((*D8h7D	LL'(UFCD#vu5$79H KKX&h1(H- 

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

s   4BD* *3Ec                 T    | j                   j                          t        |          S r?   )r  draw_without_renderingr  r  )r   r  s    r5   r  zFigureCanvasPdf.draw  s    **,w|~r7   )	r   r   r   	fixed_dpi	filetypesr  r  r  r  r  s   @r5   r   r   
  s0     I23I '+T4 r7   r   c                       e Zd ZeZy)_BackendPdfN)r   r   r   r   FigureCanvasr   r7   r5   r  r  	  s    "Lr7   r  )K   )r   )`r   r   r   r   enumr   	functoolsr   ior   r   loggingry   rV   r  r  r  rq   ri  r  rj  numpyr   PILr   
matplotlibr]   r	   r
   r   r   r   matplotlib._pylab_helpersr   matplotlib.backend_basesr   r   r   r   r   !matplotlib.backends.backend_mixedr   matplotlib.figurer   matplotlib.font_managerr   r   rO  matplotlib._afmr   matplotlib.ft2fontr   r   r   r   r   r   matplotlib.transformsr   r    matplotlib.pathr!   matplotlib.datesr"   r#   r  r%   	getLoggerr   rU  r6   rk   rw   r   r   r   rA   	maketransr   r   r   r   rL   r  r  r[  r  r  RendererPDFPSBaserQ  r  r  r   FigureManagerPdfexportr  r   r7   r5   <module>r1     s       $     	   
        F F )  @ $ I L L 4      w"d,Tn0,"*04 }}
u5UD EF#R  .      B A# A#HZ$ Z$z+\@C @CF(t-/33 t-nJ, JZ< <D%& %P %  
#( # #r7   