
    ۡi#a                        d dl Z d dlmZ d dlmZ d dlmZmZmZ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mZ ddlmZmZmZmZmZ ddlmZmZmZ dZ e G d d             Z! G d de      Z" G d de      Z# G d de"      Z$y)    N)	dataclass)IntEnum)AnyOptionalUnioncast   )fill_from_encoding)CORE_FONT_METRICS)Font)logger_warning)AnnotationDictionaryAttributesBorderStylesFieldDictionaryAttributes)DecodedStreamObjectDictionaryObject
NameObjectNumberObjectRectangleObject)ByteStringObjectTextStringObjectis_null_or_none   c                   h    e Zd ZU dZdZeeeeeeef   f   e	d<   dZ
ee	d<   ej                  Zee	d<   y)BaseStreamConfigzBA container representing the basic layout of an appearance stream.)        r   r   r   	rectangle   border_widthborder_styleN)__name__
__module____qualname____doc__r   r   r   tuplefloat__annotations__r   intr   SOLIDr    str     j/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/pypdf/generic/_appearance_stream.pyr   r      sA    LK_Iu_eE5%,F&GGH_L#$**L#*r,   r   c                   4     e Zd ZdZddee   ddf fdZ xZS )BaseStreamAppearancez^A class representing the very base of an appearance stream, that is, a rectangle and a border.Nlayoutreturnc                     t         |           |xs
 t               | _        t	        d      | t	        d      <   t	        d      | t	        d      <   t        | j                  j                        | t	        d      <   y)z
        Takes the appearance stream layout as an argument.

        Args:
            layout: The basic layout parameters.
        z/XObject/Typez/Form/Subtype/BBoxN)super__init__r   _layoutr   r   r   )selfr0   	__class__s     r-   r7   zBaseStreamAppearance.__init__"   sf     	3!1!3$.z$:Z !'1'':Z
#$$3DLL4J4J$KZ !r,   )N)r!   r"   r#   r$   r   r   r7   __classcell__r:   s   @r-   r/   r/      s(    hLx(89 LT L Lr,   r/   c                       e Zd ZdZdZdZdZy)TextAlignmentzODefines the alignment options for text within a form field's appearance stream.r   r   r	   N)r!   r"   r#   r$   LEFTCENTERRIGHTr+   r,   r-   r>   r>   0   s    YDFEr,   r>   c                       e Zd ZdZ	 d$dededededededed	ed
eeeeef      ef   fdZ	ddddde
j                  ddfdedeee   df   dedeeeef      dedededede
dedee   d
efdZdddddddde
j                  ddfdee   dedeee      dee   dedededede
dedee   d
df fdZe	 	 d%deded ed!ed"ed
d fd#       Z xZS )&TextStreamAppearanceaH  
    A class representing the appearance stream for a text-based form field.

    This class generates the content stream (the `ap_stream_data`) that dictates
    how text is rendered within a form field's bounding box. It handles properties
    like font, font size, color, multiline text, and text selection highlighting.
    font	font_sizeleading_factorfield_widthfield_heighttextmin_font_sizefont_size_stepr1   c	           
         |}	|j                  dd      j                  d      }
g }g }d}|j                  |z  dz  }|
D ]   }|j                         s|j	                  d       &|j                  d      }t        |      D ]  \  }}|j                  |      |z  dz  }||z   |r|ndz   }||kD  r*|r(|j	                  |dj                  |      f       |g}|}X|s||kD  r|j	                  ||f       g }d}w|r||z  }|j	                  |       ||z  } |s|j	                  |dj                  |      f       g }d} |t        |      dz
  |z  |z  z   }||kD  r"||z
  }||k\  r| j                  ||||||	||      S |t        |d      fS )a_  
        Takes a piece of text and scales it to field_width or field_height, given font_name
        and font_size. Wraps text where necessary.

        Args:
            font: The font to be used.
            font_size: The font size in points.
            leading_factor: The line distance.
            field_width: The width of the field in which to fit the text.
            field_height: The height of the field in which to fit the text.
            text: The text to fit with the field.
            min_font_size: The minimum font size at which to scale the text.
            font_size_step: The amount by which to decrement font size per step while scaling.

        Returns:
            The text in the form of list of tuples, each tuple containing the length of a line
            and its contents, and the font_size for these lines and lengths.
        
r     )r     r   )replacesplitspace_widthstripappend	enumerate
text_widthjoinlen_scale_textround)r9   rD   rE   rF   rG   rH   rI   rJ   rK   	orig_text
paragraphswrapped_linescurrent_line_wordscurrent_line_widthrT   	paragraphwordsiword
word_width
test_widthestimated_total_heightnew_font_sizes                          r-   r[   z TextStreamAppearance._scale_textA   s   : 	\\$-33D9
(*$%&&2T9# 	'I??$$$Y/OOC(E$U+ 54!__T2Y>E
/*<qVWX
+0B!((*<chhGY>Z)[\*.&)3&+
[0H!((*d);<)+&)*&)*k9*&--d3&*4&5  "$$&8#((CU:V%WX%'"%&"1	'4 "+c-.@1.D-VYb-b!b!L0%6M-''!" !"	 	 eIq111r,   N/Helvr   z0 gF	selectionfont_glyph_byte_map	font_name
font_coloris_multiline	alignmentis_comb
max_lengthc                 p   | j                   j                  }|xs i }t        |t              rt	        |      }|j
                  j                  d   |j
                  j                  d   z
  dz  }| j                   j                  dv rdnd}t        | j                   j                  |z  d      }|j                  d|z  z
  }|j                  d|z  z
  }|dk(  rud}|rd	}|r"t        }| j                  |||||||      \  }}n ||z  }|j                  |      d
z  }||xs dz  }t        t        t!        ||      |      d      }||z  |fg}n|
rn|r%t#        |      |kD  rt%        d| d| dt&               t)        |      D cg c]0  \  }}||xs t#        |      k  r|j                  |      |z  d
z  |f2 }}}nE|j+                  dd      j-                  d      D cg c]  }|j                  |      |z  d
z  |f }}|r0|j                  |z   |j
                  j                  d   |z  dz  z
  }n%|||j
                  j.                  |z  d
z  z
  dz  z   }| d| d| }dd|z   d| d| d| d| dj1                         }d}t)        |      D ]  \  }\  }}|r@||v r<|d|||z  |z  z
  dz
   d|j                  dz
   d|dz    d| d	j1                         z  }d} |
r"|r |j                  |z  }!|!|z
  dz  }"||!z  |"z   } nT|	t2        j4                  k(  r|j                  |dz  z
  |z
  } n+|	t2        j6                  k(  r|j                  |z
  dz  } n|dz  } | |z
  }#d}$|dk(  r|}$n|
rd}$n| |z  }$||# d|$ dj1                         z  }| }|D %cg c]#  }%|j9                  |%|%j1                  d            % }&}%t;        d |&D              r8|ddj=                  |&      j?                         j1                         z   dz   z  }s|ddj=                  |&      z   dz   z  } |dz  }|S c c}}w c c}w c c}%w ) a  
        Generates the raw bytes of the PDF appearance stream for a text field.

        This private method assembles the PDF content stream operators to draw
        the provided text within the specified rectangle. It handles text positioning,
        font application, color, and special formatting like selected text.

        Args:
            text: The text to be rendered in the form field.
            selection: An optional list of strings that should be highlighted as selected.
            font: The font to use.
            font_glyph_byte_map: An optional dictionary mapping characters to their
                byte representation for glyph encoding.
            font_name: The name of the font resource to use (e.g., "/Helv").
            font_size: The font size. If 0, it is automatically calculated
                based on whether the field is multiline or not.
            font_color: The color to apply to the font, represented as a PDF
                graphics state string (e.g., "0 g" for black).
            is_multiline: A boolean indicating if the text field is multiline.
            alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER.
            is_comb: Boolean that designates fixed-length fields, where every character
                fills one "cell", such as in a postcode.
            max_length: Used if is_comb is set. The maximum number of characters for a fixed-
                length field.

        Returns:
            A byte string containing the PDF content stream data.

           r   g     @@>   /B/Ir	      r   g      @FrO   zLength of text z exceeds maximum length (z) of field, input truncated.rM   rN   rQ   z Tf zq
/Tx BMC 
q
z	 re
W
BT
z1 z re
0.5 0.5 0.5 rg s
r   z Td
z	utf-16-bec              3   8   K   | ]  }t        |      d k\    yw)r	   N)rZ   ).0cs     r-   	<genexpr>zHTextStreamAppearance._generate_appearance_stream_data.<locals>.<genexpr>*  s     513q6Q;5s      <r,   s   > Tj
   (s   ) Tj
s   ET
Q
EMC
Q
) r8   r   
isinstancer%   r   font_descriptorbboxr    maxr   heightwidthDEFAULT_FONT_SIZE_IN_MULTILINEr[   rX   r\   minrZ   r   r!   rW   rR   rS   ascentencoder>   rA   r@   getanyrY   hex)'r9   rI   rk   rD   rl   rm   rE   rn   ro   rp   rq   rr   r   rF   factormarginrH   rG   rJ   linesmax_vertical_sizetext_width_unscaledmax_horizontal_sizeindexcharliney_offsetdefault_appearance	ap_streamcurrent_x_posline_number
line_widthdesired_abs_x_start
cell_widthcentering_offset_in_cellx_rel_offsety_rel_offsetrz   encoded_lines'                                          r-    _generate_appearance_stream_dataz5TextStreamAppearance._generate_appearance_stream_data   s5   V LL**	17Ri''	2I..33A69M9M9R9RST9UUY__ ll//<?QT\\..7; ''!f*4ooF
2 >M$:	#'#3#3" !$ y %1>$A!&*ood&;d&B#&15H5MA&N#!#c*;=P&QS`"acde	-	94@Ac$i*4%dV+DZLPlm "+4W %EZ=T3t94U %	1D8 WE W ,,tT288>@  %	1D8 @E @  ''&043G3G3L3LQ3OR[3[^d3ddH,1E1E1L1Ly1X[_1_"_cd!deH ){!I;d:,G q6zl!F81[M<. Q,-R1
&( 	  !/8/? 3	G+K+*dTY.[9%<~%MNQRRSST *+1Y]O <));(<B@ &(		 *+:&__z9
 -7,Cq+H('2Z'?C[&[#m111&/oo
&BZ&O#m222'0'Cq&H#&,qj# />L #$La'"!*{^; L><.>EEGGI 0M LP)FG#''188K+@A)L ) 555TSXXl%;$@$@$B$I$I$KKiWW	TCHH\$::YFF	g3	Gh 	''	YW
@~)s   5P( P.(P3rP   r0   font_resourcec                    t         |   |       |r4t        t        |j	                               }t        j                  |      }nt        d| dt               d}t        t        d      t        d      t        d      t        d      t        d      t        d      t        d	      t        d
      t        d      t        d      i      }t        d   }d|j                  d   z  |j                  d<   t        di t        t        t        d      t        d                  d||j                        }t!        |j"                  t$              rG|j&                  j)                         D ci c]!  \  }}||j+                  |j"                        # }}}n|j"                  j)                         D ci c]  \  }}|t-        |f       }}}|j"                  j)                         D ci c]  \  }}|t-        |f       }}}|j&                  j)                         D ]  \  }}|j/                  ||      ||<    | j1                  |||||||||	|
|      }| j3                  t5        |             t7        t9        |            | t        d      <   t        t        d      t        t        |      t;        |d|      i      i      | t        d      <   yc c}}w c c}}w c c}}w )a  
        Initializes a TextStreamAppearance object.

        This constructor creates a new PDF stream object configured as an XObject
        of subtype Form. It uses the `_appearance_stream_data` method to generate
        the content for the stream.

        Args:
            layout: The basic layout parameters.
            text: The text to be rendered in the form field.
            selection: An optional list of strings that should be highlighted as selected.
            font_resource: An optional variable that represents a PDF font dictionary.
            font_name: The name of the font resource, e.g., "/Helv".
            font_size: The font size. If 0, it's auto-calculated.
            font_color: The font color string.
            is_multiline: A boolean indicating if the text field is multiline.
            alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER.
            is_comb: Boolean that designates fixed-length fields, where every character
                fills one "cell", such as in a postcode.
            max_length: Used if is_comb is set. The maximum number of characters for a fixed-
                length field.

        zFont dictionary for z$ not found; defaulting to Helvetica.rj   r4   z/Type1z/Namer3   /Fontz	/BaseFontz
/Helveticaz	/Encodingz/WinAnsiEncoding	Helveticar	   rQ   default   cp1252Type1)namecharacter_mapencodingsub_typer   character_widthsrm   rE   rn   ro   rp   rq   rr   /Lengthindirect_referencez
/ResourcesN)r6   r7   r   r   
get_objectr   from_font_resourcer   r!   r   r   r   dictzipranger
   r~   r   r*   r   itemsr   bytesr   r   set_datar   r   rZ   getattr)r9   r0   rI   rk   r   rm   rE   rn   ro   rp   rq   rr   rD   r   kvrl   font_encoding_revkeyvalueap_stream_datar:   s                        r-   r7   zTextStreamAppearance.__init__1  s   J 	   !1=3K3K3MNM**=9D1)<`acklI,:&
8(<7#Z%87#Z%8;'L)A;'4F)G. M 0<O:;o>^>^_b>c:cO,,Y7  c%*.@.JKL "1#2#C#CD dmmS)7;7I7I7O7O7Q#/3q!188DMM**# # ?Cmm>Q>Q>S"Tda1eQDk>"T"T<@MM<O<O<Q RDAqE1$K R R"00668 M
U->-B-B3-L#E*M >>!%! ? 
 	&~67&23~3F&GZ	"#)9w!19%w}>RTa'b3 ";
 *Z%&5# #U Rs   +&K2K)K	acro_formfield
annotationuser_font_nameuser_font_sizec                 	   t        t        |t        j                           }t        ddt	        |d   |d   z
        t	        |d   |d   z
        f      }|j                  t        j                  |j                  t        j                  d            }|st        d      }n|j                         }t        j                  d|      D 	cg c]  }	|	s|		 }
}	|
j                  |
j                  d      dz
        }t        |
j                  |
j                  d      dz
              }|
j                  d       d	j!                  |
      }|r|}|dkD  r|}t        t"        t        t"        |j                  d
|j                  d
t#                                 j                               }|j                  dt#                     j                         }||vrz|j%                  d      t&        vrct        t(        t*        t*        f   |j                  d
i             }|j                         j                  dt#                     j                         }|j                  |d      }t-        |      st        t"        |j                               }|j                  t.        j0                  d      }|j                  t.        j2                  d      dk(  ru|t.        j4                  j6                  z  dk(  rUdj!                  |j                  t.        j8                  g             }|j                  dg       }t;        |t<              s|g}n|j                  dd      }g }|j?                  dd      j?                  dd      j?                  dd      }d}d}|t.        j4                  j@                  z  rd}|j                  d      }d}|t.        j4                  jB                  z  rd}|j                  dtD        jF                        }d}tH        jJ                  }d|v rFt        t"        |d         j                  d|      }t        t"        |d         j                  d|      }tM        |||      } | |||||||||||       }t        jN                  |v rQt        t"        |t        jN                           j                  d!i       jQ                         D ]  \  }}|d"vs|||<    |S c c}	w )#a  
        Creates a TextStreamAppearance object from a text field annotation.

        This class method is a factory for creating a `TextStreamAppearance`
        instance by extracting all necessary information (bounding box, font,
        text content, etc.) from the PDF field and annotation dictionaries.
        It respects inheritance for properties like default appearance (`/DA`).

        Args:
            acro_form: The root AcroForm dictionary from the PDF catalog.
            field: The field dictionary object.
            annotation: The widget annotation dictionary object associated with the field.
            user_font_name: An optional user-provided font name to override the
                default. Defaults to an empty string.
            user_font_size: An optional user-provided font size to override the
                default. A value of -1 indicates no override.

        Returns:
            A new `TextStreamAppearance` instance configured for the given field.

        r   r	   rt   r   Nz/Helv 0 Tf 0 gz\sTfrQ   z/DRr   /z/Txz/ChrM   z/VrP   \z\\(z\()z\)FTz/MaxLenz/Qz/BSz/Wz/S)r   r   r    r   z/N>   /Filterr5   r3   r   r4   ))r   r   r   Rectabsget_inheritedDAr   r   r   rerS   popr   r&   removerY   r   removeprefixr   r   r   r   r   FfFTFfBitsComboOptr~   listrR   Comb	Multiliner>   r?   r   r)   r   APr   )clsr   r   r   r   r   
_rectangler   r   propfont_propertiesrm   rE   rn   document_resourcesdocument_font_resourcesr   field_flagsrI   rk   rq   rr   ro   rp   r   r    r0   new_appearance_streamr   r   s                                 r-   from_text_annotationz)TextStreamAppearance.from_text_annotation  s   > /:6T6Y6Y+Z[
#Q3z!}z!}/L+MsS]^_S`cmnocpSpOq$rs	 (55*--MM8;;TB
 "!12B!C!3!>!>!@ -/HHU<N,OXDSW4XX#''(=(=d(Ca(GH	/--o.C.CD.IA.MNO	t$XXo.
&IA&I #' ((MM%)9);< jl	#
 #5"8"8BRBT"U"`"`"b33	8N8Ns8S[l8l!%S#XeR(" '9&C&C&E&I&I'ScSe&f&q&q&s#/33ItD}- !1=3K3K3MNM ii 9 < <a@		366>%G7>>DDDI99Z556O6S6SUWXYD		$+Ii.&K	99T2&DI ||D&)11#u=EEc5Q 
299>>>G#	2J299CCCLIIdM$6$67	#))E> 0%,?CCD,WL 0%,?CCD,WL "IL_kl #!%!!
 *,,
:%z2P2S2S'TUYYZ^`bciik7
U RR16)#.	7 %$w Ys   	SS)g?)rP   )r!   r"   r#   r$   r   r&   r*   r%   r   r[   r>   r?   r   r   r   r   boolr(   r   r   r   r7   classmethodr   r;   r<   s   @r-   rC   rC   8   s~   " !$L2L2 L2 	L2
 L2 L2 L2 L2 L2 
tE%*%&-	.L2f ;? "#0#5#5$(`` cD)` 	`
 &d3:&67` ` ` ` ` !` ` SM` 
`H .2)-48 "#0#5#5$(`)*` ` DI&	`
   01` ` ` ` ` !` ` SM` 
`D  ! "O%#O%  O% %	O%
 O% O% 
 O% O%r,   rC   )%r   dataclassesr   enumr   typingr   r   r   r   _codecsr
   _codecs.core_fontmetricsr   _fontr   _utilsr   	constantsr   r   r   genericr   r   r   r   r   generic._baser   r   r   r   r   r/   r>   rC   r+   r,   r-   <module>r      s    	 !  - - ( 8  # _ _  P O!#  + + +L. L"G k%/ k%r,   