a
    [Xh`                     @   s   d 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	Z	ddl
mZ ddlmZ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mZmZmZmZ d	dlmZmZ G dd dZ dd Z!dd Z"dd Z#dS )zFonts integration in PDF.    N)md5)WARNING)ceil)subset)TTFont
TTLibErrorttFont)instantiateVariableFont   )LOGGERcapture_logs)PANGO_STRETCH_PERCENT)
FROM_UNITSffiharfbuzzharfbuzz_subsetpango)get_hb_object_dataget_pango_font_hb_facec                   @   s@   e Zd Zdd Zdd Zedd Zdd Zd	d
 Zdd Z	dS )Fontc                    sl  t || _t|| _t| j| _t| j| _	|| _
t || _tt || _i | _t |}|tjkrdd t| dD | _| jd }rt|| _t || nt || _| jdrt |t j n| jdrt |t j | jd  d ur6tt   fdd	d
d }t !|| tt "|}d#dd t$|dd% d d D | _&t'd|d }d| j&(  d |)dd | _*| j
rt +|tj}	tt ,|	t- | j
 d | _.tt /|	t- | j
 d  | _0nd | _.| _0t1dd}
t1d}t1d}t2| jd|
| g | _3t4|
d D ],}t5|| | | j36t|  qFd| _7d| j3v rd| j3v rd| j3v rt8d d!}t9| j|}t:|dkrd"| _7t;| nd"| _7d| _<t=| j| _>t?| j| _@tA| j| _Bd#| _Cd#| _Di | _Ei | _Fd| _Gd$| _H| jrJ|  jHd%7  _Hd&|dv rh|  jHd'7  _Hd S )(Nc                 S   s*   i | ]"}| d d t| d d qS )=r      )splitfloat).0part r   Y/var/www/viveiro_mudafortebrasil/venv/lib/python3.9/site-packages/weasyprint/pdf/fonts.py
<dictcomp>"   s   z!Font.__init__.<locals>.<dictcomp>,weightitalslntZwdthc                    s   t | d   S )Nr   )abs)itemwidthr   r   <lambda>3       zFont.__init__.<locals>.<lambda>)keyr    c                 s   s   | ]}t d |d  V  qdS )A      N)chrr   letterr   r   r   	<genexpr>9   s   z Font.__init__.<locals>.<genexpr>F)usedforsecurity   s    [#@]r      /   +       -  zunsigned int *d   zhb_tag_t[100]zchar[4]EBDTEBLCglyfs   glyfTP      @   s   Serifr
   )Ir   Zpango_font_get_hb_fontZhb_fontr   hb_facer   file_contentr   Zhb_face_get_indexindex	font_sizeZ pango_font_description_get_stylestyler   stringZ!pango_font_description_get_familyfamily
variationsZ%pango_font_description_get_variationsZNULLdecoder   getroundr    Z!pango_font_description_set_weightZ!pango_font_description_get_weightZ pango_font_description_set_styleZPANGO_STYLE_ITALICZPANGO_STYLE_OBLIQUEminr   itemsZ"pango_font_description_set_stretchZ pango_font_description_to_stringjoinr   digesthashreencodereplacenameZpango_font_get_metricsZpango_font_metrics_get_ascentr   ascentZpango_font_metrics_get_descentdescentnewZhb_face_get_table_tagstablesrangeZhb_tag_to_stringappendbitmaphb_tag_from_stringZhb_face_reference_tableZhb_blob_get_lengthZhb_blob_destroyitalic_angleZhb_face_get_upemupemZhb_ot_color_has_pngpngZhb_ot_color_has_svgsvgstemvstemhwidthscmapused_in_formsflags)selfZ
pango_fontdescriptionrC   rG   r    ZstretchZdescription_stringrS   Zpango_metricsZtable_countZ
table_tags
table_nameitagZblobr   r%   r   __init__   s    






 


zFont.__init__c                 C   sj  |  || d| jv rVt| j}t|| jd}d| jvrH| j| jd< d| jvr^| j	| jd< d| jvrd}| j
dkr|d jD ]*}|jdkr|jdkr|j}n|j} qq|| jd< d| jvrt| j
d	k| jd< t }zPt|| j}|d
 j D ]&\}\}	}
|	dk rd|
f|d
 j|< q|| W n tyJ   td Y n0 | | _| jsf| jrft| j}t|| jd}zd| jvsd| jvrtd |d< td |d< | |d _dd |d jD |d _n(|d jD ]}td  |d |< qdD ]}||v r||= qt }|| | | _W n t!yd   td Y n0 dS )zRemove useless data from font.ZfvarZ
fontNumberZwghtZopszr"   r   r   r!   r
   ZhmtxzUnable to mutate variable fontZlocar;   c                 S   s   i | ]}|t d  qS )r;   )r   getTableModuleGlyphr   rS   r   r   r   r      s   zFont.clean.<locals>.<dictcomp>)ZCBDTZCBLCzSVG zUnable to save emoji fontN)"r   rW   ioBytesIOrA   r   rB   rG   r    rC   rD   ZaxesZaxisTagZmaxValueZminValueintr	   metricsrL   save	Exceptionr   warninggetvaluer^   r_   r   ZgetTableClassZgetGlyphOrderZ
glyphOrderZglyphsrm   rn   r   )rf   rc   hinting	full_fontttfontr"   ZaxeZpartial_fontr)   advanceZbearingglyphrh   Zoutput_fontr   r   r   cleanq   sf    











z
Font.cleanc                 C   s   | j d d dkrdS dS )Nr>   s   OTTOotfZttf)rA   )rf   r   r   r   type   s    z	Font.typec                 C   s8   |sdS t r(tdddr(| || n| || dS )z*Remove unused glyphs and tables from font.Nr>   r   r   )r   r   Zhb_version_atleast_harfbuzz_subset_fonttools_subset)rf   rc   rx   r   r   r   r      s
    zFont.subsetc                 C   s|  t t tj}t|}t dt| dt|}t	
||t| tjtjB tjB }t|| t|tj}tdd dD }t dt| d|}	t	
||	t| t t| j|t	j}
t|}ttt|d }t dt| d|}t	
||t| tjtjB }|s.|tjO }t|| t t|
|t	j}
|
rnt|
}|rn|| _dS td dS )	zSubset font using Harfbuzz.zhb_codepoint_t[]c                 s   s   | ]}t |d V  qdS )r<   N)r   r[   ro   r   r   r   r0      r(   z(Font._harfbuzz_subset.<locals>.<genexpr>)s   BASEs   DSIGs   EBDTs   EBLCs   EBSCs   GPOSs   GSUBs   JSTFs   LTSHs   PCLTs   SVG r   Nz#Unable to subset font with Harfbuzz)r   gcr   Zhb_subset_input_create_or_failZhb_subset_input_destroyZhb_subset_input_glyph_setrV   lensortedr   Zhb_set_add_sorted_arrayZHB_SUBSET_FLAGS_RETAIN_GIDSZ(HB_SUBSET_FLAGS_PASSTHROUGH_UNRECOGNIZEDZHB_SUBSET_FLAGS_DESUBROUTINIZEZhb_subset_input_set_flagsZhb_subset_input_setZHB_SUBSET_SETS_DROP_TABLE_TAGtupleZhb_subset_or_failr@   Zhb_face_destroyrX   maxZHB_SUBSET_FLAGS_NO_HINTINGr   rA   r   rv   )rf   rc   rx   Z	hb_subsetZgid_setZ	gid_arrayre   Zdrop_setdrop_tablesZdrop_tables_arrayr@   ZkeeprA   r   r   r   r      sZ    



zFont._harfbuzz_subsetc           
      C   s   t | j}tjddd|dd}| jg d7  _t|}|j|d zft|| j	d}t
dtd}|| W d   n1 s0    Y  |D ]}td	| j | qW n ty   td
 Y n0 t  }	||	 |	 | _dS )zSubset font using Fonttools.T)Zretain_gidsZpassthrough_tablesZignore_missing_glyphsrx   Zdesubroutinize)ZGSUBZGPOSZSVG)gidsrl   	fontTools)levelNz*fontTools warning when subsetting "%s": %sz$Unable to subset font with fontTools)rp   rq   rA   r   Optionsr   Z	SubsetterZpopulater   rB   r   r   r   rv   rF   rH   r   rt   rw   )
rf   rc   rx   ry   optionsZ	subsetterrz   ZlogslogZoptimized_fontr   r   r   r      s,    
(


zFont._fonttools_subsetN)
__name__
__module____qualname__rk   r}   propertyr   r   r   r   r   r   r   r   r      s   \@
<r   c              
   C   s  t  }i }| D ]}||jg | qi }| D ]\}	}
|
d }|jrRq:i }|rx|jsx|
D ]}i ||j	}qd|
||d  |jdkrt ddi}nt dt|ji}t j|jg||d}| | |j||	< q:| D ]
}|r
|js
|j}|j	}nt|j}t||jd}i i  }}t|  D ]\}}|jd	 |j ||< q>|  D ]*\}}||}||vrjt|||< qjt jg d
|d}t|}t| }tt|d D ]}t d||d  }|j!| d"  ||d |d d  D ]>\}}d#dd |D }|j!d|dd| d"  q|j!d q|j!$g d | | t dd|jrdnd |j%|jd}|jrt&|| |||| nt'|| |||||j |d  | | |j||j< q|S )zBuild PDF dictionary for fonts.r   rx   r~   Subtype	/OpenTypeZLength1compressrl   r7   )s$   /CIDInit /ProcSet findresource begins   12 dict begins	   begincmaps   /CIDSystemInfos   << /Registry (Adobe)s   /Ordering (UCS)s   /Supplement 0s   >> defs!   /CMapName /Adobe-Identity-UCS defs   /CMapType 2 defs   1 begincodespaceranges   <0000> <ffff>s   endcodespaceranger8   z beginbfcharr   r*   c                 s   s   | ]}| d   V  qdS )z	utf-16-beN)rQ   hexr.   r   r   r   r0   [  s   z)build_fonts_dictionary.<locals>.<genexpr><Z04xz> <>s	   endbfchar)s   endcmaps-   CMapName currentdict /CMap defineresource pop   endr   /Fontz/Type   )Typer   BaseFont	ToUnicodepdf_version)(pydyf
Dictionaryvalues
setdefaultrO   rY   rL   rZ   rd   rc   r}   r   r   rA   Stream
add_object	referencerb   rp   rq   r   rB   	enumerateZgetGlyphSetr&   r]   ZgetBestCmap
getGlyphIDr-   r   rX   r   rK   streamrQ   rM   extendrS   _build_bitmap_font_dictionary_build_vector_font_dictionary)pdfZfontsr   r   r   Z	pdf_fontsZfonts_by_file_hashfontZfont_references_by_file_hashZ	file_hashZ
file_fontsrc   Z	file_fontZ
font_extraZfont_streamZfont_widthsry   rz   ri   r|   r/   r)   Z
to_unicodeZcmap_lengthZ
cmap_itemsZbatch_lengthtextZunicode_codepointsfont_dictionaryr   r   r   build_fonts_dictionary  s    






 



r   c           7         st  t g d| d< t g d| d< |r8tt|j}nttd}|d |d  }}g }	t|D ]*}
|
d |vr||	|
 |	d	|
  qb|| d
< || d< t dt |	d| d< t i }t	|j
}t||jd}|d jd }dg|| d  }i }| D ]
\}}
|
 }||}|dkr|
j}|d jd j}|D ]X}|j}|j}||  krp|krHn n*|jj}|jj }|jj}|jj} q(qHtd|  qnp|dv rdnd}|
j|d  }|
jdd \}tj|
jdd ddd}tj|
jdd ddd}|
jd }|| }||v rF|||| < td }||||d d d }||< d|fv s|sd|d< q|dv r||d< q|d v r&dd  d t t|! d!dd    "dt#|  d"$ fd#d$t|D } t| d%|| d|d< n|d%v rg  }!|d&< |d'krJdnd}"t||"|"d  d}#t|#D ]}$|"d |$d  }%t||%|%d  d}&tj||%d |%d  ddd}'tj||%d |%d  ddd}(|!|&|'|(d( qnn td)|  t&|| |d< q| D ],\}}||vr6q|d* }|d+ |d, }|d- }'|d. }(|d d u r|| })tt&|)d}*|d& D ]L}+|+d- },|+d. }-|+d/ }.|.|vrtd0|.  q||. }+|+d d u rtd1|.  qt|+d, D ]}/t'|/|+d*  |/d |+d*  }0|+d |0 }1t|1d}2|d ||- |/ d  }3||+d*  }4|4dkrt|2|4d K }2n|4dk r|2|4 d L }2|,dkr|2|,L }2n|,dk r|2|, K }2|2d|d > ; }2|2|3K }2|*|2O }*qq|*%|)d}5n|d }5t j(d2 d3| d4|' d4|( d5) d6d7d8d9|d:d;d<|5d=g|d>}6|*|6 |6j+||< q|*| t || d?< |j+| d@< d S )AN)r   r   r   r   FontBBox)r   r   r   r   r   r   Z
FontMatrix   r   r<   r   /Z	FirstCharZLastCharz	/Encoding)r   ZDifferencesEncodingrl   r9      r:   z"Unknown bitmap metrics for glyph: )r   r
      r   r
   r   bigT)signedr>   )r&   heightxystriderZ   	subglyphsr(   rZ   )r   r2   )r
   r         r*   c                 3   s.   | ]&} | |d    d  V  qdS )r   0Nr   )r   ri   bitspaddingr&   r   r   r0     s   z0_build_bitmap_font_dictionary.<locals>.<genexpr>)r   	   r   r   )idr   r   z!Unsupported bitmap glyph format: r   r&   r   r   r   r   zUnknown subglyph: z"Unsupported subglyph in subglyph: s   0 0 d0z 0 0  z cms   BIs   /IM trues   /Ws   /Hs   /BPC 1s   /D [1 0]s   IDs   EIr   ZWidthsZ	CharProcs),r   Arrayr   r   rc   rX   rY   r   rp   rq   rA   r   rB   Z
strikeDatarL   Z	getFormatr   dataZstrikesZindexSubTablesZfirstGlyphIndexZlastGlyphIndexrs   r   r&   ZhoriBearingXZhoriBearingYr   rv   rr   
from_bytesr   binr   zfillr   rM   to_bytesbytesslicer   rQ   r   r   )7r   r   r   rb   r   r   charsfirstlastZdifferencesr|   Z
char_procsry   rz   Zfont_glyphsZglyphs_infor)   Zglyph_formatZglyph_idr   Z	subtablesZsubtableZfirst_index
last_indexr   r{   Z	bearing_xZ	bearing_yZ
data_startZ
position_yr   Z
glyph_infoZbitmap_bitsr   ri   Znumber_of_componentsjrB   Zsubglyph_idr   r   lengthZ
bitmap_intZsubglyphZsub_xZsub_yZsub_idZrow_yZ	row_slicerowZrow_intshiftZstride_differencerZ   Zbitmap_streamr   r   r   r   z  s    









  











r   c                 C   s.  d|j dkrdnd }|r(t| nd}d|j||jf}	|j}
t|dkrltt|j dkrl|
d7 }
t	
ddd	|jd
t	|jd|
dt	|	d|jd|jd|jd|	d d|jd|j||i}t|dkrJt|j}t|d d d }dg| d }|D ]}d||< qt	jtd|d|df|d}|| |j|d< |j dkr^d|d< || t	 }t|D ]>}|d |vr|| t	 }|| |||  qxt	
dd|j dkrdnd |jt	
t	d t	d!dd"d#||jd$}|| d%| d&< t	|jg| d'< d S )(NZFontFiler~   r   r
   r   r   r   z/FontDescriptorZFontNameZ
FontFamilyZFlagsr   ZItalicAngleZAscentZDescentZ	CapHeightZStemVZStemHz1.4r<   r   r   1r*   r   r   ZCIDSetr   r   r   z/CIDFontTypeZAdobeZIdentity)ZRegistryZOrderingZ
Supplementz	/Identity)r   r   r   ZCIDSystemInfoZCIDToGIDMapWZFontDescriptorz/Identity-Hr   ZDescendantFonts)r   r   r   rU   rT   re   r   setrb   r   r   rS   StringrF   r   r\   r`   ra   strr   r   r   rr   rM   r   r   r   rY   )r   r   r   rb   r   r   r   Z	font_fileZmax_xZbboxre   Zfont_descriptorZcidsZpadded_widthr   Zcidr   Z
pdf_widthsri   Zcurrent_widthsZsubfont_dictionaryr   r   r   r     st    "







r   )$__doc__rp   rP   hashlibr   loggingr   mathr   r   r   r   ZfontTools.ttLibr   r   r   ZfontTools.varLib.mutatorr	   loggerr   r   Ztext.constantsr   Ztext.ffir   r   r   r   r   Z
text.fontsr   r   r   r   r   r   r   r   r   r   <module>   s(     a "