o
    Zh0h`                     @   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rGdd t| dD | _| jd }r[t|| _t || nt || _| jdrot |t j n| jdr|t |t j | jd  d urt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|  q!d| _7d| j3v rnd| j3v rnd| j3v rkt8d d!}t9| j|}t:|dkred"| _7t;| nd"| _7d| _<t=| j| _>t?| j| _@tA| j| _Bd#| _Cd#| _Di | _Ei | _Fd| _Gd$| _H| jr|  jHd%7  _Hd&|dv r|  jHd'7  _Hd S d S )(Nc                 S   s*   i | ]}| d d t| d d qS )=r      )splitfloat).0part r   J/var/www/html/rh/venv/lib/python3.10/site-packages/weasyprint/pdf/fonts.py
<dictcomp>"   s    z!Font.__init__.<locals>.<dictcomp>,weightitalslntwdthc                    s   t | d   S )Nr   )abs)itemwidthr   r   <lambda>3   s    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       
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   pango_font_get_hb_fonthb_fontr   hb_facer   file_contentr   hb_face_get_indexindex	font_size pango_font_description_get_stylestyler   string!pango_font_description_get_familyfamily
variations%pango_font_description_get_variationsNULLdecoder   getroundr    !pango_font_description_set_weight!pango_font_description_get_weight pango_font_description_set_stylePANGO_STYLE_ITALICPANGO_STYLE_OBLIQUEminr   items"pango_font_description_set_stretch pango_font_description_to_stringjoinr   digesthashreencodereplacenamepango_font_get_metricspango_font_metrics_get_ascentr   ascentpango_font_metrics_get_descentdescentnewhb_face_get_table_tagstablesrangehb_tag_to_stringappendbitmaphb_tag_from_stringhb_face_reference_tablehb_blob_get_lengthhb_blob_destroyitalic_anglehb_face_get_upemupemhb_ot_color_has_pngpnghb_ot_color_has_svgsvgstemvstemhwidthscmapused_in_formsflags)self
pango_fontdescriptionrG   rM   r    stretchdescription_stringrb   pango_metricstable_count
table_tags
table_nameitagblobr   r&   r   __init__   s   






 


zFont.__init__c                 C   sb  |  || d| jv rt| j}t|| jd}d| jvr#| j| jd< d| jvr.| j	| jd< d| jvrZd}| j
dkrU|d jD ]}|jdkrT|jdkrO|j}n|j} nq?|| jd< d| jvrit| j
d	k| jd< t }z(t|| j}|d
 j D ]\}\}	}
|	dk rd|
f|d
 j|< q{|| W n ty   td Y nw | | _| js| jr/t| j}t|| jd}zad| 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 dS  t!y.   td Y dS w dS )zRemove useless data from font.fvar
fontNumberwght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   rb   r   r   r   r      s    zFont.clean.<locals>.<dictcomp>)CBDTCBLCzSVG zUnable to save emoji fontN)"r   rj   ioBytesIOrD   r   rF   rM   r    rG   rI   axesaxisTagmaxValueminValueintr	   metricsrY   save	Exceptionr   warninggetvaluerw   ry   r   getTableClassgetGlyphOrder
glyphOrderglyphsr   r   r   )r   r}   hinting	full_fontttfontr"   axepartial_fontr)   advancebearingglyphr   output_fontr   r   r   cleanq   sr   











z
Font.cleanc                 C   s   | j d d dkrdS dS )Nr?   s   OTTOotfttf)rD   )r   r   r   r   type   s   z	Font.typec                 C   s:   |sdS t rtdddr| || dS | || dS )z*Remove unused glyphs and tables from font.Nr?   r   r   )r   r   hb_version_atleast_harfbuzz_subset_fonttools_subset)r   r}   r   r   r   r   r      s
   zFont.subsetc                 C   sv  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}
|
rt|
}|r|| _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   ro   r   r   r   r   r0      s    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   hb_subset_input_create_or_failhb_subset_input_destroyhb_subset_input_glyph_setrh   lensortedr   hb_set_add_sorted_arrayHB_SUBSET_FLAGS_RETAIN_GIDS(HB_SUBSET_FLAGS_PASSTHROUGH_UNRECOGNIZEDHB_SUBSET_FLAGS_DESUBROUTINIZEhb_subset_input_set_flagshb_subset_input_setHB_SUBSET_SETS_DROP_TABLE_TAGtuplehb_subset_or_failrC   hb_face_destroyrk   maxHB_SUBSET_FLAGS_NO_HINTINGr   rD   r   r   )r   r}   r   	hb_subsetgid_set	gid_arrayr   drop_setdrop_tablesdrop_tables_arrayrC   keeprD   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 z3t|| j	d}t
dtd}|| W d   n1 sBw   Y  |D ]}td	| j | qIW n tyf   td
 Y dS w t  }	||	 |	 | _dS )zSubset font using Fonttools.T)retain_gidspassthrough_tablesignore_missing_glyphsr   desubroutinize)GSUBGPOSSVG)gidsr   	fontTools)levelNz*fontTools warning when subsetting "%s": %sz$Unable to subset font with fontTools)r   r   rD   r   Optionsr   	Subsetterpopulater   rF   r   r   r   r   rL   rP   r   r   r   )
r   r}   r   r   options	subsetterr   logslogoptimized_fontr   r   r   r      s2   


zFont._fonttools_subsetN)
__name__
__module____qualname__r   r   propertyr   r   r   r   r   r   r   r   r      s    \@
<r   c              
   C   s  t  }i }| D ]}||jg | q
i }| D ]R\}	}
|
d }|jr)qi }|r<|js<|
D ]	}i ||j	}q2|
||d  |jdkrQt ddi}n
t dt|ji}t j|jg||d}| | |j||	< q| D ]}|r|js|j}|j	}nCt|j}t||jd}i i }}t|  D ]\}}|jd	 |j ||< q|  D ]\}}||}||vrt|||< qt jg d
|d}t|}t| }tt|d D ]H}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r@dnd |j%|jd}|jrYt&|| |||| nt'|| |||||j |d  | | |j||j< qt|S )zBuild PDF dictionary for fonts.r   r   r   Subtype	/OpenTypeLength1compressr   r8   )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   endcodespaceranger9   z beginbfcharr   r*   c                 s   s     | ]}| d   V  qdS )z	utf-16-beN)r`   hexr.   r   r   r   r0   [  r1   z)build_fonts_dictionary.<locals>.<genexpr><04xz> <>s	   endbfchar)s   endcmaps-   CMapName currentdict /CMap defineresource pop   endr   /Fontz/Type   )Typer   BaseFont	ToUnicodepdf_version)(pydyf
Dictionaryvalues
setdefaultr^   rm   rY   rn   r~   r}   r   r   r   rD   Stream
add_object	referencer|   r   r   r   rF   	enumerategetGlyphSetr'   ru   getBestCmap
getGlyphIDr-   r   rk   r   rX   streamr`   r\   extendrb   _build_bitmap_font_dictionary_build_vector_font_dictionary)pdffontsr   r   r   	pdf_fontsfonts_by_file_hashfontfont_references_by_file_hash	file_hash
file_fontsr}   	file_font
font_extrafont_streamfont_widthsr   r   r   r   r/   r)   
to_unicodecmap_length
cmap_itemsbatch_lengthtextunicode_codepointsfont_dictionaryr   r   r   build_fonts_dictionary  s   






 



r  c           7         s^  t g d| d< t g d| d< |rtt|j}nttd}|d |d }}g }	t|D ]}
|
d |vr>|	|
 |	d	|
  q1|| 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 ](}|j}|j}||  kr|krn q|jj}|jj }|jj}|jj} n
qtd|  qn7|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 r|||| < td }||||d d d }||< d|fv s:|s?d|d< q|dv rI||d< q|d v rdd  d t t|! d!dd    "dt#|  d"$ fd#d$t|D } t| d%|| d|d< q|d%v rg  }!|d&< |d'krd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( qqtd)|  t&|| |d< q| D ]\}}||vrq|d* }|d+ |d, }|d- }'|d. }(|d d u r|| })tt&|)d}*|d& D ]}+|+d- },|+d. }-|+d/ }.|.|vrYtd0|.  q<||. }+|+d d u rntd1|.  q<t|+d, D ]l}/t'|/|+d*  |/d |+d*  }0|+d |0 }1t|1d}2|d ||- |/ d  }3||+d*  }4|4dkr|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 }*qt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   
FontMatrix   r   r=   r   /	FirstCharLastCharz	/Encoding)r   DifferencesEncodingr   r:      r;   z"Unknown bitmap metrics for glyph: )r   r
      r%  r
   r   bigT)signedr?   )r'   heightxystridern   	subglyphs    rn   )r   r3   )r
   r$        r*   c                 3   s0    | ]} | |d    d  V  qdS )r   0Nr   )r   r   bitspaddingr'   r   r   r0     s
    
z0_build_bitmap_font_dictionary.<locals>.<genexpr>)r%  	   r,  r4  )idr)  r*  z!Unsupported bitmap glyph format: r+  r'   r(  r)  r*  r5  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   Widths	CharProcs),r   Arrayr   r   r}   rk   rm   r   r   r   rD   r   rF   
strikeDatarY   	getFormatr  datastrikesindexSubTablesfirstGlyphIndexlastGlyphIndexr   r(  r'   horiBearingXhoriBearingYr   r   r   
from_bytesr   binr   zfillr   r\   to_bytesbytesslicer   r`   r   r   )7r  r  r  r|   r   r   charsfirstlastdifferencesr   
char_procsr   r   font_glyphsglyphs_infor)   glyph_formatglyph_idr<  	subtablessubtablefirst_index
last_indexr(  r   	bearing_x	bearing_y
data_start
position_yr+  
glyph_infobitmap_bitsr,  r   number_of_componentsjrF   subglyph_idr)  r*  length
bitmap_intsubglyphsub_xsub_ysub_idrow_y	row_slicerowrow_intshiftstride_differencern   bitmap_streamr   r1  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r6tt|j dkr6|
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rt|j}t|d d d }dg| d }|D ]}d||< qt	jtd|d|df|d}|| |j|d< |j dkrd|d< || t	 }t|D ]}|d |vr|| t	 }|| |||  qt	
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FontName
FontFamilyFlagsr  ItalicAngleAscentDescent	CapHeightStemVStemHz1.4r=   r%  r0  1r*   r&  r   CIDSetr   r   r   z/CIDFontTypeAdobeIdentity)RegistryOrdering
Supplementz	/Identity)r   r   r   CIDSystemInfoCIDToGIDMapWFontDescriptorz/Identity-Hr#  DescendantFonts)r   r   r   rg   re   r   r   setr|   r   r   rb   StringrL   r9  rs   rz   r{   strr   r   r   r   r\   rF  r   r   rm   )r  r  r  r|   r   r   r   	font_filemax_xbboxr   font_descriptorcidspadded_widthr2  cidr  
pdf_widthsr   current_widthssubfont_dictionaryr   r   r   r    st   "









r  )$__doc__r   r_   hashlibr   loggingr   mathr   r   r   r   fontTools.ttLibr   r   r   fontTools.varLib.mutatorr	   loggerr   r   text.constantsr   text.ffir   r   r   r   r   
text.fontsr   r   r   r  r  r  r   r   r   r   <module>   s*      a "