
    IjD                     D   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m	Z	m
Z
 ddlmZ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 ddlmZ ddlmZ ddl m!Z! ddl"m#Z#  ej$        d          Z% G d de          Z&e&j'        Z(defdZ)d-dee*ef         dz  ddfdZ+ e)            a, G d de
d          Z- G d de          Z. G d de.          Z/ G d  d!e.          Z0 G d" d#e.          Z1de2fd$Z3d%ede*fd&Z4d'ed(e2defd)Z5d*e	de6e	d+f         fd,Z7dS ).zEProvides common utilities to support Rich in cmd2-based applications.    N)Mapping)Enum)IOAny	TypedDict)ConsoleConsoleRenderableJustifyMethodOverflowMethodRenderableType)Padding)is_expandable)	rich_cast)	StyleType)ColumnTable)Text)Theme)RichHelpFormatter   )DEFAULT_CMD2_STYLESz\x1b\[[0-9;]*mc                   6    e Zd ZdZdZdZdZdefdZdefdZ	dS )	
AllowStylez+Values for ``cmd2.rich_utils.ALLOW_STYLE``.AlwaysNeverTerminalreturnc                 *    t          | j                  S )zEReturn value instead of enum name for printing in cmd2's set command.)strvalueselfs    g/home/jenkins/jenkins/workspace/simtester-sanitize/venv/lib/python3.11/site-packages/cmd2/rich_utils.py__str__zAllowStyle.__str__0   s    4:    c                 *    t          | j                  S )zSReturn quoted value instead of enum description for printing in cmd2's set command.)reprr    r!   s    r#   __repr__zAllowStyle.__repr__4   s    DJr%   N)
__name__
__module____qualname____doc__ALWAYSNEVERTERMINALr   r$   r(    r%   r#   r   r   )   s_        55FEH     #            r%   r   r   c                      t          j                    } |                     t          j                                                   t          | d          S )zCreate a default theme for the application.

    This theme combines the default styles from cmd2, rich-argparse, and Rich.
    T)inherit)r   copyupdater   stylesr   )
app_styless    r#   _create_default_themer7   =   sI    
 %)++J'.3355666T****r%   r5   c                 `   i }|                     t                      j                   | |                     |            t          |          at
          j                                        t          j                                        z  D ]!}t          j        |         t
          j        |<   "dS )zSet the Rich theme used by cmd2.

    Call set_theme() with no arguments to reset to the default theme.
    This will clear any custom styles that were previously applied.

    :param styles: optional mapping of style names to styles
    N)r4   r7   r5   r   	APP_THEMEr   keys)r5   r6   names      r#   	set_themer<   G   s     (*J+--4555 &!!!j!!I "(--//)2B2G2G2I2II @ @)2)9$)? &&@ @r%   c                   x    e Zd ZU dZedz  ed<   edz  ed<   edz  ed<   edz  ed<   edz  ed<   eed<   eed	<   dS )
RichPrintKwargsa  Keyword arguments that can be passed to rich.console.Console.print() via cmd2's print methods.

    See Rich's Console.print() documentation for full details on these parameters.
    https://rich.readthedocs.io/en/stable/reference/console.html#rich.console.Console.print

    Note: All fields are optional (total=False). If a key is not present in the
    dictionary, Rich's default behavior for that argument will apply.
    Njustifyoverflowno_wrapwidthheightcropnew_line_start)	r)   r*   r+   r,   r
   __annotations__r   boolintr0   r%   r#   r>   r>   d   s           T!!!!t####D[:$J
JJJr%   r>   F)totalc            !           e Zd ZdZdddee         dz  deddf fdZd%dZ	 	 	 d&d	ed
e	dz  de	dz  de	dz  dede
f fdZddddddddddddddddededededz  dedz  dedz  de	dz  de	dz  de	dz  d
e	dz  dedz  dedz  de	de	dz  de	ddf  fdZddddddddd d!	dededededz  dedz  de	dz  de	dz  d
e	dz  d"e	d#eddf fd$Z xZS )'Cmd2BaseConsolezBase class for all cmd2 Rich consoles.

    This class handles the core logic for managing Rich behavior based on
    cmd2's global settings, such as `ALLOW_STYLE` and `APP_THEME`.
    NfilerM   kwargsr   c          	         d|v rt          d          d|v rt          d          d|v rt          d          d|v rt          d          d	}d	}d
}t          t          j        k    rd}d}t	          |          }|j        }nDt          t          j        k    rt	          |          }|j        }nt          t          j        k    rd
} t                      j
        d||rdnd	||t          d| t          j                    | _        d	S )a5  Cmd2BaseConsole initializer.

        :param file: optional file object where the console should write to.
                     Defaults to sys.stdout.
        :param kwargs: keyword arguments passed to the parent Console class.
        :raises TypeError: if disallowed keyword argument is passed in.
        color_systemz_Passing 'color_system' is not allowed. Its behavior is controlled by the 'ALLOW_STYLE' setting.force_terminalzaPassing 'force_terminal' is not allowed. Its behavior is controlled by the 'ALLOW_STYLE' setting.force_interactivezdPassing 'force_interactive' is not allowed. Its behavior is controlled by the 'ALLOW_STYLE' setting.themezcPassing 'theme' is not allowed. Its behavior is controlled by the global APP_THEME and set_theme().NFTrL   	truecolor)rM   rP   rQ   rR   rS   r0   )	TypeErrorALLOW_STYLEr   r-   r   is_interactiver/   is_terminalr.   super__init__r9   	threadinglocal_thread_local)r"   rM   rN   rQ   rR   allow_styletmp_console	__class__s          r#   rZ   zCmd2BaseConsole.__init__~   se    V##}~~~v%%s   &((v   fu   '+)-*+++!NK "t,,,K + :J///!t,,,K%1KKJ,,,"N 	
(3=)/	
 	
 	
 	
 	
 '_..r%   c                     d| _         t          )z<Override which raises BrokenPipeError instead of SystemExit.T)quietBrokenPipeErrorr!   s    r#   on_broken_pipezCmd2BaseConsole.on_broken_pipe   s    
r%   text	highlightmarkupemojic                     |t          | j        dd          }|t          | j        dd          }|t          | j        dd          } t                      j        |f|||d|S )zROverride to ensure formatting overrides passed to print() and log() are respected.Nrh   rg   rf   )rf   rg   rh   )getattrr]   rY   
render_str)r"   re   rf   rg   rh   rN   r`   s         r#   rk   zCmd2BaseConsole.render_str   s{     =D.>>E>T/4@@F 2KFFI!uww!$b)FRWbb[abbbr%    
TFsependstyler?   r@   rA   rh   rg   rf   rB   rC   rD   	soft_wraprE   objectsro   rp   rq   r?   r@   rA   rB   rC   rD   rr   rE   c                J   t          | }|| j        _        || j        _        |	| j        _        	  t                      j        ||||||||||	|
||||d d| j        _        d| j        _        d| j        _        dS # d| j        _        d| j        _        d| j        _        w xY w)a7  Override to support ANSI sequences and address a bug in Rich.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being printed. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.

        Additionally, it works around a bug in Rich where complex renderables
        (like Table and Rule) may not receive formatting settings passed to print().
        By temporarily injecting these settings into thread-local storage, we ensure
        that all internal rendering calls within the print() operation respect the
        requested overrides.

        There is an issue on Rich to fix the latter:
        https://github.com/Textualize/rich/issues/4028
        rn   N)prepare_objects_for_renderingr]   rh   rg   rf   rY   print)r"   ro   rp   rq   r?   r@   rA   rh   rg   rf   rB   rC   rD   rr   rE   rs   prepared_objectsr`   s                    r#   rv   zCmd2BaseConsole.print   s    D 9'B $) $*!'0$	0EGGM!!##-   & (,D$(,D%+/D((( (,D$(,D%+/D(////s   &A< <&B"r   	ro   rp   rq   r?   rh   rg   rf   
log_locals_stack_offsetry   rz   c       	         F   t          |
 }|| j        _        || j        _        || j        _        	  t                      j        ||||||||||	dz   d	 d| j        _        d| j        _        d| j        _        dS # d| j        _        d| j        _        d| j        _        w xY w)a2  Override to support ANSI sequences and address a bug in Rich.

        This method calls [cmd2.rich_utils.prepare_objects_for_rendering][] on the
        objects being logged. This ensures that strings containing ANSI style
        sequences are converted to Rich Text objects, so that Rich can correctly
        calculate their display width.

        Additionally, it works around a bug in Rich where complex renderables
        (like Table and Rule) may not receive formatting settings passed to log().
        By temporarily injecting these settings into thread-local storage, we ensure
        that all internal rendering calls within the log() operation respect the
        requested overrides.

        There is an issue on Rich to fix the latter:
        https://github.com/Textualize/rich/issues/4028
        r   rx   N)ru   r]   rh   rg   rf   rY   log)r"   ro   rp   rq   r?   rh   rg   rf   ry   rz   rs   rw   r`   s               r#   r|   zCmd2BaseConsole.log  s    : 9'B $) $*!'0$	0EGGK!#%+a/    (,D$(,D%+/D((( (,D$(,D%+/D(////s   $A: :&B )r   N)NNN)r)   r*   r+   r,   r   r   r   rZ   rd   rG   r   rk   r   r
   r   rH   rv   r|   __classcell__r`   s   @r#   rK   rK   w   s          $:/ :/ :/ gn:/ 	:/
 
:/ :/ :/ :/ :/ :/x    "&"!c cc $;c t	c
 d{c c 
c c c c c c* "&(,*.#!"!% !!%$!?0 ?0 ?0?0 ?0 	?0
 4?0 %?0 !4'?0 ?0 d{?0 t?0 $;?0 Tz?0 d
?0 ?0 $;?0  !?0" 
#?0 ?0 ?0 ?0 ?0 ?0H "&(,!"!% 60 60 6060 60 	60
 460 %60 d{60 t60 $;60 60 60 
60 60 60 60 60 60 60 60 60 60r%   rK   c                   D     e Zd ZdZdddee         dz  ddf fdZ xZS )Cmd2GeneralConsolezRich console for general-purpose printing.

    It enables soft wrap and disables Rich's automatic detection for markup,
    emoji, and highlighting. These defaults can be overridden in calls to the
    console's or cmd2's print methods.
    NrL   rM   r   c                T    t                                          |dddd           dS )zCmd2GeneralConsole initializer.

        :param file: optional file object where the console should write to.
                     Defaults to sys.stdout.
        TFrM   rr   rg   rh   rf   NrY   rZ   r"   rM   r`   s     r#   rZ   zCmd2GeneralConsole.__init__S  s?     	 	 	
 	
 	
 	
 	
r%   r)   r*   r+   r,   r   r   rZ   r}   r~   s   @r#   r   r   K  l          26 
 
 
3$ 
$ 
 
 
 
 
 
 
 
 
 
r%   r   c                   D     e Zd ZdZdddee         dz  ddf fdZ xZS )Cmd2RichArgparseConsolea/  Rich console for rich-argparse output.

    Ensures long lines in help text are not truncated by disabling soft_wrap,
    which conflicts with rich-argparse's explicit no_wrap and overflow settings.

    Since this console is used to print error messages which may not be intended
    for Rich formatting, it disables Rich's automatic detection for markup, emoji,
    and highlighting. Because rich-argparse does markup and highlighting without
    involving the console, disabling these settings does not affect the library's
    internal functionality.
    NrL   rM   r   c                T    t                                          |dddd           dS )zCmd2RichArgparseConsole initializer.

        :param file: optional file object where the console should write to.
                     Defaults to sys.stdout.
        Fr   Nr   r   s     r#   rZ   z Cmd2RichArgparseConsole.__init__o  ?     	 	 	
 	
 	
 	
 	
r%   r   r~   s   @r#   r   r   b  sl        
 
 26 
 
 
3$ 
$ 
 
 
 
 
 
 
 
 
 
r%   r   c                   D     e Zd ZdZdddee         dz  ddf fdZ xZS )Cmd2ExceptionConsolezRich console for printing exceptions and Rich Tracebacks.

    Ensures that output is always word-wrapped for readability and disables
    Rich's automatic detection for markup, emoji, and highlighting to prevent
    interference with raw error data.
    NrL   rM   r   c                T    t                                          |dddd           dS )zCmd2ExceptionConsole initializer.

        :param file: optional file object where the console should write to.
                     Defaults to sys.stdout.
        Fr   Nr   r   s     r#   rZ   zCmd2ExceptionConsole.__init__  r   r%   r   r~   s   @r#   r   r   ~  r   r%   r   c                  (    t                      j        S )z Return the width of the console.)r   rB   r0   r%   r#   console_widthr     s    99?r%   re   c                     t          ddddt                    }|                                5 }|                    | d           ddd           n# 1 swxY w Y   |                                S )av  Convert a Rich Text object to a string.

    This function's purpose is to render a Rich Text object, including any styles (e.g., color, bold),
    to a plain Python string with ANSI style sequences. It differs from `text.plain`, which strips
    all formatting.

    :param text: the text object to convert
    :return: the resulting string with ANSI styles preserved.
    TrT   F)rQ   rP   rr   no_colorrS    )rp   N)r   r9   capturerv   get)re   consoler   s      r#   rich_text_to_stringr     s        G 
		 $gd###$ $ $ $ $ $ $ $ $ $ $ $ $ $ $;;==s   AAA
renderablelevelc                     t          | t          t          f          r9t          j        t          d                    }|                    |            |} t          j        | |          S )ap  Indent a Rich renderable.

    When soft-wrapping is enabled, a Rich console is unable to properly print a
    Padding object of indented text, as it truncates long strings instead of wrapping
    them. This function provides a workaround for this issue, ensuring that indented
    text is printed correctly regardless of the soft-wrap setting.

    For non-text objects, this function merely serves as a convenience
    wrapper around Padding.indent().

    :param renderable: a Rich renderable to indent.
    :param level: number of characters to indent.
    :return: a Padding object containing the indented content.
    fold)r@   )	
isinstancer   r   r   gridr   add_rowr   indent)r   r   	text_grids      r#   r   r     s_     *sDk** Jvv66677	*%%%
>*e,,,r%   rs   .c                  P   t          |           }t          |          D ]y\  }}t          |          }t          |t                    st          |          r9t          |          }t                              |          rt          j
        |          ||<   zt          |          S )a  Prepare a tuple of objects for printing by Rich's Console.print().

    This function processes objects to ensure they are rendered correctly by Rich.
    It inspects each object and, if its string representation contains ANSI style
    sequences, it converts the object to a Rich Text object. This ensures Rich can
    properly parse the non-printing codes for accurate display width calculation.

    Objects that already implement the Rich console protocol or are expandable
    by its pretty printer are left untouched, as they can be handled directly by
    Rich's native renderers.

    :param objects: objects to prepare
    :return: a tuple containing the processed objects.
    )list	enumerater   r   r	   r   r   ANSI_STYLE_SEQUENCE_REsearchr   	from_ansituple)rs   object_listiobjr   renderable_as_strs         r#   ru   ru     s     w--KK(( ? ?3 s^^
 j"344 	j8Q8Q 	  
OO!(():;; 	?!^,=>>KNr%   )N)8r,   rer[   collections.abcr   enumr   typingr   r   r   rich.consoler   r	   r
   r   r   rich.paddingr   rich.prettyr   rich.protocolr   
rich.styler   
rich.tabler   r   	rich.textr   
rich.themer   rich_argparser   r5   r   compiler   r   r/   rV   r7   r   r<   r9   r>   rK   r   r   r   rH   r   r   r   r   ru   r0   r%   r#   <module>r      s   K K 				     # # # # # #                             !           % % % % % % # # # # # #                                + + + + + + ' ' ' ' ' ' $$566                " !+u + + + +@ @gc9n-4 @ @ @ @ @4 "!##	    iu    &Q0 Q0 Q0 Q0 Q0g Q0 Q0 Q0h
 
 
 
 
 
 
 
.
 
 
 
 
o 
 
 
8
 
 
 
 
? 
 
 
.s    
d s    ,-~ -c -g - - - -0C E#s(O      r%   