a
    Qh`                     @   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   M/var/www/sistema_ama/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_font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_variationsNULLdecoder   getroundr    !pango_font_description_set_weightZ!pango_font_description_get_weight pango_font_description_set_stylePANGO_STYLE_ITALICPANGO_STYLE_OBLIQUEminr   items"pango_font_description_set_stretchZ pango_font_description_to_stringjoinr   digesthashreencodereplacenameZpango_font_get_metrics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_length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)self
pango_fontdescriptionrD   rH   r    stretchZdescription_stringrZ   Zpango_metricsZtable_countZ
table_tags
table_nameitag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.fvar
fontNumberZwghtZopszr"   r   r   r!   r
   hmtxzUnable to mutate variable fontlocar;   c                 S   s   i | ]}|t d  qS )r;   )r   getTableModuleGlyphr   rZ   r   r   r   r      s   zFont.clean.<locals>.<dictcomp>)CBDTCBLCzSVG zUnable to save emoji fontN)"r   r_   ioBytesIOrB   r   rC   rH   r    rD   rE   axesaxisTagmaxValueminValueintr	   metricsrR   save	Exceptionr   warninggetvaluerg   rh   r   getTableClassgetGlyphOrder
glyphOrderglyphsr}   r~   r   )ro   rl   hinting	full_fontttfontr"   ZaxeZpartial_fontr)   advanceZbearingglyphrs   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)rB   )ro   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)ro   rl   r   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   rc   r   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_setr^   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_failrA   Zhb_face_destroyr`   maxZHB_SUBSET_FLAGS_NO_HINTINGr   rB   r   r   )ro   rl   r   Z	hb_subsetZgid_setZ	gid_arrayrn   Zdrop_setdrop_tablesZdrop_tables_arrayrA   keeprB   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_glyphsr   Zdesubroutinize)GSUBGPOSSVG)gidsry   	fontTools)levelNz*fontTools warning when subsetting "%s": %sz$Unable to subset font with fontTools)r   r   rB   r   Optionsr   Z	Subsetterpopulater   rC   r   r   r   r   rG   rJ   r   r   r   )
ro   rl   r   r   optionsZ	subsetterr   ZlogslogZoptimized_fontr   r   r   r      s,    
(


zFont._fonttools_subsetN)
__name__
__module____qualname__rw   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   r   r   Subtype	/OpenTypeLength1compressry   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)rX   hexr.   r   r   r   r0   [  s   z)build_fonts_dictionary.<locals>.<genexpr><04xz> <>s	   endbfchar)s   endcmaps-   CMapName currentdict /CMap defineresource pop   endr   /Fontz/Type   )Typer   BaseFontZ	ToUnicodepdf_version)(pydyf
Dictionaryvalues
setdefaultrV   ra   rR   rb   rm   rl   r   r   r   rB   Stream
add_object	referencerk   r   r   r   rC   	enumerategetGlyphSetr&   rf   getBestCmap
getGlyphIDr-   r   r`   r   rQ   streamrX   rT   extendrZ   _build_bitmap_font_dictionary_build_vector_font_dictionary)pdffontsr   r   r   	pdf_fontsZfonts_by_file_hashfontZfont_references_by_file_hash	file_hashZ
file_fontsrl   Z	file_fontZ
font_extraZfont_streamZfont_widthsr   r   rt   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   /	FirstCharLastCharz	/Encoding)r   DifferencesEncodingry   r9      r:   z"Unknown bitmap metrics for glyph: )r   r
      r   r
   r   bigT)signedr>   )r&   heightxystriderb   	subglyphsr(   rb   )r   r2   )r
   r         r*   c                 3   s.   | ]&} | |d    d  V  qdS )r   0Nr   )r   rt   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   WidthsZ	CharProcs),r   Arrayr   r   rl   r`   ra   r   r   r   rB   r   rC   Z
strikeDatarR   Z	getFormatr   dataZstrikesZindexSubTablesZfirstGlyphIndexZlastGlyphIndexr   r   r&   ZhoriBearingXZhoriBearingYr   r   r   
from_bytesr   binr   zfillr   rT   to_bytesbytesslicer   rX   r   r   )7r   r   r   rk   r   r   charsfirstlastdifferencesr   Z
char_procsr   r   Zfont_glyphsZglyphs_infor)   Zglyph_formatZglyph_idr   Z	subtablesZsubtableZfirst_index
last_indexr   r   Z	bearing_xZ	bearing_yZ
data_start
position_yr   
glyph_infoZbitmap_bitsr   rt   Znumber_of_componentsjrC   Zsubglyph_idr   r   lengthZ
bitmap_intZsubglyphZsub_xZsub_yZsub_idrow_yZ	row_slicerowZrow_intshiftZstride_differencerb   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 )(NFontFiler   r   r
   r   r   r   z/FontDescriptorFontNameZ
FontFamilyFlagsr   ItalicAngleAscentDescent	CapHeightStemVZStemHz1.4r<   r   r   1r*   r   r   ZCIDSetr   r   r   z/CIDFontTypeZAdobeIdentity)ZRegistryZOrderingZ
Supplementz	/Identity)r   r   r   ZCIDSystemInfoZCIDToGIDMapWFontDescriptorz/Identity-Hr   ZDescendantFonts)r   r   r   r]   r\   rn   r   setrk   r   r   rZ   StringrG   r   re   ri   rj   strr   r   r   r   rT   r   r   r   ra   )r   r   r   rk   r   r   r   Z	font_filemax_xbboxrn   Zfont_descriptorZcidsZpadded_widthr   cidr   Z
pdf_widthsrt   Zcurrent_widthsZsubfont_dictionaryr   r   r   r     st    "







r   )$__doc__r   rW   hashlibr   loggingr   mathr   r   r   r   fontTools.ttLibr   r   r   ZfontTools.varLib.mutatorr	   loggerr   r   Ztext.constantsr   Ztext.ffir   r   r   r   r   
text.fontsr   r   r   r   r   r   r   r   r   r   <module>   s(     a "