
    hh\                     Z   d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlm	Z	 ddlm
Z ddlmZ  G d	 d
e      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zd!dZd"dZd Zd#dZd Zd"d Zy)$a  A module for console attributes, special characters and functions.

The target architectures {linux, macos, windows} support inline encoding for
all attributes except color. Windows requires win32 calls to manipulate the
console color state.

Usage:

  # Get the console attribute state.
  out = log.out
  con = console_attr.GetConsoleAttr(out=out)

  # Get the ISO 8879:1986//ENTITIES Box and Line Drawing characters.
  box = con.GetBoxLineCharacters()
  # Print an X inside a box.
  out.write(box.dr)
  out.write(box.h)
  out.write(box.dl)
  out.write('\n')
  out.write(box.v)
  out.write('X')
  out.write(box.v)
  out.write('\n')
  out.write(box.ur)
  out.write(box.h)
  out.write(box.ul)
  out.write('\n')

  # Print the bullet characters.
  for c in con.GetBullets():
    out.write(c)
  out.write('\n')

  # Print FAIL in red.
  out.write('Epic ')
  con.Colorize('FAIL', 'red')
  out.write(', my first.')

  # Print italic and bold text.
  bold = con.GetFontCode(bold=True)
  italic = con.GetFontCode(italic=True)
  normal = con.GetFontCode()
  out.write('This is {bold}bold{normal}, this is {italic}italic{normal},'
            ' and this is normal.\n'.format(bold=bold, italic=italic,
                                            normal=normal))

  # Read one character from stdin with echo disabled.
  c = con.GetRawKey()
  if c is None:
    print 'EOF\n'

  # Return the display width of a string that may contain FontCode() chars.
  display_width = con.DisplayWidth(string)

  # Reset the memoized state.
  con = console_attr.ResetConsoleAttr()

  # Print the console width and height in characters.
  width, height = con.GetTermSize()
  print 'width={width}, height={height}'.format(width=width, height=height)

  # Colorize table data cells.
  fail = console_attr.Colorizer('FAIL', 'red')
  pass = console_attr.Colorizer('PASS', 'green')
  cells = ['label', fail, 'more text', pass, 'end']
  for cell in cells;
    if isinstance(cell, console_attr.Colorizer):
      cell.Render()
    else:
      out.write(cell)
    )absolute_import)division)unicode_literalsN)console_attr_osencoding)textc                       e Zd ZdZy)BoxLineCharacterszBox/line drawing characters.

  The element names are from ISO 8879:1986//ENTITIES Box and Line Drawing//EN:
    http://www.w3.org/2003/entities/iso8879doc/isobox.html
  N__name__
__module____qualname____doc__     W/var/www/html/dev/engine/venv/lib/python3.12/site-packages/fire/console/console_attr.pyr   r   i   s    r   r   c                   h    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZy)BoxLineCharactersUnicodez?unicode Box/line drawing characters (cp437 compatible unicode).u   ┐u   ┌u   ─u   ┬u   ┴u   ┘u   └u   │u   ┼u   ┤u   ├u   ╗u   ╔u   ═u   ╦u   ╩u   ╝u   ╚u   ║u   ╬u   ╣u   ╠Nr   r   r   r   dldrhhdhuulurvvhvlvrd_dld_drd_hd_hdd_hud_uld_urd_vd_vhd_vld_vrr   r   r   r   r   q   ss    G""!""""!"""	$	$#	$	$	$	$#	$	$	$r   r   c                   h    e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZy)BoxLineCharactersAsciiz"ASCII Box/line drawing characters.+-|#=Nr   r   r   r   r.   r.      ss    *
"
"	!
"
"
"
"	!
"
"
"	$	$#	$	$	$	$#	$	$	$r   r.   c                   0    e Zd ZdZdZdZdZdZdZdZ	dZ
dZy)BoxLineCharactersScreenReader N)r   r   r   r   r   r   r   r   r   r   r    r!   r   r   r   r5   r5      s/    
"
"
"
"
"
"
"
"
"r   r5   c                       e Zd ZdZy)ProgressTrackerSymbols%Characters used by progress trackers.Nr   r   r   r   r8   r8      s    -r   r8   c                       e Zd ZdZed        Z ej                  dgej                  j                        Z
 ej                  dgej                  j                        ZdZdZdZy	)
ProgressTrackerSymbolsUnicoder9   c                 
    g dS )N)u   ⠏u   ⠛u   ⠹u   ⠼u   ⠶u   ⠧r   selfs    r   
spin_marksz(ProgressTrackerSymbolsUnicode.spin_marks   s    55r   u   ✓)	text_typeXr0   .   N)r   r   r   r   propertyr?   r	   	TypedText	TextTypes
PT_SUCCESSsuccess
PT_FAILUREfailedinterruptednot_startedprefix_lengthr   r   r   r;   r;      sd    -6 6 DNNE7dnn.G.GH'4>>3%4>>+D+DE&++-r   r;   c                   4    e Zd ZdZed        ZdZdZdZdZ	dZ
y)	ProgressTrackerSymbolsAsciir9   c                 
    g dS )N)r1   /r0   \r   r=   s    r   r?   z&ProgressTrackerSymbolsAscii.spin_marks   s    !!r   OKrA   r0   rB      N)r   r   r   r   rD   r?   rH   rJ   rK   rL   rM   r   r   r   rO   rO      s2    -" " '&++-r   rO   c                       e Zd ZdZdZdddddZdZd	Zd
ZdZ	ddZ
d ZddZd Zd Zd Zd Zd Zd Zd Zd dZd Zd Zd Zd Zd Zd Zd Zy)!ConsoleAttra;  Console attribute and special drawing characters and functions accessor.

  Use GetConsoleAttr() to get a global ConsoleAttr object shared by all callers.
  Use ConsoleAttr() for abstracting multiple consoles.

  If _out is not associated with a console, or if the console properties cannot
  be determined, the default behavior is ASCII art with no attributes.

  Attributes:
    _ANSI_COLOR: The ANSI color control sequence dict.
    _ANSI_COLOR_RESET: The ANSI color reset control sequence string.
    _csi: The ANSI Control Sequence indicator string, '' if not supported.
    _encoding: The character encoding.
        ascii: ASCII art. This is the default.
        utf8: UTF-8 unicode.
        win: Windows code page 437.
    _font_bold: The ANSI bold font embellishment code string.
    _font_italic: The ANSI italic font embellishment code string.
    _get_raw_key: A function that reads one keypress from stdin with no echo.
    _out: The console output file stream.
    _term: TERM environment variable value.
    _term_size: The terminal (x, y) dimensions in characters.
  Nz31;1mz33;1m32mz34;1m)redyellowgreenbluez39;0m)u   ▪u   ◆u   ▸u   ▫u   ◇u   ▹)u   ■u   ≡u   ∞u   Φ   ·)o*r/   r0   c                 "   |s| j                         }n|dk(  rd}|xs d| _        |rdn#t        j                  dd      j	                         | _        | j                         rd| _        d| _        d| _	        nd	| _        d| _        d| _	        d
}| j                  dk(  r2|s0t               | _        | j                  | _        t               | _        n| j                  dk(  r2|s0t               | _        | j                   | _        t#               | _        n@t%               | _        |rt'               | _        | j(                  | _        t#               | _        t+        j,                         g| _        |rdnt+        j0                         | _        i | _        y	)a  Constructor.

    Args:
      encoding: Encoding override.
        ascii -- ASCII art. This is the default.
        utf8 -- UTF-8 unicode.
        win -- Windows code page 437.
      suppress_output: True to create a ConsoleAttr that doesn't want to output
        anything.
    wincp437ascii TERMz[14NFutf8)r   r   )_GetConsoleEncoding	_encodingosgetenvlower_termSupportsAnsi_csi
_font_bold_font_italicr   _box_line_characters_BULLETS_UNICODE_bulletsr;   _progress_tracker_symbols_BULLETS_WINDOWSrO   r.   r5   _BULLETS_ASCIIr   GetRawKeyFunction_get_raw_keyGetTermSize
_term_size_display_width_cache)r>   r   suppress_outputis_screen_readers       r   __init__zConsoleAttr.__init__   s]    ))+h	U	h(DN&BIIfb,A,G,G,IDJ  didoddidod ~~(8":"<d++dm'D'Fd$	7	"+;":"<d++dm'B'Dd$"8":d	$A$C!))dm'B'Dd$ )::<=D!'B'B'D 	O !#Dr   c                 t    t        t        j                  dd      }|sy|j                         }d|v ryd|v ryy)zGets the encoding as declared by the stdout stream.

    Returns:
      str, The encoding name or None if it could not be determined.
    r   Nutf-8rg   ra   )getattrsysstdoutrl   )r>   console_encodings     r   rh   zConsoleAttr._GetConsoleEncoding1  sG     szz:t<'--/""	$	$r   c                     |r ||      }| j                   rD|| j                  v r6dj                  | j                   | j                  |   | j                  |      S |S )ah  Generates a colorized string, optionally justified.

    Args:
      string: The string to write.
      color: The color name -- must be in _ANSI_COLOR.
      justify: The justification function, no justification if None. For
        example, justify=lambda s: s.center(10)

    Returns:
      str, The colorized string that can be printed to the console.
    z*{csi}{color_code}{string}{csi}{reset_code})csi
color_code
reset_codestring)ro   _ANSI_COLORformat_ANSI_COLOR_RESETr>   r   colorjustifys       r   ColorizezConsoleAttr.ColorizeA  se     vfyyUd...9@@ii%%e,++	 A   Mr   c                     t        |t              r|j                  | j                        }t        || j                  d      S )a8  Converts a console output string buf to unicode.

    Mainly used for testing. Allows test comparisons in unicode while ensuring
    that unicode => encoding => unicode works.

    Args:
      buf: The console output string to convert.

    Returns:
      The console output string buf converted to unicode.
    replace)
isinstancestrencoderi   )r>   bufs     r   ConvertOutputToUnicodez"ConsoleAttr.ConvertOutputToUnicodeX  s3     #sJJt~~&csDNNI..r   c                     | j                   S )a  Returns the box/line drawing characters object.

    The element names are from ISO 8879:1986//ENTITIES Box and Line Drawing//EN:
      http://www.w3.org/2003/entities/iso8879doc/isobox.html

    Returns:
      A BoxLineCharacters object for the console output device.
    )rr   r=   s    r   GetBoxLineCharactersz ConsoleAttr.GetBoxLineCharactersh  s     $$$r   c                     | j                   S )a  Returns the bullet characters list.

    Use the list elements in order for best appearance in nested bullet lists,
    wrapping back to the first element for deep nesting. The list size depends
    on the console implementation.

    Returns:
      A tuple of bullet characters.
    )rt   r=   s    r   
GetBulletszConsoleAttr.GetBulletss  s     ==r   c                     | j                   S )zReturns the progress tracker characters object.

    Returns:
      A ProgressTrackerSymbols object for the console output device.
    )ru   r=   s    r   GetProgressTrackerSymbolsz%ConsoleAttr.GetProgressTrackerSymbols  s     )))r   c                     | j                   S )zReturns the control sequence indicator string.

    Returns:
      The control sequence indicator string or None if control sequences are not
      supported.
    )ro   r=   s    r   GetControlSequenceIndicatorz'ConsoleAttr.GetControlSequenceIndicator  s     99r   c                     | j                   r|j                  | j                         syd}|D ]  }|dz  }|j                         s |S  |S )aV  Returns the control sequence length at the beginning of buf.

    Used in display width computations. Control sequences have display width 0.

    Args:
      buf: The string to check for a control sequence.

    Returns:
      The control sequence length at the beginning of buf or 0 if buf does not
      start with a control sequence.
    r      )ro   
startswithisalpha)r>   r   ncs       r   GetControlSequenceLenz!ConsoleAttr.GetControlSequenceLen  sR     99CNN4995	A 1fa	
H	 Hr   c                     | j                   S )zReturns the current encoding.)ri   r=   s    r   GetEncodingzConsoleAttr.GetEncoding  s    >>r   c                     | j                   syg }|r|j                  | j                         |r|j                  | j                         dj	                  | j                   dj                  |            S )a}  Returns a font code string for 0 or more embellishments.

    GetFontCode() with no args returns the default font code string.

    Args:
      bold: True for bold embellishment.
      italic: True for italic embellishment.

    Returns:
      The font code string for the requested embellishments. Write this string
        to the console output to control the font settings.
    rc   z{csi}{codes}m;)r   codes)ro   appendrp   rq   r   join)r>   bolditalicr   s       r   GetFontCodezConsoleAttr.GetFontCode  s]     99Ell4??#ll4$$%!!diisxx!GGr   c                 *     | j                   d          S )zReads one key press from stdin with no echo.

    Returns:
      The key name, None for EOF, <KEY-*> for function keys, otherwise a
      character.
    r   )ry   r=   s    r   	GetRawKeyzConsoleAttr.GetRawKey  s      4Q!!r   c                     | j                   S )zReturns the TERM environment variable for the console.

    Returns:
      str: A str that describes the console's text capabilities
    )rm   r=   s    r   GetTermIdentifierzConsoleAttr.GetTermIdentifier  s     ::r   c                     | j                   S )zReturns the terminal (x, y) dimensions in characters.

    Returns:
      (x, y): A tuple of the terminal x and y dimensions.
    )r{   r=   s    r   rz   zConsoleAttr.GetTermSize  s     ??r   c                    t        |t              st        |      S | j                  j	                  |d      }||S d}d}d}|t        |      k  r| j
                  r6||d j                  | j
                        r|| j                  ||d       z  }n2||   dk(  rt        ||      }d}|dz  }n|t        ||         z  }|dz  }|t        |      k  rt        ||      }|| j                  |<   |S )zReturns the display width of buf, handling unicode and ANSI controls.

    Args:
      buf: The string to count from.

    Returns:
      The display width of buf, handling unicode and ANSI controls.
    Nr   
r   )
r   r   lenr|   getro   r   r   maxGetCharacterDisplayWidth)r>   r   cachedwidth	max_widthis         r   DisplayWidthzConsoleAttr.DisplayWidth  s    c3Xo&&**35FmEI	A
c#h,	s12w))$))4	T''AB00q6T> y)		Q)#a&11	Q c#h, E9%I%.Dc"r   c                 F   | j                   r|s|dfgS g }d}|t        |      k  r{|j                  | j                   |      }|dk  r|j                  ||d df       	 |S ||| }|| j	                  ||d       z   }|j                  |||| f       |t        |      k  r{|S )a  Returns a list of (normal_string, control_sequence) tuples from buf.

    Args:
      buf: The input string containing one or more control sequences
        interspersed with normal strings.

    Returns:
      A list of (normal_string, control_sequence) tuples.
    rc   r   N)ro   r   findr   r   )r>   r   seqr   r   normals         r   SplitIntoNormalAndControlz%ConsoleAttr.SplitIntoNormalAndControl  s     99CBi[
C	A
c#h,
((499a
 a	
Q

CGR=! J 1Qxf
d((QR1
1a	jj&#a(#$ c#h, Jr   c                     g }d}d}d}| j                  |      D ]L  \  }}d}	 ||z
  }	|t        |      z  }||k  rn#|j                  ||d|	 z          d}d}d}||	d }<|||z   z  }N |s|r|j                  |       |S )a  Splits line into width length chunks.

    Args:
      line: The line to split.
      width: The width of each chunk except the last which could be smaller than
        width.

    Returns:
      A list of chunks, all but the last with display width == width.
    rc   r   FTN)r   r   r   )
r>   liner   lineschunkwkeepr   controlr   s
             r   	SplitLinezConsoleAttr.SplitLine  s     EE	AD99$?  dAI	S[:
UVBQZ'(  ve  ll5Lr   c                 `    | j                   dk7  xr d| j                  v xs d| j                  v S )Nrb   screenxterm)ri   rm   r=   s    r   rn   zConsoleAttr.SupportsAnsi5  s2    NNg% >#<w$**'<?r   NFN)FF)r   r   r   r   _CONSOLE_ATTR_STATEr   r   rs   rv   rw   r   rh   r   r   r   r   r   r   r   r   r   r   r   rz   r   r   r   rn   r   r   r   rV   rV      s    0  	+ ?6'.7#r ./ 	%
**H,"#J0@?r   rV   c                   P    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 Zd ZddZy)	ColorizerzResource string colorizer.

  Attributes:
    _con: ConsoleAttr object.
    _color: Color name.
    _string: The string to colorize.
    _justify: The justification function, no justification if None. For example,
      justify=lambda s: s.center(10)
  Nc                 L    t               | _        || _        || _        || _        y)zConstructor.

    Args:
      string: The string to colorize.
      color: Color name used to index ConsoleAttr._ANSI_COLOR.
      justify: The justification function, no justification if None. For
        example, justify=lambda s: s.center(10)
    N)GetConsoleAttr_con_color_string_justifyr   s       r   r   zColorizer.__init__E  s#      DIDKDLDMr   c                 2    | j                   t        |      k(  S r   r   r   r>   others     r   __eq__zColorizer.__eq__S  s    <<3u:%%r   c                     | |k(   S r   r   r   s     r   __ne__zColorizer.__ne__V  s    u}r   c                 2    | j                   t        |      kD  S r   r   r   s     r   __gt__zColorizer.__gt__Y      <<#e*$$r   c                 2    | j                   t        |      k  S r   r   r   s     r   __lt__zColorizer.__lt__\  r   r   c                     | |k   S r   r   r   s     r   __ge__zColorizer.__ge___      e|r   c                     | |kD   S r   r   r   s     r   __le__zColorizer.__le__b  r   r   c                 L    | j                   j                  | j                        S r   )r   r   r   r=   s    r   __len__zColorizer.__len__e  s    99!!$,,//r   c                     | j                   S r   )r   r=   s    r   __str__zColorizer.__str__h  s    <<r   c                     |j                  | j                  j                  | j                  | j                  |xs | j
                               y)a  Renders the string as self._color on the console.

    Args:
      stream: The stream to render the string to. The stream given here *must*
        have the same encoding as sys.stdout for this to work properly.
      justify: The justification function, self._justify if None.
    N)writer   r   r   r   r   )r>   streamr   s      r   RenderzColorizer.Renderk  s8     LL		4<<g6NOQr   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   :  s:    &%%0	Qr   r   c                     t         j                  }|s|sd}n| r| |j                         k7  rd}|rt        |       }|t         _        |S )a  Gets the console attribute state.

  If this is the first call or reset is True or encoding is not None and does
  not match the current encoding or out is not None and does not match the
  current out then the state is (re)initialized. Otherwise the current state
  is returned.

  This call associates the out file stream with the console. All console related
  output should go to the same stream.

  Args:
    encoding: Encoding override.
      ascii -- ASCII. This is the default.
      utf8 -- UTF-8 unicode.
      win -- Windows code page 437.
    reset: Force re-initialization if True.

  Returns:
    The global ConsoleAttr state object.
  Tr   )rV   r   r   )r   resetattrs      r   r   r   w  sL    * 
	(	($	e	h$"2"2"44e
)D&*K#	+r   c                     t        | d      S )a$  Resets the console attribute state to the console default.

  Args:
    encoding: Reset to this encoding instead of the default.
      ascii -- ASCII. This is the default.
      utf8 -- UTF-8 unicode.
      win -- Windows code page 437.

  Returns:
    The global ConsoleAttr state object.
  T)r   r   )r   r   s    r   ResetConsoleAttrr     s     
	66r   c                     t        | t              syt        j                  d|       } t        j                  |       dk7  ryt        j
                  |       dk(  ryt        j                  |       dv ryy)at  Returns the monospaced terminal display width of char.

  Assumptions:
    - monospaced display
    - ambiguous or unknown chars default to width 1
    - ASCII control char width is 1 => don't use this for control chars

  Args:
    char: The character to determine the display width of.

  Returns:
    The monospaced terminal display width of char: either 0, 1, or 2.
  r   NFCr   CfFWrC   )r   r   unicodedata	normalize	combiningcategoryeast_asian_width)chars    r   r   r     sl     
D#	 
		ud	+$4 A%D!T)##D)T1 r   c                     	 | y|xs t               j                         }t        j                  | |      }	 |j	                  |       |S # t
        $ r( |j	                  ||rdnd      j                  |      cY S w xY w)NNoner   backslashreplacer   )r   r   encoding_utilDecoder   UnicodeErrordecode)datar   escaper   s       r   SafeTextr    s    0 
\7)557(x8&

MM(M	  VHF0	JVH	s   A .A=<A=c                    | yt        | t              r| S t        |       }	 |j                  d      S # t        $ r Y nw xY w	 |j                  t               j                               S # t        $ r Y nw xY w|j                  d      S )a  Encode data to bytes.

  The primary use case is for base64/mime style 7-bit ascii encoding where the
  encoder input must be bytes. "safe" means that the conversion always returns
  bytes and will not raise codec exceptions.

  If data is text then an 8-bit ascii encoding is attempted, then the console
  encoding, and finally utf-8.

  Args:
    data: Any bytes, string, or object that has str() or unicode() methods.

  Returns:
    A bytes string representation of the data.
  r   z
iso-8859-1r   )r   bytesr   r   UnicodeEncodeErrorr   r   )r  ss     r   EncodeToBytesr    s      
\eK 
$i!	88L!!	 			88N$00233	 		 
'	s   3 	??&A* *	A65A6c                 h    |xs t               j                         }t        j                  | |      S )at  Converts the given string, bytes, or object to a text string.

  Args:
    data: Any bytes, string, or object that has str() or unicode() methods.
    encoding: A suggesting encoding used to decode. If this encoding doesn't
      work, other defaults are tried. Defaults to
      GetConsoleAttr().GetEncoding().

  Returns:
    A text string representation of the data.
  r   )r   r   r  r	  )r  r   s     r   r	  r	    s-     7)557(			dX	66r   r   r   )NT)r   
__future__r   r   r   rj   r   r   fire.consoler   r   r  r	   objectr   r   r.   r5   r8   r;   rO   rV   r   r   r   r   r  r  r	  r   r   r   <module>r     s   "FR '  ' 	 
  ) 2  0 4. 4	$: 	.V .$: "8 f?& f?R:Q :QzB7 F(V&R7r   