
    G8c                       d Z ddlZddlmZ ddlmZ ddlmZ ddlmZ ddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlZddlmZmZmZmZmZ dd	lm Z  dd
l!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddlm?Z? ddl@mAZA  e
j                  eC      ZD ej                  dd      dAd       ZFdAdZGd ZHd ZIdBdZJdBdZKdBdZLeMj                  d d!d"d#d$d%      ZOd& ZPd' ZQ G d( d)      ZRe G d* d+             ZS ej                  d       G d, d-             ZT G d. d/      ZU G d0 d1e      ZV G d2 d3      ZWd4 ZX G d5 d6      ZY G d7 d8eAj                        Z[ G d9 d:e%      Z\ G d; d<      Z] G d= d>e#      Z^e$Z_e"j                   G d? d@e"             Zay)CuO   
A PDF Matplotlib backend.

Author: Jouni K Seppänen <jks@iki.fi> and others.
    N)datetime)Enum)total_ordering)BytesIO)Image)_api_text_helpers
_type1fontcbookdviread)Gcf)_BackendFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase)MixedModeRenderer)Figure)get_fontfontManager)AFM)FIXED_WIDTHITALICLOAD_NO_SCALELOAD_NO_HINTINGKERNING_UNFITTEDFT2Font)Affine2DBboxBase)Path)UTC)_path   )_backend_pdf_ps3.6za vendored copy of _fill)alternativec                     t        | |      S )N)linelen)_fill)stringsr(   s     A/usr/lib/python3/dist-packages/matplotlib/backends/backend_pdf.pyfillr,   _   s    '**    c                 "   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)r*   r(   currposlastiresultislengths           r+   r)   r)   d   s     GEF'" 1QVg%vz!GMM$))GE!$456EG MM$))GEFO,-::fr-   c           
         t        j                  d      }|r5t        j                  t	        |            }|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    r+   is_string_likez-_create_pdf_info_dict.<locals>.is_string_like   s    !S!!r-   zan instance of strc                 "    t        | t              S rB   )rC   r   rE   s    r+   is_datez&_create_pdf_info_dict.<locals>.is_date   s    !X&&r-   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rC   NamenamerE   s    r+   check_trappedz,_create_pdf_info_dict.<locals>.check_trapped   s(    a66<<<444r-   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 rW   )osgetenvr   utcfromtimestampintreplacer!   todaympl__version__itemstext_for_warningr   warn_externalsetrO   )backendmetadatasource_date_epochsource_dateinfokvrG   rI   rQ   keywordss              r+   _create_pdf_info_dictrm   z   s   @ 		"56//4E0FG!)))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   "
E%-E%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altzonetimezone)drzs      r+   _datetime_to_pdfrz      s     	


#$A	A}II==AAAv	S
 H	 
Q	]rdlaR4K888 H 	
]a4iT222Hr-   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)rF   ywidthheightangle	sin_angle	cos_angleabcrw   efs                r+   !_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++r-   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 .0rk   s     r+   	<genexpr>z,_get_coordinates_of_block.<locals>.<genexpr>
       '!'   c              3   &   K   | ]	  }|d      ywr#   Nr   r   s     r+   r   z,_get_coordinates_of_block.<locals>.<genexpr>  r   r   c              3   &   K   | ]	  }|d      ywr   r   r   s     r+   r   z,_get_coordinates_of_block.<locals>.<genexpr>  r   r   c              3   &   K   | ]	  }|d      ywr   r   r   s     r+   r   z,_get_coordinates_of_block.<locals>.<genexpr>  r   r   )r   minmaxtuple	itertoolschainfrom_iterable)rF   r   r   r   r   verticespadmin_xmin_ymax_xmax_ys              r+   _get_coordinates_of_blockr      s     1Au17@H RZ'QC'h''#-E'h''#-E'h''#-E'h''#-E)////9:E5%(* *r-   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   rO   get_url)	gcrF   r   r   r   r   
quadpointsrectlink_annotations	            r+   _get_link_annotationr     sd     1AufeLJW<e::<
	O rz(2%r-   z\\z\(z\)z\nz\r)\()
c                 B   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jA                  tC        |                   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 {} objects)"hasattrr   rC   floatnpfloatingisfinite
ValueErrorrstripboolr\   integerrD   isasciiencodecodecsBOM_UTF16_BEbytesdecode	translate_str_escapesdictr)   ra   rO   listr   r   rz   r   bounds	TypeErrorformattype)objrx   rj   rk   vals        r+   r   r   0  sR    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:: HS	*, 	,+ 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     r+   _font_supports_glyphr   y  s/     1}|2~~

r-   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 rB   idselfr   s     r+   __init__zReference.__init__  	    r-   c                      d| j                   z  S )Nz<Reference %d>r   r   s    r+   __repr__zReference.__repr__  s    $''))r-   c                      d| j                   z  S )Ns   %d 0 Rr   r   s    r+   r   zReference.pdfRepr  s    477""r-   c                 x    |j                   } |d| j                  z          |t        |              |d       y )N	   %d 0 obj
s   
endobj
)writer   r   )r   contentsfiler   s       r+   r   zReference.write  s1    

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

+BBr-   c                 X    t        |t              xr | j                  |j                  k  S rB   rN   r  s     r+   __lt__zName.__lt__  s!    %&A499uzz+AAr-   c                 ,    t        | j                        S rB   )hashrP   r   s    r+   __hash__zName.__hash__  s    DIIr-   r%   c                 :    dt        | j                               z  S )Nr  )ordgroup)matchs    r+   hexifyzName.hexify  s     U[[]+++r-   c                      d| j                   z   S )N   /r   r   s    r+   r   zName.pdfRepr  s    diir-   N)r   r   r   r   	__slots__ranger  r  r   r   r
  r  r  r  staticmethodr   
deprecatedr  r   r   r   s   00r+   rO   rO     s    I%%*(H%C#c(Q,*G(HHJ 'A+~ JGE'/CB T__U,  , ?Js   A5rO   c                   "    e Zd ZdZd Zd Zd Zy)Operatoropc                     || _         y rB   r"  )r   r#  s     r+   r   zOperator.__init__  r   r-   c                      d| j                   z  S )Nz<Operator %s>r"  r   s    r+   r   zOperator.__repr__  s    ((r-   c                     | j                   S rB   r"  r   s    r+   r   zOperator.pdfRepr      wwr-   N)r   r   r   r  r   r   r   r   r-   r+   r!  r!    s    I)r-   r!  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 rB   _x)r   rF   s     r+   r   zVerbatim.__init__  s	    r-   c                     | j                   S rB   r+  r   s    r+   r   zVerbatim.pdfRepr  r'  r-   N)r   r   r   r   r   r   r   r-   r+   r)  r)    s    Or-   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(  e)jT                  d'       e+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   shr%   c                     | j                   S rB   valuer   s    r+   <lambda>zOp.<lambda>  s
    djj r-   c                     | j                   S rB   rD  r   s    r+   r   z
Op.pdfRepr  s    zzr-   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stroker,   endpath)clsr,   rJ  s      r+   
paint_pathzOp.paint_path  s4     &zz!xx{{"r-   N)0r   r   r   r   close_fill_strokerI  r,   	closepathclose_strokerJ  rK  
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   r  propertyr#  r   classmethodrM  r   r-   r+   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		)@ A	BB # #r-   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   r2   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   r2   rs  fhr   rt  r   ru  copyupdaterO   
recordXrefr_   rcParamszlibr   _writeHeadertellrv  )r   r   r2   r   ru  pngs         r+   r   zStream.__init__,  s      GG	=DJDJ?JJd=.A.13 4 	(<<)*3#//./ 1D88	DIyy~~'DHr-   c                    | j                   j                  } |d| j                  z         | j                  }| j                  |d<   t
        j                  d   rt        d      |d<    |t        |              |d       y )Nr   Lengthr{  rx  ry  s   
stream
)	r   r   r   ru  r2   r_   r  rO   r   )r   r   r   s      r+   r  zStream._writeHeaderS  se    		mdgg%&zzX<<)*!-0DNgdmmr-   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
)_flushr2   r   getvaluers  r|  r  r   r  rv  writeObject)r   r   r:   s      r+   endz
Stream.end^  s     	88yy))+H8}DHDIIIOOH%IIOO45YY^^%0FIIOO45LL$$TXXv6r-   c                     | j                   | j                  j                  |       y| j                   j                  |      }| j                  j                  |       y)zWrite some data on the stream.N)rt  r   r   compress)r   data
compresseds      r+   r   zStream.writen  sF     #IIOOD!))2248JIIOOJ'r-   c                     | j                   =| j                   j                         }| j                  j                  |       d| _         yy)zFlush the compression object.N)rt  flushr   r   )r   r  s     r+   r  zStream._flushw  sA     '))//1JIIOOJ'#D (r-   NN)
r   r   r   r   r  r   r  r  r   r  r   r-   r+   rr  rr  #  s)     PI%(N	7 ($r-   rr  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)r9  r8  r-   r7  r3  Tr2  )r   units_per_EM
load_glyphr   r   arrayhoriAdvancebboxastyper\   get_pathnonzerosortedallpostscript_namer4   maprD   r   r"   convert_to_stringr    get_glyph_name)	font_path	glyph_idsfontconvprocsglyph_idgd1rk   r   quadsquads_onquads_mid_onimplicits                 r+   _get_pdf_charprocsr    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 Lr-   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rO   r   r8   s     r+   r   z#PdfFile.__init__.<locals>.<genexpr>       "MQ4!A3="M   c              3   8   K   | ]  }t        d |         yw)r   Nr  r  s     r+   r   z#PdfFile.__init__.<locals>.<genexpr>  s      K1!g Kr  c              3   8   K   | ]  }t        d |         yw)SMNr  r  s     r+   r   z#PdfFile.__init__.<locals>.<genexpr>  s     J!tbH~Jr  c              3   8   K   | ]  }t        d |         yw)HNr  r  s     r+   r   z#PdfFile.__init__.<locals>.<genexpr>  r  r  c              3   8   K   | ]  }t        d |         yw)INr  r  s     r+   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_filehandler  IOErrorr   r|  currentstreamr   reserveObject
rootObjectpagesObjectpageList
fontObject_extGStateObjecthatchObjectgouraudObjectXObjectObjectresourceObjectrO   r  rm   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   filenamerf   r|  openedr  rF   procsetsr  	__class__s
            r+   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  rO   r  r  r  r  r3   r  r  beginStreamr   outputr/  r]  r^  GraphicsContextPdf
joinstylesrb  )r   r   r   contentObjectannotsObjectthePage
pageObjects          r+   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  "r-   r!  r   r   c                 l    t        d      t        d      ||d}| j                  j                  |       y )Nr   Text)r   r   r  r   )rO   r  r3   )r   textpositionRecttheNotes       r+   newTextnotezPdfFile.newTextnote7  s3    ="6l#'
 	##G,r-   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 rB   )stringascii_uppercase)nbasetoStrs     r+   r.  z,PdfFile._get_subsetted_psname.<locals>.toStrA  sD    4x--a00 !t)T*V-C-CAH-MMr-   r#   r        +)r  	frozensetkeyssysmaxsize)r   ps_namecharmaphashedprefixr.  s        @r+   _get_subsetted_psnamezPdfFile._get_subsetted_psname@  sU    	 i/0S[[1_4IJvr" bqzC'))r-   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  ra   r  r  r  writeImageswriteMarkerswritePathCollectionTemplatesr  rO   r  r2   writeInfoDict	writeXrefwriteTrailer)r   imagerP   obxobjectstuprE  pathtransr4   cappaddingfilledstrokeds                 r+   finalizezPdfFile.finalizeP  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  r|  r  r  r   r  closer   s    r+   rW  zPdfFile.closeq  s^     	%%GGMMO&&2''--dgg.>.>.@AGGMMOr-   c                     | j                   | j                  j                  |       y | j                   j                  |       y rB   )r  r|  r   )r   r  s     r+   r   zPdfFile.write|  s2    %GGMM$$$T*r-   c           
          | j                  t        |D cg c]  }t        |       c}             | j                  d       y c c}w )Nr0   )r   r)   r   )r   r  rF   s      r+   r  zPdfFile.output  s3    

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

5 4s   Ac                 H    | j                   J t        ||| ||      | _         y rB   )r  rr  )r   r   r2   ru  r  s        r+   r  zPdfFile.beginStream  s)    !!)))#BT5#>r-   c                 `    | j                   "| j                   j                          d | _         y y rB   )r  r  r   s    r+   r  zPdfFile.endStream  s-    )""$!%D *r-   ru  c                    | j                  |j                  d |       | j                  j                  |       | j	                          y rB   )r  r   r  r   r  )r   refr  ru  s       r+   outputStreamzPdfFile.outputStream  s6    u-  &r-   c                 P    | j                   D ]  \  }}| j                  ||        y rB   )r  r  )r   r  r  s      r+   r>  zPdfFile._write_annotations  s,    )-):): 	8%L+\;7	8r-   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)rC   rD   r_   r  _fontManager_find_fonts_by_propsRendererPdf_afm_font_dirr  getnextr  _logdebug)r   fontprop	filenamesfirst_FxfnameFxs         r+   fontNamezPdfFile.fontName  s     h$!
I\\./$99%;3L3LI %99(CI 		"E##E*Bz$112(*u%

3R?!H		" r-   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  rj  texnamerv  r   
PsfontsMap_find_tex_filer  r   r   psnamerk  r  rl  rm  typesSimpleNamespaceencodingrz  )r   ru  dvi_infotex_font_mappsfontrv  s         r+   dviFontNamezPdfFile.dviFontName  s     ##''8###))'*@*@*NOgoo.??"5w79 9
 t../

17GOOL,1,A,A__]]NN-$) r-   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  ra   rv  rl  rm  _embedTeXFontr  endswith_write_afm_fontr  usedrj  embedTTFr  r  )r   r  dvinameri   rr  r  charss          r+   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	? 	%0r-   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_fontnamerO   r  r  )r   r  r|  r  fontnamefontdictfontdictObjects          r+   r  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  r  r   r#   )r   r   	FirstCharLastCharWidthsr  r   DifferenceszBecause of TeX configuration (pdftex.map, see updmap option pdftexDownloadBase14) the font %s is not embedded. This is deprecated as of PDF 1.5 and it may cause the consumer application to show something that was not intended.r  FontNameslant        extend      ?FontDescriptor)rl  rm  ru  r{  __dict__r  r  widthsrO   r2   ry  r  r   
_parse_encrw  warningrx  r
   	Type1Fontrz  	transformproprj  r  createType1Descriptor)r   fontinfowidthsObjectr  r  t1fontrz  fontdescs           r+   r  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r-   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StemVr-   )Length1Length2Length3r\  )r  r  r   rO   r  ascender	descenderr  r_  r4   partsr2   )
r   r  rw  fontdescObjectfontfileObjectitalic_anglefixed_pitchflagsft2font
descriptors
             r+   r  zPdfFile.createType1Descriptor0  sQ    ++,=>++K8{{=1kk.1VOE VOE
 VOE   8$   01J 78 "<<'"++",,)!;;|4
" 	4.#((6<<3C*D,/Q,@,/Q,@,-!/ 	 	0
 r-   c                     | j                  |      }dj                  |j                  j                         t        j
                  j                  t        j
                  j                  |            d   |g      S )N-r   )rs  r4   rP   r   rY   rO  splitextbasename)r   r  
glyph_namerr  s       r+   _get_xobject_glyph_namezPdfFile._get_xobject_glyph_nameo  s]    ]]8$xxGGNNGGRWW--h78;  	r-   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  r|   floorceil)r:   upenearestrE  s       r+   cvtzPdfFile.embedTTF.<locals>.cvt  sB    SL4'EU|#qyzz%((yy''r-   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   rO   r  
FontMatrix	CharProcsr  r  r   )cp1252c                     t        j                  |          }j                  |t        t        z        j
                  } |      S )Nr  )r  decoding_table	load_charr   r   r  )charcoder9   r   r  r  r  s      r+   get_char_widthz?PdfFile.embedTTF.<locals>.embedTTFType3.<locals>.get_char_width  sG    --h78]_< ' >>Ik 5z!r-   ignorer#   NMaxWidthr   r  Formr   r   BBox   d1r  charProcr\  )r  r  rO   	encodingsr  warningscatch_warningsfilterwarningsr  r   rd   get_char_indexr3   r  addsortr  r  findr_  r  r  r  )$r  
charactersr  r  r  r  charprocsObjectdifferencesArray	firstcharlastcharrF   r  r  r  r  r  r  differencesmulti_byte_charsr   ccodegindr  last_crP   rawcharprocs	charprocscharnamestreamcharprocDictcharprocObjectr  r  r  r6  r   s$   `                              @r+   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rB   )chrr  s     r+   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  r\   i   r  Nr#   r  r  r   s   <%04x> <%04x> [%s]r/   c              3   &   K   | ]	  }d |z    yw)s   <%04x>Nr   )r   rF   s     r+   r   z;PdfFile.embedTTF.<locals>.embedTTFType42.<locals>.<genexpr>f  s     Jy1}Jr   r0   Fr  r  r  r  r  r  r  utf-16ber  )%r  r4   rl  rm  r$   get_glyphs_subsetrY   statst_size	getbuffernbytesr   rO   r_  r  r  r  r   r   r3   r  r  r   r  r   r  _identityToUnicodeCMapr2   r   r  r  r  r  r  r  r   r  )-r  r  r  r  cidFontDictObjecttype0FontDictObjectcidToGidMapObjectr  wObjecttoUnicodeMapObject
subset_strfontdata	full_fontcidFontDicttype0FontDictcid_to_gid_mapr  	max_ccoder   r  r  r   
last_ccodew	max_widthunicode_groupsr   unicode_bfrangestartr  unicode_cmapr  rF   r  r  r  r  r	  r
  rP   r  r  r   r6  r   s-                                           r+   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_   r  r  r:  r  get_charmapr   rO   get_sfnt_table
face_flagsstyle_flagsr   r   r  r  r  )r   r  r  r  r  r9  r:  r=  ffsfr  symbolicrF   r  r  r   r6  s   ``            @@@r+   r  zPdfFile.embedTTF  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  rj  rk  r  rO   )r   alphastaterP   s       r+   
alphaStatezPdfFile.alphaState  ss       $$UD18OD))*D-(%(4 5 	 r-   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  rj  rk  r  r  rO   r  r3   r/  rn  )r   smaskrL  rP   groupObs        r+   _soft_mask_statezPdfFile._soft_mask_state  s    &&**5$78OD''($$%GH[) Ll+# 		)
u% 	%%Y<n-|, -'#u6$ #Y

#'
 	  r-   c                     | j                  | j                  t        g | j                  j	                         | j
                  j	                                      y rB   )r  r  r   r  rD  r  r   s    r+   r@  zPdfFile.writeExtGSTates	  sT    !! !!((*''..0 	
r-   c                     | j                   D ]B  \  }}}| j                  |j                  d |        | j                  |  | j	                          D y rB   )r  r  r   r  r  )r   rL  
attributescontents       r+   rA  zPdfFile._write_soft_mask_groups  sL    '+'='= 	#B
GRUUD*5DKK!NN	r-   c                     |%|\  }}}|t        |      }|t        |      }|||f}| j                  j                  |d       }||S t        | j                        }|| j                  |<   |S rB   )r   r  rj  rk  r  )r   hatch_styleedgefacehatchpatternrP   s          r+   hatchPatternzPdfFile.hatchPattern  s    " +D$T{T{u-K$$((d;ND++,*.;'r-   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  rZ  r  zhatch.linewidthFsimplify)r   r  ra   r  r  rO   r  r   r   r  r/  r[  r\  rT  r,   r_   r  rl  pathOperationsr    rf  r   scalerI  r  r  r  )r   	hatchDictsidelenrc  rP   rL  rF   res
stroke_rgbfill_rgbrf  s              r+   rB  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 )rO   r2   r  r  r3   )r   pointscolorsrP   rL  s        r+   addGouraudTriangleszPdfFile.addGouraudTrianglesP  s\    $ FS!6!6778"3D6 :;$$dB%?@Rxr-   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  rV  F)ShadingTypeBitsPerCoordinateBitsPerComponentBitsPerFlag
ColorSpace	AntiAliasDecode)r  u1)r{  z>u4)r  r|  r  )dtyper  r{  g     o@)r   r  shapereshaper   r   r   r  r   rO   emptyr   tobytesr  r  r  )r   gouraudDictrP   rL  r{  r|  r  flat_pointscolordimflat_colors
points_min
points_maxfactor	streamarrs                 r+   rC  zPdfFile.writeGouraudTrianglesg  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 	++[9r-   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  rj  r   rk  r  r  )r   rK  entryrP   rL  s        r+   imageObjectzPdfFile.imageObject  so       ED18ODOO$&0#($"3RYr-   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  r  r  )r   imrgbrK  s       r+   _unpackzPdfFile._unpack  s     "X77a<t8OQ2A2X,C((3c*Cxx{a1a7I.66%3,' E
 : HHU#6E : :r-   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.
        r  )r   r  r-   Ns   !L4s)   IHDR   PLTE   IDATztruncated datar  r  r  s   IENDr#   r  )	r   saveseekstructunpackreadr2   RuntimeErrorr\   )	r   imgbufferpng_data	bit_depthpaletter:   r   r  s	            r+   	_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++r-   c           	         |j                   \  }}}t        d      t        d      ||t        ddd|         dd}|r||d<   t        j                  d	   r|j                   d
   dk(  r|j	                  d
      }t        j                  |      }|j                  d      }	|dk(  r|	t        |	      }
t        t
        dt
              j                  }t        t
        dt
              j                  }|j                  d|||
      }| j                  |      \  }}}||t        d      |d|
dz   }t        d|
dz
  t!        |      fz        |d<   ||d<   d}n| j                  |      \  }}}d||d}nd}| j#                  || j%                  d      ||       |r| j&                  j)                         n)| j&                  j)                  |j+                                | j-                          y)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   rV  r  r#   r   r  )r   r   WidthHeightr  r  rT  r{  r  r#   r  r  )	maxcolorsr   NDitherPaletteP)modeditherr  r|  zinvalid PNG headers   [/Indexed /DeviceRGB %d %s]r  r  
   )	PredictorColorsColumnszlength of image stream)r  )r  rO   r_   r  squeezer   	fromarray	getcolorsr2   getattrNONEADAPTIVEconvertr  r  r)  r   r  r  r  r   r  r  )r   r  r   r[  r   r   color_channelsr   r  
img_colors
num_colorsr  pmoder  r  r  _r  s                     r+   	_writeImgzPdfFile._writeImg  s	    )-

%~Iw-!l&1#33A#C D#$&  CL<<)*zz"~"|||,//$'C5J"z'= !_
 !%8==y%8AAkkVU: "  04~~c/B,)W$&';<<!/:>2$,2!A~ww'789%:L! +4&'!"!%!4!Q "nOCC78	 	 	 $$X.$$T\\^4r-   c                    | j                   j                         D ]i  \  }}}| j                  |      \  }}|.| j                  d      }| j	                  ||j
                         nd }| j	                  ||j
                  |       k y )Nr[  )r  rD  r  r  r  r   )r   r  rP   rL  r  adatasmaskObjects          r+   rE  zPdfFile.writeImages  sw    !\\002 	5MCr,,s+KD% "009uknn5"NN44	5r-   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.Frq  zM%dz	marker %dr  r   )	rs  r   r   r   rj  rO   r2   r  get_extents)r   rO  rP  r,   rJ  lw	joinstylecapstylepathopskeyr7   rP   rL  r  s                 r+   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r-   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   ra   paddedr  r   rO   r   extentsr  r  r  r/  rb  	capstylesrc  rM  r  )
r   r  r,   rJ  r  r  rP   rL  r  r  s
             r+   rF  zPdfFile.writeMarkers5  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'	r-   c                    t        dt        | j                        z        }| j                  dt        | j                        z        }| j                  j	                  |||||j                         |j                         |||f	       |S )NzP%dzpath %d)rO   r2   r  r  r3   get_joinstyleget_capstyle)	r   r   rO  rP  rR  rS  rT  rP   rL  s	            r+   pathCollectionObjectzPdfFile.pathCollectionObjectK  sx    EC

O+,	C

O ;<

4B$4$4$68Ifg'	( r-   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 )NFrq  r   r   r   r   r  r  r  )r  rs  r  r   r  r   r  r  r   r  r   rO   r  r  r  r/  rb  r  rc  rM  r  )r   rP   rO  rP  rL  r  r  rR  rS  rT  r  r  r  s                r+   rG  z$PdfFile.writePathCollectionTemplatesS  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%	r-   c                    t        t        j                  | ||||dt        j                  j
                  t        j                  j
                  dt        j                  j
                  t        j                  j
                  gd            gS )Nr0  r-   T)	r)  r"   r  r/  rV  rE  rU  rS  rO  )rO  r  rm  rr  sketchs        r+   rs  zPdfFile.pathOperationsh  sg    00)T8VYY__biioosBJJ4D4D\\!   	r-   c                     |r-dd| j                   dz  | j                  dz  f}|j                  }nd }d}| j                  |||||      } | j                  |  y )Nr  r  F)rr  r  )r   r   should_simplifyrs  r  )r   rO  r  rm  r  rr  cmdss          r+   	writePathzPdfFile.writePathq  sg    djj2ot{{R/?@D++HDH""4D8*0 # 2Tr-   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   )rk  r  r  r3   r   )r   rP   r   s      r+   r  zPdfFile.reserveObject|  s6     $""#tQo.}r-   c                 r    | j                   j                         | j                  z
  | j                  |   d<   y Nr   )r|  r  r  r  r   s     r+   r  zPdfFile.recordXref  s(     $ ?r1r-   c                 ^    | j                  |j                         |j                  ||        y rB   )r  r   r   )r   objectr   s      r+   r  zPdfFile.writeObject  s     		"Xt$r-   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  r2  r6  s   %010d %05d %b 
)	r|  r  r  	startxrefr   r2   r  r1   AssertionError)r   r8   offset
generationrP   r  r$  s          r+   rI  zPdfFile.writeXref  s    $..8

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

4 	!r-   c                 |    | j                  d      | _        | j                  | j                  | j                         y)z8Write out the info dictionary, checking it for good formri   N)r  
infoObjectr  r  r   s    r+   rH  zPdfFile.writeInfoDict  s.     ,,V4$--8r-   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   r2   r  r  r  r  r   s    r+   rJ  zPdfFile.writeTrailer  sZ     	

< 

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

04>>ABr-   rB   r  )NNNFN)r  )4r   r   r   r   r   r  r'  r:  rU  rW  r   r  r  r  r_  r>  rs  r  r?  r  r  r  r  r%  r  rM  r]  r@  rA  rh  rB  r}  rC  r  r  r  r  rE  r  rF  r  rG  r  rs  r  r  r  r  rI  rH  rJ  __classcell__r	  s   @r+   r  r    s   g9R": .@ -* B	+?&
 04 
8><1*
8t=~*{@z	2h
$$6L.*:X
.,:9v5:,*  		@%!9	Cr-   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 )rh  zfonts/pdfcorefontsrb  c                 l    t         |   ||       || _        | j                         | _        || _        y rB   )r  r   r   new_gcr   	image_dpi)r   r   r  r   r   r	  s        r+   r   zRendererPdf.__init__  s-    '	++-"r-   c                 f     | j                   j                  | j                  j                           y rB   )r   r  r   rU  r   s    r+   rU  zRendererPdf.finalize  s#    		$''**,-r-   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  )r  r   get_rgbset_foreground_forced_alpha_alphar  r2   _rgbr   deltar   r  )r   r   	fillcolor	orig_fillorig_alphasr
  s         r+   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$ "*r-   c                      | j                   dz  S )Nrj  )r  r   s    r+   get_image_magnificationz#RendererPdf.get_image_magnification  s    ~~d""r-   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  rj  r#   )r  	set_alphar  r  r   r  r  r/  re  rW  rX  rf  frozen	to_values)r   r   rF   r   r  r  hr3  imobtr1tr2tr3tr4tr5tr6s                  r+   
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;;@r-   c                    | j                  ||       | j                  j                  |||d u xr |j                         d u |j	                                | j                  j                  | j                  j                                y rB   )r  r   r  get_hatch_pathget_sketch_paramsr  r   paint)r   r   rO  r  rgbFaces        r+   	draw_pathzRendererPdf.draw_path  sk    b'"		)tO; 1 1 3t ;  "	$ 			)r-   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   asarrayr2   	get_hatchr  r   _iter_collection_uses_per_pathr   draw_path_collectionr   r1   _iter_collection_raw_pathsr   r  r3   r  r   push_iter_collectionr  r/  rW  rX  pop)$r   r   master_transformr  all_transformsoffsetsoffset_trans
facecolors
edgecolors
linewidths
linestylesantialiasedsurlsoffset_positioncan_do_optimizationrS  rT  len_pathuses_per_pathshould_do_optimizationrR  
path_codesr8   rO  r  rP   r  lastxlastyxoyopath_idgc0r"  dxdys$                                       r+   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		" 	r-   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)rm  rr  r  r#   )r2   r   draw_markersr  r,   rJ  r   r  r  r   
_linewidthr  r  r/  re  iter_segmentsr   r   rW  rX  rf  )r   r   marker_pathmarker_transrO  rP  r"  len_marker_pathusesr,   rJ  r  markerr=  r>  r   coderF   r   rC  rD  s                        r+   rF  zRendererPdf.draw_markersF  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{{r-   c                 h    | j                  ||j                  d      |j                  d      |       y )N)r#   r   r  )r#   r   r  )draw_gouraud_trianglesr  )r   r   r{  r|  rP  s        r+   draw_gouraud_trianglez!RendererPdf.draw_gouraud_trianglel  s,    ##By(A$*NN9$=u	Fr-   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  r  r  )r   r   r   )r2   r  r  r  r  r   r}  r  r  r  r/  rn  r   allcloser]  re  rd  rf  )r   r   r{  r|  rP  r  tpointsrP   r  r  rK  smask_obgstates                r+   rP  z"RendererPdf.draw_gouraud_trianglesp  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\\;; r-   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/  rg  r|   r}   r   r~   ri  )r   rF   r   r   oldxoldyoldangles          r+   _setup_textposzRendererPdf._setup_textpos  s    H!!IIQXq4x<LL'EIITXXe_dhhuo"hhuo-txx2==2 IIQ2::.r-   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  r3   r   r_   r  r|   r}   r  r/  re  r   r~   rW  r  r	  rQ  r  track_glyphrq  r   r[  rs  rh  encode_stringr  rj  rR  _draw_xobject_glyphr  rT  r,   rf  )r   r   rF   r   r9   r  r   r   r   descentglyphsrectsr   r   	prev_fontrX  rY  unsupported_charsr  fontsizenumoxoyr  s                           r+   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
 			%r-   )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  r3   r   r   r   r$  r  sizer   r2   absr   
rotate_degr   r  r	  r  r/  rQ  rh  r  r[  rj  rk  rR  r  copy_propertiesset_linewidthr    MOVETOLINETO	CLOSEPOLYboxesr#  )#r   r   rF   r   r9   r  r   rm  
texmanagerrh  dvifiledvir  oldfontseqx1y1ru  r   r   rv  r8   curxeltnxtr  mytranscuryrX  rY  boxgcr  r  r3  rO  s#                                      r+   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   r9   r   s      r+   ra  zRendererPdf.encode_string+	  s,    v88Hi00xx
I..r-   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 )Nrb  r#   r  r  r  )r   r   T)	kern_moder  Fr   ir  )4r  r	  rl  rp  r_   r  _get_font_afm_get_font_ttfr   r  trackr   set_textget_width_heightr  r3   r   r  r/  rQ  rs  rh  r[  ra  rj  rR  r	   layoutr   r   r  char	ft_objectrF   	prev_kern	glyph_idxre  r|   r}   r   r~   rW  rq  r   groupbyr   r   rk  r4   rk  rb  rf  )r   r   rF   r   r9   r  r   ismathrm  rh  r  r   r   r   singlebyte_chunksmultibyte_glyphsprev_was_multibyterf  itemr   prev_start_xr  start_xkerns_or_charsft_nametpr  r  s                               r+   	draw_textzRendererPdf.draw_text0	  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  rq  r  r/  re  rW  rO   rX  rf  )r   r  rh  r  rF   r   r  rP   s           r+   rb  zRendererPdf._draw_xobject_glyph	  sx    ((3
yy00ZH		HHHaEH$4aB<L<LJKK		
r-   c                 ,    t        | j                        S rB   )r  r   r   s    r+   r  zRendererPdf.new_gc	  s    !$)),,r-   rB   r   r  )r   r   r   r   _get_data_pathri  _use_afm_rc_namer   rU  r  r  r  r#  r(  rF  rQ  rP  r[  rl  r  ra  r  rb  r  r  r  s   @r+   rh  rh    s    (E(()=>M+#.+6#@<*DN "$LF& P/4&l ;? Q:f/
b*H	
-r-   rh  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     r+   r   zGraphicsContextPdf.__init__	  s+    )!+	r-   c                 N    t        | j                        }|d= |d= t        |      S )Nr   r  )r   r  repr)r   rw   s     r+   r   zGraphicsContextPdf.__repr__	  s'    fIhKAwr-   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  )rG  r  r2   r	  r   s    r+   rJ  zGraphicsContextPdf.stroke	  sK     !# =a =TYY1$;		!(;	>r-   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  )r2   r   _hatch)r   argsr   s      r+   r,   zGraphicsContextPdf.fill	  sX     t9aJJ A4' @j/Q&>*Q-3*>	Br-   c                 f    t         j                  | j                         | j                               S )zo
        Return the appropriate pdf operator to cause the path to be
        stroked, filled, or both.
        )r/  rM  r,   rJ  r   s    r+   r!  zGraphicsContextPdf.paint	  s!    
 }}TYY[$++-88r-   r   r#   r  )buttr  
projecting)miterr  bevelc                 @    | j                   |   t        j                  gS rB   )r  r/  rc  r   styles     r+   capstyle_cmdzGraphicsContextPdf.capstyle_cmd	  s    u%r}}55r-   c                 @    | j                   |   t        j                  gS rB   )r  r/  rb  r  s     r+   joinstyle_cmdz GraphicsContextPdf.joinstyle_cmd	  s    &77r-   c                 &    |t         j                  gS rB   )r/  rl  )r   r   s     r+   linewidth_cmdz GraphicsContextPdf.linewidth_cmd	  s    r''r-   c                 P    |\  }}|g }d}t        |      |t        j                  gS r  )r   r/  ra  )r   dashesr  dashs       r+   dash_cmdzGraphicsContextPdf.dash_cmd	  s/    <DFT
FBJJ//r-   c                 \    | j                   j                  |      }|t        j                  gS rB   )r   rM  r/  rd  )r   rK  forcedeffective_alphasrP   s        r+   	alpha_cmdzGraphicsContextPdf.alpha_cmd	  s&    yy##$45bll##r-   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_cmdrO   r/  r^  r   rh  r`  )r   rf  hatch_colorrc  rP   s        r+   	hatch_cmdzGraphicsContextPdf.hatch_cmd	  s    *))$//::[)2+E+EFF&?K99))+6DOR%?%?"//1 1r-   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_   r  r/  rY  r[  r   r  s     r+   rgb_cmdzGraphicsContextPdf.rgb_cmd	  s^    <<*+Iq6SV%s1v%FB--../S!W/b..//r-   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_   r  r/  rZ  r\  r  s     r+   r  z GraphicsContextPdf.fillcolor_cmd	  sb    ;#,,'9:IVs1v'Q'FB00112S!W2b1122r-   c                     t        | j                        }|j                  |        | j                  |_        || _        t        j
                  gS rB   )r  r   rv  r  r/  re  )r   r  s     r+   r*  zGraphicsContextPdf.push
  s<    #DII.t$zr-   c                     | j                   J | j                  | j                          | j                   j                   | _         t        j                  gS rB   )r  rv  r/  rf  r   s    r+   r,  zGraphicsContextPdf.pop
  sA    {{&&&T[[)kk((}r-   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()`.Frq  )	_cliprect	_clippathr  r  r,  r*  r/  rT  rm  rK  get_transformed_path_and_affiner  rs  )r   cliprectclippathr  rO  affines         r+   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)*+ r-   )r  r  )r  r  r  )	_capstyler   )
_joinstyle)rG  )_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 )zy
        Copy properties of other into self and return PDF commands
        needed to transform self into other.
        Fr  Tr  )
commandsr  r   r   r   r%  r  anyr  setattr)
r   r  r  fill_performedparamscmd	differentpourstheirss
             r+   r
  zGraphicsContextPdf.delta6
  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  rv  r  r   r  )r   r  r  r  r	  s       r+   rv  z"GraphicsContextPdf.copy_properties\
  sL     	&E<A	"5*=#'#9#9;#!1r-   c                 z    g }| j                   ,|j                  | j                                | j                   ,|S )zB
        Make sure every pushed graphics state is popped.
        )r  r  r,  )r   r  s     r+   rU  zGraphicsContextPdf.finalizeg
  s6     kk%KK
# kk%r-   )r   r   r   r   r   rJ  r,   r!  r  r  r  r  r  r  r  r  r  r  r*  r,  r  r  r
  rv  rU  r  r  s   @r+   r  r  	  s    	>B9 Qa8Iq15J68(0$
103, 
$X.	99E	&	-(	-(	-(	x 	G	#Y/
H$L	2r-   r  c                   P    e Zd ZdZdZd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.
    )_file
keep_emptyNc                 6    t        ||      | _        || _        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 at once and any older file with the
            same name is overwritten.

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

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

            The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
            'Creator', 'Producer', 'CreationDate', 'ModDate', and
            'Trapped'. Values have been predefined for 'Creator', 'Producer'
            and 'CreationDate'. They can be removed by setting them to `None`.
        rf   N)r  r  r  )r   r  r  rf   s       r+   r   zPdfPages.__init__
  s    2 X9
$r-   c                     | S rB   r   r   s    r+   	__enter__zPdfPages.__enter__
  s    r-   c                 $    | j                          y rB   )rW  )r   exc_typeexc_valexc_tbs       r+   __exit__zPdfPages.__exit__
  s    

r-   c                 J   | j                   j                          | j                   j                          | j                         dk(  rU| j                  sI| j                   j
                  s3t        j                  | j                   j                  j                         d| _         y)z_
        Finalize this object, making the underlying file a complete
        PDF file.
        r   N)
r  rU  rW  get_pagecountr  r  rY   remover|  rP   r   s    r+   rW  zPdfPages.close
  si    
 	



 A%dooJJ44IIdjjmm(()
r-   c                 .    | j                   j                  S )z
        Return a modifiable information dictionary object
        (see PDF reference section 10.2.1 'Document Information
        Dictionary').
        )r  r  r   s    r+   infodictzPdfPages.infodict
  s     zz"""r-   c                 j   t        |t              s^|t        j                         }nt        j                  |      }|t        dj                  |            |j                  j                  }	 |j                  }t        |      |_         |j                  | fddi| ||_        y# |_        w 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 {}r   r  )rC   r   r   
get_activeget_fig_managerr   r   canvasfigureFigureCanvasPdfsavefig)r   r  kwargsmanagerorig_canvass        r+   r  zPdfPages.savefig
  s     &&)~..*--f5 !6!6v!>??^^**F	( --K+F3FMFNN4888'FMKFMs   01B) )	B2c                 @    t        | j                  j                        S )z=Return the current number of pages in the multipage pdf file.)r2   r  r  r   s    r+   r  zPdfPages.get_pagecount
  s    4::&&''r-   r   c                 <    | 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      r+   attach_notezPdfPages.attach_note
  s     	

t\2r-   )TNrB   )r   r   r   r   r  r   r  r  rW  r  r  r  r	  r   r-   r+   r  r  q
  s<    & (I%8
#(6( .@ 3r-   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    r+   get_default_filetypez$FigureCanvasPdf.get_default_filetype
  s    r-   N)bbox_inches_restorerf   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_inchesrC   r  r  r  r  r   rh  drawrU  r  rW  )	r   r  r  rf   r  r   r   r   renderers	            r+   	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   0BD& &3Ec                 T    | j                   j                          t        |          S rB   )r  draw_without_renderingr  r  )r   r	  s    r+   r  zFigureCanvasPdf.draw	  s    **,w|~r-   )	r   r   r   	fixed_dpi	filetypesr  r  r  r  r  s   @r+   r  r  
  s0     I23I '+T4 r-   r  c                       e Zd ZeZy)_BackendPdfN)r   r   r   r  FigureCanvasr   r-   r+   r  r    s    "Lr-   r  )K   )r   )br   r   r   enumr   	functoolsr   ior   r   loggingr|   rY   r*  r  r4  rs   r  r  r  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   rf  matplotlib._afmr   matplotlib.ft2fontr   r   r   r   r   r   matplotlib.transformsr   r   matplotlib.pathr    matplotlib.datesr!   r"   r  r$   	getLoggerr   rl  r  r,   r)   rm   rz   r   r   r   rD   	maketransr   r   r   r   rO   r!  r)  r/  rr  r  r  RendererPDFPSBaserh  r  r  r  FigureManagerPdfexportr  r   r-   r+   <module>r2     s      $     	   
        F F )  @ $ I L L 4      w"d $>?+ @+,Tn0,"*04 }}
u5UD EF,R  . #  #  # L 
 
 
 C# C#LZ$ Z$z+\|C |C~'t-/33 t-nJ, JZr3 r3j%& %P %  
#( # #r-   