
    >iC                    b   d dl m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	m
Z
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  ej0                  e      Z G d d	e      Z ed
       G d d             Z ed
       G d d             Z ed
       G d d             Z G d d      ZeZ y)    )annotationsN)	dataclass)AnyOptionalProtocolcast)InputCommands)CHAR_TO_KEY_INFODEFAULT_TYPO_PROBABILITYQWERTY_NEIGHBORSKeyTypoType)KeyEventTypeKeyModifierc                      e Zd ZdZddZy)CommandExecutorz3Protocol for objects that can execute CDP commands.c                   K   y wN )selfcommands     b/var/www/python/tenders/Scrapper/venv/lib/python3.12/site-packages/pydoll/interactions/keyboard.py_execute_commandz CommandExecutor._execute_command   s     s   N)r   r   returnr   )__name__
__module____qualname____doc__r   r       r   r   r      s    =>r   r   T)frozenc                  *    e Zd ZU dZded<   dZded<   y)
TypoResultzResult of a typo generation.r   	typo_type str
wrong_charN)r   r   r   r   __annotations__r&   r   r   r   r"   r"      s    &Jr   r"   c                     e Zd ZU dZdZded<   dZded<   dZded<   d	Zded
<   dZ	ded<   dZ
ded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   d Zded!<   dZded"<   y#)$TimingConfigz*Configuration for realistic typing timing.gQ?floatkeystroke_minQ?keystroke_max{Gz?punctuation_ming
ףp=
?punctuation_maxg{Gz?thinking_probabilityg333333?thinking_mingffffff?thinking_maxg{Gzt?distraction_probabilityg      ?distraction_ming333333?distraction_max皙?mistake_realize_ming      ?mistake_realize_maxafter_correction_minafter_correction_maxdouble_press_min皙?double_press_maxg333333?hesitation_minhesitation_maxN)r   r   r   r   r+   r'   r-   r/   r0   r1   r2   r3   r4   r5   r6   r8   r9   r:   r;   r<   r>   r?   r@   r   r   r   r)   r)   %   s    4M5M5!OU!!OU!"&%&L%L%%*U* OU  OU !$$!%%"&%&"&%&"e""e" NE NEr   r)   c                  X    e Zd ZU dZdZded<   dZded<   dZded<   d	Zded
<   dZ	ded<   y)
TypoConfigz*Configuration for typo generation weights.g?r*   adjacent_weightg?transpose_weightr,   double_weightr.   skip_weightr=   missed_space_weightN)
r   r   r   r   rC   r'   rD   rE   rF   rG   r   r   r   rB   rB   =   s9    4!OU!"e"M5K!%%r   rB   c                  |   e Zd ZdZ ed      Z	 	 d	 	 	 	 	 d dZd Z	 	 d!	 	 	 	 	 d"dZd#d$dZ	d%dZ
d#d&d	Z	 	 d'	 	 	 	 	 d(d
Zd)dZd*dZd Z	 	 	 	 	 	 d+dZ	 	 	 	 	 	 	 	 d,dZd-dZd.dZd/dZd/dZd0dZd1dZed2d       Zd3dZd4dZ	 	 	 	 	 	 	 	 d5dZd3dZd6dZed7d       Zed8d       Z ed9d       Z!y):Keyboardz
    Keyboard input controller for Tab and WebElement.

    Provides methods for:
    - Tab: Public keyboard simulation (press, down, up, hotkey)
    - WebElement: Private text typing with optional humanization
    z .,!?;:
Nc                    || _         |xs
 t               | _        |xs
 t               | _        t        |d      | _        y)a  
        Initialize keyboard controller.

        Args:
            executor: Object with _execute_command method (Tab or WebElement).
            timing: Optional custom timing configuration.
            typo_config: Optional custom typo weights configuration.
        focusN)	_executorr)   _timingrB   _typo_confighasattr
_has_focus)r   executortimingtypo_configs       r   __init__zKeyboard.__init__S   s6     "/'7:<!(G4r   c                n   K   | j                   r#| j                  j                          d{    yy7 w)zFRe-focus the executor element before a keystroke if it supports focus.N)rP   rL   rK   r   s    r   _ensure_focuszKeyboard._ensure_focusf   s+     ??..&&((( (s   *535c                   K   t         j                  d| d|        | j                  ||       d{    t        j                  |       d{    | j                  |       d{    y7 ;7  7 	w)a  
        Press and release a key (down + wait + up).

        Args:
            key: Key to press (from Key enum).
            modifiers: Optional key modifiers (Alt=1, Ctrl=2, Meta=4, Shift=8).
            interval: Time to hold the key down in seconds.

        Example:
            await tab.keyboard.press(Key.ENTER)
            await tab.keyboard.press(Key.A, modifiers=KeyModifier.CTRL)
        zPressing key: z with modifiers: N)loggerinfodownasynciosleepup)r   key	modifiersintervals       r   presszKeyboard.pressk   sf     $ 	nSE):9+FGiiY'''mmH%%%ggcl 	(%s3   1A5A/A5A1A5)A3*A51A53A5c                   K   |\  }}t         j                  d|        t        j                  t        j
                  ||||      }| j                  j                  |       d{    y7 w)z
        Press a key down (without releasing).

        Args:
            key: Key to press down (from Key enum).
            modifiers: Optional key modifiers.
        z
Key down: )typer_   windows_virtual_key_codenative_virtual_key_coder`   N)rY   debugr	   dispatch_key_eventr   KEY_DOWNrL   r   )r   r_   r`   key_namecoder   s         r   r[   zKeyboard.down   sc      $z(,-22&&%)$(
 nn--g666s   A$A.&A,'A.c                   K   |\  }}t         j                  d|        t        j                  t        j
                  |||      }| j                  j                  |       d{    y7 w)zo
        Release a key (key up event).

        Args:
            key: Key to release (from Key enum).
        zKey up: )rd   r_   re   rf   N)rY   rg   r	   rh   r   KEY_UPrL   r   )r   r_   rj   rk   r   s        r   r^   zKeyboard.up   s`      $xz*+22$$%)$(	
 nn--g666s   A#A-%A+&A-c                &  K   t         j                  d| d| |rd| ndz          ||g}||j                  |       | j                  |      \  }}| j	                  |      }|D ]:  }| j                  ||       d{    t        j                  d       d{    < t        j                  d       d{    t        |      D ]8  }| j                  |       d{    t        j                  d       d{    : y7 7 l7 O7 *7 w)a8  
        Execute a key combination (hotkey) with up to 3 keys.

        Args:
            key1: First key (usually a modifier like Ctrl, Shift, Alt).
            key2: Second key.
            key3: Optional third key.

        Example:
            await tab.keyboard.hotkey(Key.CONTROL, Key.C)  # Ctrl+C
        zHotkey: z + r$   N)r`   r=   r7   )
rY   rZ   append_split_modifiers_and_keys_calculate_modifier_valuer[   r\   r]   reversedr^   )	r   key1key2key3keysr`   non_modifiersmodifier_valuer_   s	            r   hotkeyzKeyboard.hotkey   s	     	htfCv.$Cv,BOPd|KK#'#A#A$#G 	=77	B  	&C))C>):::--%%%	& mmC   M* 	&C''#,--%%%	& ;%  %sZ   A=D?D DD	D;D<&D"D#D?D D	DDDDc                  K   |t        j                  dt        d       |r| j                  |       d{    y|D ]8  }| j	                  |       d{    t        j                  d       d{    : y7 C7 &7 w)a  
        Type text character by character.

        Args:
            text: Text to type.
            humanize: When True, simulates human-like typing with
                variable delays and occasional typos (~2%).
            interval: Deprecated. Use humanize=True instead.

        Example:
            await tab.keyboard.type_text("Hello World", humanize=True)
            await tab.keyboard.type_text("Hello World")
        NzyThe "interval" parameter is deprecated and will be removed in a future version. Use "humanize=True" for realistic typing.   )
stacklevelr=   )warningswarnDeprecationWarning_type_text_humanized
_type_charr\   r]   )r   texthumanizera   current_chars        r   	type_textzKeyboard.type_text   s     & MMQ"	 ++D111  	&L//,///--%%%	& 2 0%s3   5BA;BA=B3A?4B=B?Bc                  K   d}|t        |      k  ro||   }|dz   t        |      k  r||dz      nd}| j                  ||       d{   }|r|dz  }| j                  |       d{    |dz  }|t        |      k  rnyy7 :7 w)z-Type text with realistic human-like behavior.r      N)len_process_char_with_typo_apply_realistic_delay)r   r   
char_indexr   	next_charshould_skip_nexts         r   r   zKeyboard._type_text_humanized   s     
3t9$
+L0:QT0JZ!^,PTI%)%A%A,PY%ZZa
--l;;;!OJ 3t9$  [
 <s*   ABB	B(B)BBBc           	       K   | j                          d{    t        j                  ||ddf      \  }}}t        j                  t
        j                  ||||||      }| j                  j                  |       d{    t        j                  t
        j                  ||||      }| j                  j                  |       d{    y7 7 R7 	w)zGType a single character, re-focusing the element before each keystroke.Nr$   r   )rd   r_   rk   r   unmodified_textre   rf   )rd   r_   rk   re   rf   )
rW   r
   getr	   rh   r   ri   rL   r   rm   )r   charr_   rk   keycodecommand_down
command_ups          r   r   zKeyboard._type_char   s       """-11$r1FT7$77&& %,$+
 nn--l;;;"55$$%,$+

 nn--j999) 	# 	< 	:s5   CCA)C CA
CCCCCc                   K   | j                          d{    | j                  t        j                         d{    | j	                  t        j                         d{    y7 S7 .7 	w)zSend backspace keypress.N)rW   r[   r   	BACKSPACEr^   rV   s    r   _type_backspacezKeyboard._type_backspace  sQ       """ii&&&ggcmm$$$ 	#&$s1   A0A*&A0A,&A0$A.%A0,A0.A0c                   K   | j                         s| j                  |       d{    y| j                  ||      }| j                  |||       d{   S 7 27 w)zQProcess character, potentially with typo. Returns True if next should be skipped.NF)_should_make_typor   _generate_typo_handle_typor   r   r   typos       r   r   z Keyboard._process_char_with_typo  s_      %%'//,///""<;&&|YEEE	 0 Fs!   %AA-AAAAc                  K   |j                   t        j                  k(  r%| j                  ||j                         d{    y|j                   t        j
                  k(  r|r| j                  ||       d{    y|j                   t        j                  k(  r| j                  |       d{    y|j                   t        j                  k(  r| j                  |       d{    y|j                   t        j                  k(  r"|dk(  r|r| j                  ||       d{    y| j                  |       d{    y7 7 7 7 e7 (7 w)z9Handle typo. Returns True if next char should be skipped.NFT )r#   r   ADJACENT_do_adjacent_typor&   	TRANSPOSE_do_transpose_typoDOUBLE_do_double_typoSKIP_do_skip_typoMISSED_SPACE_do_missed_space_typor   r   s       r   r   zKeyboard._handle_typo!  s!     >>X...((tGGG>>X///I)),	BBB>>X__,&&|444>>X]]*$$\222>>X222|s7Jy,,\9EEEool+++) H C 5 3 F 	,sj   =EE 9E9E	:6E0E16E'E(>E&E'E EE	EEEEEc                  K   | j                   }| j                  |       d{    t        j                  t	        j
                  |j                  |j                               d{    | j                          d{    t        j                  t	        j
                  |j                  |j                               d{    | j                  |       d{    y7 7 }7 g7 $7 w)z3Type wrong adjacent key, pause, backspace, correct.NrM   r   r\   r]   randomuniformr8   r9   r   r:   r;   )r   correct_charr&   rR   s       r   r   zKeyboard._do_adjacent_typo?  s     ooj)))mmFNN6+E+EvGaGabccc""$$$mmNN6668S8ST
 	
 	
 ool+++ 	*c$	
 	,sY   !C.C$AC.(C&)C. C(AC.C*C.C,C.&C.(C.*C.,C.c                  K   | j                   }| j                  |       d{    t        j                  t	        j
                  |j                  |j                               d{    | j                  |       d{    t        j                  t	        j
                  |j                  |j                               d{    | j                          d{    | j                          d{    t        j                  t	        j
                  |j                  |j                               d{    | j                  |       d{    t        j                  t	        j
                  |j                  |j                               d{    | j                  |       d{    y7 7 S7 =7 7 7 7 7 t7 17 w)z$Type chars in wrong order, then fix.N)rM   r   r\   r]   r   r   r+   r-   r8   r9   r   r:   r;   )r   r   r   rR   s       r   r   zKeyboard._do_transpose_typoJ  sU    ooi(((mmFNN6+?+?AUAUVWWWool+++mmFNN6+E+EvGaGabccc""$$$""$$$mmNN6668S8ST
 	
 	
 ool+++mmFNN6+?+?AUAUVWWWooi((( 	)W+c$$	
 	,W(s   !GF8AG(F;)GF>AGGGGG6G7AG;G<GG	AGGG2G3G;G>GGGGG	GGGc                  K   | j                   }| j                  |       d{    t        j                  t	        j
                  |j                  |j                               d{    | j                  |       d{    t        j                  t	        j
                  |j                  |j                               d{    | j                          d{    y7 7 }7 f7 #7 w)z%Type character twice, then backspace.N)rM   r   r\   r]   r   r   r<   r>   r8   r9   r   r   r   rR   s      r   r   zKeyboard._do_double_typo\  s     ool+++mmFNN6+B+BFD[D[\]]]ool+++mmFNN6+E+EvGaGabccc""$$$	 	,]+c$sY   !C.C$AC.(C&)C.C(AC.C*C.C,C.&C.(C.*C.,C.c                   K   | j                   }t        j                  t        j                  |j
                  |j                               d{    | j                  |       d{    y7 7 w)zHesitate, then type normally.N)rM   r\   r]   r   r   r?   r@   r   r   s      r   r   zKeyboard._do_skip_typoe  sT     mmFNN6+@+@&BWBWXYYYool+++ 	Z+s$   AA2A.A2(A0)A20A2c                  K   | j                   }| j                  |       d{    t        j                  t	        j
                  |j                  |j                               d{    | j                          d{    t        j                  t	        j
                  |j                  |j                               d{    | j                  |       d{    t        j                  t	        j
                  |j                  |j                               d{    | j                  |       d{    y7 7 7 7 7 l7 )7 w)z5Miss space, type next char, realize, go back and fix.Nr   )r   
space_charr   rR   s       r   r   zKeyboard._do_missed_space_typok  s	    ooi(((mmFNN6+E+EvGaGabccc""$$$mmNN6668S8ST
 	
 	
 ooj)))mmNN6668S8ST
 	
 	
 ooi((( 	)c$	
 	*	
 	)s~   !EEAE(E)E EAEE	EEAE#E$E<E=EEE	EEEEc                d  K   | j                   }t        j                  |j                  |j                        }|| j
                  v r-|t        j                  |j                  |j                        z  }t        j                         |j                  k  r-|t        j                  |j                  |j                        z  }t        j                         |j                  k  r-|t        j                  |j                  |j                        z  }t        j                  |       d{    y7 w)z/Apply realistic delay after typing a character.N)rM   r   r   r+   r-   PAUSE_CHARSr/   r0   r1   r2   r3   r4   r5   r6   r\   r]   )r   
typed_charrR   delays       r   r   zKeyboard._apply_realistic_delayz  s     v33V5I5IJ)))V^^F$:$:F<R<RSSE==?V888V^^F$7$79L9LMME==?V;;;V^^F$:$:F<R<RSSEmmE"""s   D&D0(D.)D0c                 8    t        j                          t        k  S )z!Determine if a typo should occur.)r   r   r   r   r   r   zKeyboard._should_make_typo  s     }}!999r   c                H    | j                         }| j                  |||      S )z1Generate a realistic typo based on QWERTY layout.)_select_typo_type_create_typo)r   r   r   r#   s       r   r   zKeyboard._generate_typo  s%    **,	  L)DDr   c                \   | j                   }t        j                  t        j                  t        j                  t        j
                  t        j                  g}|j                  |j                  |j                  |j                  |j                  g}t        j                  ||d      d   S )z"Select typo type based on weights.r   )weightskr   )rN   r   r   r   r   r   r   rC   rD   rE   rF   rG   r   choices)r   config
typo_typestypo_weightss       r   r   zKeyboard._select_typo_type  s    ""OOMM!!

 ""##  &&
 ~~j,!DQGGr   c           
     "    t         j                   fdt         j                   fdt         j                   fdt         j                  fdt         j
                  d i}|j                  ||t         j
                           } |       S )z!Create typo result based on type.c                 &    j                         S r   )_create_adjacent_typor   r   s   r   <lambda>z'Keyboard._create_typo.<locals>.<lambda>  s    t'A'A,'O r   c                 (    j                         S r   )_create_transpose_typo)r   r   r   s   r   r   z'Keyboard._create_typo.<locals>.<lambda>  s    (C(CLR[(\ r   c                 &    j                         S r   )_create_missed_space_typor   s   r   r   z'Keyboard._create_typo.<locals>.<lambda>  s    4+I+I,+W r   c                 :    t        t        j                         S )Nr#   r&   )r"   r   r   )r   s   r   r   z'Keyboard._create_typo.<locals>.<lambda>  s    Z(//Vb%c r   c                 6    t        t        j                        S )Nr#   )r"   r   r   r   r   r   r   z'Keyboard._create_typo.<locals>.<lambda>  s    :#F r   )r   r   r   r   r   r   r   )r   r#   r   r   typo_handlershandlers   ` ``  r   r   zKeyboard._create_typo  si     O \!!#WOOcMMF
  ##I}X]]/KLyr   c                ~    |r+|j                         rt        t        j                  |      S | j	                  |      S )z@Create transpose typo, falling back to adjacent if not possible.r   )isalphar"   r   r   r   )r   r   r   s      r   r   zKeyboard._create_transpose_typo  s4    **,(:(:yQQ)),77r   c                b    |dk(  rt        t        j                        S | j                  |      S )zBCreate missed space typo, falling back to adjacent if not a space.r   r   )r"   r   r   r   )r   r   s     r   r   z"Keyboard._create_missed_space_typo  s,    3(=(=>>)),77r   c                   | j                         }|t        vrt        t        j                  |       S t        j                  t        |         }| j                         r|j                         }t        t        j                  |      S )zCreate adjacent key typo.r   )
lowerr   r"   r   r   r   choiceisupperupperr   )original_charlowercase_charadjacent_chars      r   r   zKeyboard._create_adjacent_typo  sm     ',,.!11MRR&6~&FG  ")//1MH$5$5-PPr   c                    t         j                  t         j                  t         j                  t         j                  h}| D cg c]	  }||v s| }}| D cg c]	  }||vs| }}||fS c c}w c c}w )z,Split keys into modifiers and non-modifiers.)r   CONTROLSHIFTALTMETA)rv   modifier_keysr_   r`   rw   s        r   rp   z"Keyboard._split_modifiers_and_keys  sj     cii#((C$(ASC=,@SA	A(,I=0HII-'' BIs   	A+A+	A0!A0c                    | syt         j                  dt         j                  dt         j                  dt         j                  dit        fd| D              }|dkD  rt        t        |      S dS )z/Calculate KeyModifier value from modifier keys.Nr   r{         c              3  B   K   | ]  }j                  |d         yw)r   N)r   ).0modmodifier_maps     r   	<genexpr>z5Keyboard._calculate_modifier_value.<locals>.<genexpr>  s     BL$$S!,Bs   r   )r   r   r   r   r   sumr   r   )r`   valuer   s     @r   rq   z"Keyboard._calculate_modifier_value  sb      GGQKKHHaIIq	
 B	BB+019tK'>$>r   )NN)rQ   r   rR   zOptional[TimingConfig]rS   zOptional[TypoConfig])Nr7   )r_   r   r`   Optional[KeyModifier]ra   r*   r   )r_   r   r`   r   )r_   r   )rs   r   rt   r   ru   zOptional[Key])FN)r   r%   r   boolra   zOptional[float])r   r%   )r   r%   )r   r%   r   Optional[str]r   r   )r   r%   r   r   r   r"   r   r   )r   r%   r&   r%   )r   r%   r   r%   )r   r%   )r   r%   r   r%   )r   r%   )r   r   )r   r%   r   r   r   r"   )r   r   )r#   r   r   r%   r   r   r   r"   )r   r%   r   r"   )r   r%   r   r"   )rv   	list[Key]r   ztuple[list[Key], list[Key]])r`   r   r   r   )"r   r   r   r   	frozensetr   rT   rW   rb   r[   r^   ry   r   r   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   rp   rq   r   r   r   rI   rI   H   s    K(K
 *.,0	5!5 '5 *	5&) ,0	 ) 	.7&7"&B $(	!&!& !& "	!&F:0%FF !F 
	F ! 	
 
<	,)$%,)#  : :E
H&  !	
 
"88 Q Q ( ( ? ?r   rI   )!
__future__r   r\   loggingr   r}   dataclassesr   typingr   r   r   r   pydoll.commandsr	   pydoll.constantsr
   r   r   r   r   pydoll.protocol.input.typesr   r   	getLoggerr   rY   r   r"   r)   rB   rI   KeyboardAPIr   r   r   <module>r      s    "     ! 0 0 )  B			8	$?h ? $   $     . $& & &a? a?H r   