U
    \Sh;                     @  s  d 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m	Z	 ddlm
Z
 ddlmZ ddlmZ ddlmZ ddlZdd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZmZ ddlmZm Z  ddl!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z, e-e.Z/e	0eddZ1dZ2G dd deZ3G dd deZ4dZ5e6dZ7e6dZ8e6dZ9d d!d"d#d$Z:d d%d&d'd(d)Z;d[d d d+d d d,d-d.Z<d/d d0d1d2Z=d d/d d3d4d5Z>d6d d7d8d9d:Z?d d/d d!d;d<d=Z@d d/d d!d;d>d?ZAd@d dAdBdCdDZBd d d dEdFdGZCdHdId&dJdKdLZDd@dMd dNdOdPZEd@dQd&dNdRdSZFd@dTd&dNdUdVZGdHdWdXdYdZZHdS )\z*Render math in HTML via dvipng or dvisvgm.    )annotationsN)path)CalledProcessError)Any)nodes)Element)package_dir)Sphinx)Builder)Config)SphinxError)___)loggingsha1)get_node_equation_numberwrap_displaymath)	ensuredir)read_png_depthwrite_png_depth)LaTeXRenderer)HTML5TranslatorZ	templatesimgmath c                      s.   e Zd ZdZd	ddddd fddZ  ZS )
MathExtErrorzMath extension errorNstrz
str | NoneNone)msgstderrstdoutreturnc                   s0   |r|d| 7 }|r |d| 7 }t  | d S )Nz

[stderr]
z

[stdout]
)super__init__)selfr   r   r   	__class__r   E/root/rtd-docs/venv/lib/python3.8/site-packages/sphinx/ext/imgmath.pyr"   )   s
    zMathExtError.__init__)NN)__name__
__module____qualname__categoryr"   __classcell__r   r   r$   r&   r   &   s      r   c                   @  s   e Zd ZdZdS )InvokeErrorzerrors on invoking converters.N)r'   r(   r)   __doc__r   r   r   r&   r,   3   s   r,   )pngsvgz\[\d+ depth=(-?\d+)\]z.*, depth=(.*)ptz<!-- DEPTH=(-?\d+) -->r   z
int | None)filenamer    c              
   C  sX   t | ddB}|D ]}qt|}|r@t|dW  5 Q R  S W 5 Q R  dS Q R X dS )z9Read the depth from comment at last line of SVG file
    utf-8encoding   N)opendepthsvgcomment_rematchintgroup)r0   flinematchedr   r   r&   read_svg_depth>   s    
r=   r8   r   )r0   depthr    c              	   C  s,   t | ddd}|d|  W 5 Q R X dS )z<Write the depth to SVG file as a comment at end of file
    ar1   r2   z
<!-- DEPTH=%s -->N)r5   write)r0   r>   r:   r   r   r&   write_svg_depthK   s    rA    r   )image_formatmathconfigconfdirr    c                 C  s   |j tt|j d |j| dkr$dnd|d}|jr:d}nd}|jD ].}t|||}t|rDt	 
||  S qDt	t
||S )zGenerate LaTeX macro.g333333?r.   rB   z,dvips,tightpage)ZfontsizeZbaselineskippreambleZ	tightpagerD   zpreview.tex_tztemplate.tex_t)imgmath_font_sizer8   roundimgmath_latex_preambleimgmath_use_previewtemplates_pathr   joinexistsr   render)rC   rD   rE   rF   	variablesZtemplate_nameZtemplate_dirtemplater   r   r&   generate_latex_macroR   s    


rR   r
   )builderr    c                 C  s   t | dst | _| jS )zCreate temporary directory.

    use only one tempdir per build -- the use of a directory is cleaner
    than using temporary files, since we can clean up everything at once
    just removing the whole directory (see cleanup_tempdir)
    _imgmath_tempdir)hasattrtempfilemkdtemprT   )rS   r   r   r&   ensure_tempdirn   s    

rX   )latexrS   r    c              
   C  s,  t |}t|d}t|ddd}||  W 5 Q R X t|jj}|jjg}|dkrb|d |	|jj
 |d z<tj|d|ddd	 |d
krt|dW S t|dW S W np tk
r } zttd|jj t|W 5 d}~X Y n6 tk
r& } ztd|j|j|W 5 d}~X Y nX dS )z%Compile LaTeX macros for math to DVI.zmath.texwr1   r2   )tectonicz--interaction=nonstopmodeTascii)capture_outputcwdcheckr3   )Zxelatexr[   zmath.xdvzmath.dvizYLaTeX command %r cannot be run (needed for math display), check the imgmath_latex settingNzlatex exited with error)rX   r   rM   r5   r@   basenamerE   imgmath_latexappendextendimgmath_latex_args
subprocessrunOSErrorloggerwarningr   r,   r   r   r   r   )rY   rS   tempdirr0   r:   Zimgmath_latex_namecommandexcr   r   r&   compile_math{   s0    



rm   z	list[str]ztuple[str, str])rk   namer    c              
   C  s   z t j| dddd}|j|jfW S  tk
r` } z"ttd|| d | t|W 5 d}~X Y n8 t	k
r } zt
d| |j|j|W 5 d}~X Y nX dS )z*Convert DVI file to specific image format.Tr\   )r]   r_   r3   zS%s command %r cannot be run (needed for math display), check the imgmath_%s settingr   Nz%s exited with error)re   rf   r   r   rg   rh   ri   r   r,   r   r   )rk   rn   retrl   r   r   r&   convert_dvi_to_image   s    
  rp   )dvipathrS   out_pathr    c           
      C  s   d}|j jd|dddg}||j j |j jr8|d ||  t||\}}d}|j jr| D ].}t	|}	|	rdt
|	d}t||  qqd|S )	zConvert DVI file to PNG image.dvipng-oz-TZtightz-z9z--depthNr4   )rE   imgmath_dvipngrc   imgmath_dvipng_argsrK   rb   rp   
splitlinesdepth_rer7   r8   r9   r   
rq   rS   rr   rn   rk   r   r   r>   r;   r<   r   r   r&   convert_dvi_to_png   s     



rz   c           
      C  s   d}|j jd|g}||j j ||  t||\}}d}|j jr| D ]:}t	|}	|	rLt
t|	dd d }t||  qqL|S )zConvert DVI file to SVG image.dvisvgmrt   Nr4   d   gzGR@)rE   imgmath_dvisvgmrc   imgmath_dvisvgm_argsrb   rp   rK   rw   depthsvg_rer7   rI   floatr9   rA   ry   r   r   r&   convert_dvi_to_svg   s    


r   r   ztuple[str | None, int | None])r#   rD   r    c                 C  sT  | j jj }|tkrtdt||| j j| j j}t|	 
  d| }t| j j| j jd|}tt| t|r|dkrt|}n|dkrt|}||fS t| j dst| j drdS zt|| j }W n tk
r   d	| j _Y dS X z6|dkrt|| j |}n|dkr(t|| j |}W n  tk
rJ   d	| j _Y dS X ||fS )
a{  Render the LaTeX math expression *math* using latex and dvipng or
    dvisvgm.

    Return the image absolute filename and the "depth",
    that is, the distance of image bottom and baseline in pixels, if the
    option to use preview_latex is switched on.

    Error handling may seem strange, but follows a pattern: if LaTeX or dvipng
    (dvisvgm) aren't available, only a warning is generated (since that enables
    people on machines without these programs to at least build the rest of the
    docs successfully).  If the programs are there, however, they may not fail
    since that indicates a problem in the math source.
    2imgmath_image_format must be either "png" or "svg".rD   r.   r/   _imgmath_warned_latex _imgmath_warned_image_translator)NNT)rS   rE   imgmath_image_formatlowerSUPPORT_FORMATr   rR   rF   r   encode	hexdigestr   rM   outdirimagedirr   dirnameisfiler   r=   rU   rm   r,   r   rz   r   r   )r#   rD   rC   rY   r0   generated_pathr>   rq   r   r   r&   render_math   sF    




r   )rC   r   r    c              	   C  s\   t |d}t| jdd}W 5 Q R X | dkr>d| S | dkrPd| S tdd S )	Nrbr1   r2   r.   zdata:image/png;base64,r/   zdata:image/svg+xml;base64,r   )r5   base64	b64encodereaddecoder   )rC   r   r:   encodedr   r   r&   render_maths_to_base64  s     

r   r	   	Exception)apprl   r    c                 C  s   |rd S t | jdr<zt| jj W n tk
r:   Y nX | jjjr|z tt	| jj
| jjd W n tk
rz   Y nX d S )NrT   rD   )rU   rS   shutilrmtreerT   r   rE   imgmath_embedr   rM   r   r   )r   rl   r   r   r&   clean_up_files  s    
 r   r   )r#   noder    c                 C  s$   | j jjr d| |   S dS )Nz	 alt="%s"rB   )rS   rE   imgmath_add_tooltipsr   astextstrip)r#   r   r   r   r&   get_tooltip2  s    
r   z
nodes.mathc              
   C  sN  zt | d|  d \}}W nj tk
r } zLt|}tj|ddg | d}||  tt	d| | tj
|W 5 d }~X Y nX |d kr| jd| |    n| jjjr| jjj }t||}n*t|}	t| jjd|	}
|
tjd}d	| d
t| | }|d k	r4|d| dd7 }| j|d  tj
d S )N$WARNING   typelevelZbackrefssourcezdisplay latex %r: %sz<span class="math">%s</span>rD   /z<img class="math" src=""z style="vertical-align: dzpx"z/>)r   r   r   r   r   system_message	walkaboutrh   ri   r   SkipNodebodyrb   r   r   rS   rE   r   r   r   r   r   r`   rM   imgpathreplacesepr   )r#   r   rendered_pathr>   rl   r   smrC   img_srcbnamerelative_pathcr   r   r&   html_visit_math8  s4    
 



r   znodes.math_blockc              
   C  s  |d r|  }nt|  d d}zt| |\}}W nj tk
r } zLt|}tj|ddg |  d}||  t	t
d|  | tj|W 5 d }~X Y nX | j| j|ddd	 | jd
 |d rt| |}| jd|  | |td | jd |d kr.| jd| |     nr| jjjrT| jjj }	t|	|}
n*t|}t| jjd|}|tjd}
| jd|
 dt | | d  tjd S )NZnowrapFr   r   r   zinline latex %r: %sdivrD   )ZCLASSz<p>numberz<span class="eqno">(%s)zPermalink to this equationz</span>z'<span class="math">%s</span></p>
</div>r   z
<img src="r   z/></p>
</div>)!r   r   r   r   r   r   r   r   rh   ri   r   r   r   rb   Zstarttagr   Zadd_permalink_refr   r   r   rS   rE   r   r   r   r   r   r`   rM   r   r   r   r   )r#   r   rY   r   r>   rl   r   r   r   rC   r   r   r   r   r   r&   html_visit_displaymathV  sF    

 




r   zdict[str, Any])r   r    c              	   C  s   |  dtd ftd f | ddd | ddd | ddd | d	d
d | ddd | dddddddgd | ddgd | dg d | ddd | ddd | ddd | dddtg | dt tjddS ) Nr   r   r.   htmlru   rs   r}   r{   ra   rY   rK   Frv   z-gammaz1.5z-DZ110z-bgZTransparentr~   z
--no-fontsrd   rJ   rB   r   TrH      r   zbuild-finished)versionZparallel_read_safe)	Zadd_html_math_rendererr   r   Zadd_config_valueboolconnectr   sphinxZ__display_version__)r   r   r   r&   setup}  s*    r   )rB   )Ir-   
__future__r   r   rer   re   rV   osr   r   typingr   Zdocutilsr   Zdocutils.nodesr   r   r   Zsphinx.applicationr	   Zsphinx.buildersr
   Zsphinx.configr   Zsphinx.errorsr   Zsphinx.localer   r   Zsphinx.utilr   r   Zsphinx.util.mathr   r   Zsphinx.util.osutilr   Zsphinx.util.pngr   r   Zsphinx.util.templater   Zsphinx.writers.htmlr   	getLoggerr'   rh   rM   rL   __all__r   r,   r   compilerx   r   r6   r=   rA   rR   rX   rm   rp   rz   r   r   r   r   r   r   r   r   r   r   r   r&   <module>   sb   




 #=
'