
    ,jw                    
   d Z ddlm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 dd	lmZmZ dd
lmZmZmZmZmZ ddlmZmZ ddlmZmZmZ  G d dej>                        Z  G d de
      Z!ddZ"	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ#	 	 	 	 	 	 	 	 	 	 	 	 ddZ$	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d dZ%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d!dZ&	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d dZ'ddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d"dZ(y)#z*This is a python implementation of clip().    )annotationsN)islice)LiteralCallableOptional
NamedTuple   )width)iter_graphemes)	HyperlinkHyperlinkParams)_SGR_STATE_DEFAULT	_SGRState_sgr_state_update_sgr_state_is_active_sgr_state_to_sequence)
TextSizingTextSizingParams)_SEQUENCE_CLASSIFY_HORIZONTAL_CURSOR_MOVEMENTINDETERMINATE_EFFECT_SEQUENCEc                      e Zd ZdZ ej
                         Z ej
                         Z ej
                         Z ej
                         Z	y)_HyperlinkActionz.Outcome of processing an OSC 8 hyperlink unit.N)
__name__
__module____qualname____doc__enumautoNO_CLOSEEMPTYOUTSIDEVISIBLE     O/home/ubuntu/waydroid_script/venv/lib/python3.12/site-packages/wcwidth/_clip.pyr   r      s9    8tyy{HDIIKEdiikGdiikGr%   r   c                  ~    e Zd ZU 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)_HyperlinkResultzn
    Result of processing an OSC 8 hyperlink.

    Only the fields relevant to each action are populated.
    r   actionr   int	close_endinner_width stropen_seqclipped_inner	close_seqclipped_width
hl_col_endN)r   r   r   r   __annotations__r+   r,   r/   r0   r1   r2   r3   r$   r%   r&   r(   r(   "   sU     IsKHcM3IsM3Jr%   r(   c                N    |"t        |      x}r|| z   } t        |      r| dz  } | S )z
    Apply SGR prefix/suffix around *result*.

    If an SGR state was captured at the first visible character, prefix the result with the
    corresponding SGR sequence and suffix with a reset if any styles are active.
    z[0m)r   r   )resultcaptured_styleprefixs      r&   _apply_sgr_wrapr9   3   s:     !+N;;6;f_F/iFMr%   c          
        t        j                  | |      \  }
}|
|fdk(  rt        t        j                        S | ||
 }t        ||||      }|dk(  rt        t        j                  |      S |	|z   }||k  s|	|k\  rt        t        j                  ||      S t        d||	z
        }||	z
  }t        ||||||d|      }t        ||||      }t        t        j                  |||j                         ||j                         ||      S )	z
    Process an OSC 8 hyperlink unit.

    Finds the matching close sequence, measures the inner text width, and determines whether the
    hyperlink is empty, outside the clip window, or visible (requiring inner-text clipping).
    )r;   )control_codestabsizeambiguous_widthr   )r+   )r+   r,   F)fillcharr=   r>   propagate_sgrr<   )r+   r,   r/   r0   r1   r2   r3   )r   
find_closer(   r   r    r
   r!   r"   maxclipr#   	make_open
make_close)textstartendr?   r=   r>   r<   params	match_endcolclose_startr+   
inner_textr,   r3   inner_clip_startinner_clip_endr0   r2   s                      r&   _process_hyperlinkrP   B   s<   ( '11$	BKY8+ 0 9 9::i,J-K
 a 0 6 6)LL{"JUcSj 0 8 8I,79 	9 1eck*3YN$n7'#M ]M
   !!####%#	 	r%   c                   i }|D ])  \  }}}|j                  |g       j                  ||f       + |j                         D ]  }	|	j                           | rt	        | j                               nd}
|rt	        |j                               nd}t	        |
|      }g }d}t        ||      }||k  r|j                  |d      D ]  \  }}|j                  |        ||k\  r|dz  };|| v r| |   \  }}|j                  |       ||z  }n$||cxk  r|
k  rn n|j                  |       |dz  }||k  rt        |j                               D ]&  }||kD  s	||   D ]  \  }}|j                  |        ( dj                  |      S )z
    Reconstruct the output string from painter's algorithm state.

    Walks columns left-to-right, interleaving escape sequences and cell content, filling gaps with
    *fillchar*.
    r;   r   r$   r	   r-   )

setdefaultappendvaluessortrB   keysmingetsortedjoin)cells	sequencesrG   rH   r?   seqs_by_colcol_posorderseq_textentriesmax_cell_colmax_seq_colmax_colpartswalk_col	col_limit_	cell_textcell_wcs                       r&   _reconstruct_painterrl      s    57K$- F w+22E83DEF%%'  ).3uzz|$2L-8#k&&()bK,,GEHGS!I
i
&??8R8 	#KAxLL"	# s?MHu %hIvLL#H0L0X&MH! i
& K$$&' 'y=*1~ '8X&''
 775>r%   c               	   g }	d}
d}d}|rt         nd}|t        |       k  r| |   }|
|k\  r'|dvr#|n| j                  d|dz         }|dk(  rnl|}@|dk(  r/t        j                  | |      }|s|	j                  |       |dz  }u|j                  d      /|r-|+t        ||j                               }|j                         }t        j                  |j                               x}rDt        | ||||||||j                         |

      }|j                  t        j                  u r0|	j                  |j                                |j                         }n|j                  t        j                  u r|j                   }n|j                  t        j"                  u r|
|j$                  z  }
|j                   }nr|	j                  |j&                         |	j                  |j(                         |	j                  |j*                         |r||}|
|j$                  z  }
|j                   }|j                  d	      x}|j                  d
      }|j                  d      }||J t-        t/        j0                  ||      ||      }|j3                  |      }|
|k\  r3|
|z   |k  r+|	j                  |j5                                |r||}|
|z  }
nC|
|k  r9|
|z   |kD  r1g dfd}t7        ||
|||||      }
|	j9                         |r
||}n|
|z  }
|j                         }|j                         }|r&t;        j                  |      rt=        d| d|      |	j                  |       |j                         }u|dk(  r^|dkD  rA|
||
|z  z
  z   }|
|k  rB||
cxk  r|k  rn n|	j                  d       |r||}|
dz  }
|
|k  r0n|	j                  d       |dz  }t?        tA        | |            }tC        ||      }|dk(  r ||
cxk  r|k  r{n nx|	j                  |       nf|
|k\  r |
|z   |k  r|	j                  |       |rF|D|}nA|
|k  r<|
|z   |kD  r4|	j                  |tE        ||
|z         tG        ||
      z
  z         |r||}|
|z  }
|t        |      z  }|t        |       k  rdjI                  |	      |fS )z
    Clip text without cursor movement (simple append-to-output path).

    Returns ``(result, captured_style)``.  The caller applies SGR wrapping.
    r   Nz	r	   r;   
sgr_paramsrI   rJ   rK   ts_metats_textts_termr<   c                (    j                  |        y )N)rS   )s_w_colts_partss      r&   	_ts_writez_clip_simple.<locals>._ts_write'  s     *r%   *Indeterminate cursor sequence at position , 	 rG   r>   r-   )rv   r.   rw   r*   rx   r*   returnNone)%r   lenfindr   matchrS   groupr   rH   r   parserP   r)   r   r    r!   r+   r"   r,   r/   r0   r1   r   r   from_paramsdisplay_widthmake_sequence_text_sizing_clipextendr   
ValueErrornextr   r
   rW   rB   rZ   )rF   rG   rH   r@   r>   r?   r=   strictr<   outputrK   idxr7   current_stylecharnext_escmhl_staterrq   rr   rs   tsts_widthrz   seqnext_tabgrapheme
grapheme_wry   s                                @r&   _clip_simpler      s   * F
C
C +/N*7&TM
D	/Cy #:$n4)
 yyq1H2~C6>"((s3Ad#q ww|$0]}G` 1- Keeg +00;;x;&%h!#quuwC
 88/888MM!''),%%'CXX!1!7!77++CXX!1!9!991==(C++CMM!**-MM!//2MM!++.$)?)61==(C++C 779--:''),''),*w/BBB$00VW& ++O<%<C(Nc$9MM""2"2"45$)?)68OC3Y3>E#9*,H++CX!#C MM(+$)?)68OCeeg '')C7==cB @Rg  MM#%%'C4<{'S7]";<Hn)c)c*(^-C-:N1HC Hn d#1HCt3788_E
 ?!c!h'E\cJ.#5MM(#!7!.3Y3+e3MM(c#sZ/?&@3uc?&RST!7!.zs8}G D	/J 776?N**r%   c                R     j                  |      }||k\  r%||z   |k  r  j                         ||       ||z   S ||k\  s||z   |k  r||z   S t        d||z
        }t        |||z         |z
  }	 j                  j
                  g }
 j                  j                  dkD  rt        t         j                         j                  j                        D ]  }|
j                  |f        t         j                  j                  t        |
      z
        D ]  }|
j                  df        n;t         j                        D ]#  }|
j                  |t        ||      z  f       % g d fd}||z   }d}|
D ]  \  }}||z   }||k  r|}||	k\  r nt        ||	      t        ||      z
  }||k(  r*|dkD  r%s|t        ||      z   }j                  ||f       n4 ||       |t        ||      z   }t        |      D ]  } |d||z           |}  ||       ||z   S )z
    Emit tokens for a text-sizing (OSC 66) sequence, clipped to (start, end).

    Calls *write_cells(text, width, col)* for each emitted cell or sequence. Returns new column
    position.
    r   r-   r   c                   sy D cg c]  }|d   	 }}t        d D              }t        j                  j                  dkD  rt	        |      ndj                  j
                  j                  j                  j                  j                  j                  j                        } t        |dj                  |      j                        j                         ||        j                          y c c}w )Nr   c              3  &   K   | ]	  }|d      yw)r	   Nr$   ).0us     r&   	<genexpr>z3_text_sizing_clip.<locals>.flush.<locals>.<genexpr>  s     2qad2s   r-   )sumr   rI   r
   r   	numeratordenominatorvertical_alignhorizontal_alignr   rZ   
terminatorr   clear)		flush_colr   textstotal_wrI   pending_unitsscaler   write_cellss	        r&   flushz _text_sizing_clip.<locals>.flush  s    ,-!1--2M22!))//A-CJ1II!6!6II$$bii&@&@	B
 	vrwwu~r}}=KKM	 	 .s   C:r	   )r   r*   r   r   )r   r   rB   rW   rI   r   r
   r   r   rF   rS   ranger   )r   rK   rG   rH   r?   r>   r   r   	rel_startrel_endunitsgrh   r   flush_col_posunit_pos	unit_textunit_wunit_endoverlap	abs_startir   r   s   `     `               @@r&   r   r   f  sN     0H e|h#-B$$&#6X~
czS8^u,X~ Aus{#I#sX~&,GIIOOE#%E	yyrww/A 	%ALL!U$	%ryyU34 	&ALL"e%	&  ( 	QALL!U1oFNOP	Q ,.M   )OMH" 	6f$y Hwh(3x+CCf!  #c(I&> >  )V!45- c(I66I7^ 8HaQ78%( 
->r%   c                 #$%& i $t               &g }	d}
d}d}d#rt        nd%	 d	 	 	 d#$%&fd}|t        |       k  r| |   }||k\  r	#|dk7  rn|dk(  rt        j                  | |      }|s%|	j                  ||
|f       |
dz  }
r#%#|dz  }e|j                  d      /r-%+t        %|j                               %|j                         }t        j                  |j                               x}rst        | |||||||j                         |
      }|j                  t        j                  u r>|	j                  ||
|j                         f       |
dz  }
r#%#|j                         }n|j                  t        j                  u r|j                   }n|j                  t        j"                  u r||j$                  z  }|j                   }n|	j                  ||
|j&                  f       |
dz  }
r#%# ||j(                  |j*                  |d	       ||j*                  z  }|	j                  ||
|j,                  f       |
dz  }
|j.                  }|j                   }>|j                  d
      x}s|j                  d      }|j                  d      }||J t1        t3        j4                  ||      ||      }t7        ||||||      }r#%#|j                         }|j                         }|r&t9        j                  |      rt;        d| d|      |j                  d      x}$|rt=        |      dz
  nd}|j                         }3|j                  d      x}a|rt=        |      nd}||z   }||k  r4||kD  r/t?        tA        ||      tC        ||            D ]  } |d|        |}|j                         }|j                  d      x}L|rt=        |      nd}|r||kD  rt;        d| d| d| d      tA        d||z
        }|j                         }|	j                  ||
|j                         f       |
dz  }
r#%#|j                         }E|dk(  r	d}|dz  }S|dk(  r|dkD  r|dz  }|dz  }i|dk(  r_|dkD  r4||||z  z
  z   }||k  rC||cxk  r|k  rn n
 |d|       |dz  }||k  r#n|	j                  ||
df       |
dz  }
r#%#|dz  }tE        tG        | |            }tI        ||      } | dk(  r.||cxk  r|k  rn n~|	j                  ||
|f       |
dz  }
rc#a%#n^||k\  r|| z   |k  r ||| |       nF||k  rA|| z   |kD  r9tA        ||      }!t?        tC        ||| z         |!z
        D ]  }" |d|!|"z           || z  }|t        |      z  }|t        |       k  rtK        $|	||      #fS )z
    Clip text with cursor movement (painter's algorithm path).

    Returns ``(result, captured_style)``.  The caller applies SGR wrapping.
    r   Nc                   t        |      D ]  }||z   }|dkD  r9j                  |dz
  d      d   dk(  r	df|dz
  <   
j                  |dz
         j                  |d      d   dk(  r	df|dz   <   
j                  |dz          j                  |d       
j                  |        | |f|<   |r$t        |      D ]  }
j	                  ||z           ryyy)zIWrite *w* cells of text *s* at *write_col*, handling wide-char splitting.r   r	   )r-   r      N)r   rX   discardpopadd)rv   w	write_colis_hyperlinkoffsetsrc_colr7   r[   r   r?   hyperlink_cellsr@   s         r&   _write_cellsz#_clip_painter.<locals>._write_cells  s    Ah 		-F&(G{uyy1g>qAQF&.]gk"''!4yy'*1-2&.]gk"''!4IIgt$##G,		- q6i( 8##I$678^3*N 4=r%   rn   r	   ro   rp   T)r   rq   rr   rs   rt   r{   r|   hpa_n
cforward_ncbackward_nz!Cursor left movement at position z would move z cells left from column z, exceeding string startr}   r   r   )F)
rv   r.   r   r*   r   r*   r   boolr   r   )&setr   r   r   r   rS   r   r   rH   r   r   rP   r)   r   r    r!   r+   r"   r,   r/   r0   r2   r1   r3   r   r   r   r   r   r   r*   r   rB   rW   r   r   r
   rl   )'rF   rG   rH   r@   r>   r?   r=   r   r<   r\   	seq_orderrK   r   r   r   r   r   r   rq   rr   rs   r   r   r   r   	n_forwardmove_endr   r   
n_backwardr   r   r   
clip_startr   r7   r[   r   r   s'      ` `                             @@@@r&   _clip_painterr     s   * )+E #O,.II
C
C +/N*7&TM +0+#'+48+ +* D	/Cy #:.46>"((s3A  #y$!78Q	 ^%;%2Nq ww|$0]}G` 1- Keeg +00;;x;&%h!#quuwC
 88/888$$c9aggi%@ANI$)?)6%%'CXX!1!7!77++CXX!1!9!991==(C++C$$c9ajj%ABNI$)?)6 !//3.241??*C$$c9akk%BCNI,,C++C 779--:''),''),*w/BBB$00VW& (UC? " !^%;%2Neeg '')C7==cB @Rg  ))6(-c%j1n1eeg  ggl33
@/9C
Oq	?9E!1"3sE?C#4FG 5$Xq!45eeg  !ww}55B1<S-!
j3.$;C5%,&>se D12 
 !S:-.eeg c9aggi89NI!7!.%%'C 4<C1HC 6>Qwq1HC 4<{'S7]";<Hn)c)$Xq#61HC Hn
   #y$!78Q	 ^%;%2N1HC t3788_E
 ?!c!  #y(!;<Q	 ^%;%2NE\cJ.#5:s33Y3+e3UCJCz)9 :Z GH ?Xq*v*=>? 	zs8}M D	/P  y%hGWWr%   r~      Tr   )r?   r=   r>   r@   r<   
overtypingc               V   t        |d      }||k  ry| j                         r| j                         r| || S d| v }	|r|	sd}|6|dk7  xr. d| v xs( d| v xs" |	xr t        t	        j
                  |             }n	|r|dk(  rd}|rt        nt        }
t         |
| |||||||dk(  |		       S )
u  
    Clip text to display columns (start, end) while preserving all terminal sequences.

    This function extracts a substring based on visible column positions rather than
    character indices. Terminal escape sequences are preserved in the output since
    they have zero display width. If a wide character (width 2) is split at
    either boundary, it is replaced with ``fillchar``.

    TAB characters (``\t``) are expanded to spaces up to the next tab stop,
    controlled by the ``tabsize`` parameter. When cursor movement is detected,
    a "painter's algorithm" is used, cursor movements actively change the write
    position, allowing cursor-left and carriage return to overwrite previously
    written cells. It is assumed that ``text`` begins at column 0.

    **OSC 8 hyperlinks** are handled specially: the visible text inside a hyperlink
    is clipped to the requested column range, and the hyperlink is rebuilt around
    the clipped text.  Empty hyperlinks (those with no remaining visible text after
    clipping) are removed::

        >>> clip('\x1b]8;;http://example.com\x07Click This link\x1b]8;;\x07', 6, 10)
        '\x1b]8;;http://example.com\x07This\x1b]8;;\x07'

    :param text: String to clip, may contain terminal escape sequences.
    :param start: Absolute starting column (inclusive, 0-indexed).
    :param end: Absolute ending column (exclusive).
    :param fillchar: Character to use when a wide character must be split at
        a boundary (default space). Must have display width of 1.
    :param tabsize: Tab stop width (default 8). Set to 0 to pass tabs through
        as zero-width (preserved in output but don't advance column position).
    :param ambiguous_width: Width to use for East Asian Ambiguous (A)
        characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts.
    :param propagate_sgr: If True (default), SGR (terminal styling) sequences
        are propagated. The result begins with any active style at the start
        position and ends with a reset sequence if styles are active.
    :param control_codes: How to handle control characters and sequences:

        - ``'parse'`` (default): Track horizontal cursor movement and clip
          hyperlink text.  Cursor overwrite is always allowed, with best effort
          results; indeterminate sequences (home, clear, reset, etc.) are
          preserved as zero-width.
        - ``'strict'``: Like ``parse``, but raises :exc:`ValueError` on
          sequences with indeterminate effects (cursor home, clear screen,
          reset, vertical movement, etc.) matching :func:`width` behavior.
          Also raises on out-of-bounds horizontal cursor movement.
        - ``'ignore'``: All control characters are treated as zero-width.
          Cursor movement is not tracked (fastest path).

    :param overtyping: Whether to use the painter's algorithm for cursor
        movement (``\b`` backspace, ``\r`` carriage return, and CSI cursor
        left/right/position sequences).  When ``None`` (default), auto-detects
        by scanning for these characters in *text*.  Set to ``False`` for improved
        performance when the caller knows *text* contains no cursor movement
        characters.  Set to ``True`` to force the painter's algorithm (useful
        for testing).  Has no effect when ``control_codes='ignore'``.

    :returns: Substring of ``text`` spanning display columns (start, end),
        with all terminal sequences preserved and wide characters at boundaries
        replaced with ``fillchar``.

    :raises ValueError: If ``control_codes='strict'`` and an indeterminate-effect
        sequence or out-of-bounds cursor movement is encountered.

    SGR (terminal styling) sequences are propagated by default. The result
    begins with any active style and ends with a reset::

        >>> clip('\x1b[1;34mHello world\x1b[0m', 6, 11)
        '\x1b[1;34mworld\x1b[0m'

    Set ``propagate_sgr=False`` to disable this behavior.

    .. versionadded:: 0.3.0

    .. versionchanged:: 0.5.0
       Added ``propagate_sgr`` parameter (default True).

    .. versionchanged:: 0.7.0
       Added ``control_codes`` parameter (default 'parse').
       OSC 8 hyperlink-aware clipping.  OSC 66 text sizing protocol support.
       Added ``overtyping`` parameter (default None, auto-detect).

    Example::

        >>> clip('hello world', 0, 5)
        'hello'
        >>> clip('中文字', 0, 3)  # Wide char split at column 3
        '中 '
        >>> clip('a\tb', 0, 10)  # Tab expanded to spaces
        'a       b'
    r   r-   rn   Fignorer   r   r   )	rF   rG   rH   r@   r>   r?   r=   r   r<   )	rB   isasciiisprintabler   r   searchr   r   r9   )rF   rG   rH   r?   r=   r>   r@   r<   r   has_escfn_clips              r&   rC   rC     s    J qME
e| ||~$**,E# nGW  X% Kt^ Jtt| JH$:AA$GH 	
 
1
)m|GG#')#
 
 
r%   )r6   r.   r7   zOptional[_SGRState]r   r.   )rF   r.   rG   r*   rH   r*   r?   r.   r=   r*   r>   r*   r<   $Literal['parse', 'strict', 'ignore']rI   r   rJ   r*   rK   r*   r   r(   )r[   zdict[int, tuple[str, int]]r\   zlist[tuple[int, int, str]]rG   r*   rH   r*   r?   r.   r   r.   )rF   r.   rG   r*   rH   r*   r@   r   r>   r*   r?   r.   r=   r*   r   r   r<   r   r   ztuple[str, Optional[_SGRState]])r   r   rK   r*   rG   r*   rH   r*   r?   r.   r>   r*   r   zCallable[[str, int, int], None]r   r*   )rF   r.   rG   r*   rH   r*   r?   r.   r=   r*   r>   r*   r@   r   r<   r   r   zOptional[bool]r   r.   ))r   
__future__r   r   	itertoolsr   typingr   r   r   r   _widthr
   r   r   	hyperlinkr   r   	sgr_stater   r   r   r   r   text_sizingr   r   escape_sequencesr   r   r   Enumr   r(   r9   rP   rl   r   r   r   rC   r$   r%   r&   <module>r      s   0 "   : :  $ 10 0
 6> >
tyy z "?
?? 
? 	?
 ? ? 8? ? ? 
? ?D4%4)4 4 
	4
 4 	4nh+
h+h+ 
h+
 h+ h+ h+ h+ h+ 8h+ %h+VRR	R R 
	R
 R R 1R 	RjcX
cXcX 
cX
 cX cX cX cX cX 8cX %cXV :A!%H
HH 
H
 H H H H 8H H 	Hr%   