o
    Df^X                     @  s  d dl mZ d dlZejdksJ d dlZd dlmZmZ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 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mZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( e$s{d dlm)Z) dgZ*d*ddZ+dZ,dZ-G dd de.Z/edZ0G dd de&Z1G dd  d Z2G d!d" d"Z3d+d&d'Z4e4e2Z5e4e3Z6e7e5e7eksJ e7e6e7eksJ G d(d) d)Z8dS ),    )annotationsNwin32)ArgumentErrorbyrefc_charc_longc_uintc_ulongpointer)DWORDHANDLE)CallableTextIOTypeVar)CursorShape)Size)ANSI_COLOR_NAMESAttrs)
get_cwidth)CONSOLE_SCREEN_BUFFER_INFOCOORD
SMALL_RECTSTD_INPUT_HANDLESTD_OUTPUT_HANDLE   )SPHINX_AUTODOC_RUNNING   )Output)
ColorDepth)windllWin32Outputcoordr   returnr   c                 C  s   t | jd | jd@ B S )aI  
    Turns a COORD object into a c_long.
    This will cause it to be passed by value instead of by reference. (That is what I think at least.)

    When running ``ptipython`` is run (only with IPython), we often got the following error::

         Error in 'SetConsoleCursorPosition'.
         ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
     argument 2: <class 'TypeError'>: wrong type

    It was solved by turning ``COORD`` parameters into a ``c_long`` like this.

    More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
    i   i  )r   YX)r!    r%   T/home/ubuntu/webapp/venv/lib/python3.10/site-packages/prompt_toolkit/output/win32.py_coord_byval'   s   r'   Fz!prompt-toolkit-windows-output.logc                      s"   e Zd ZdZd fddZ  ZS )NoConsoleScreenBufferErrorz
    Raised when the application is not running inside a Windows Console, but
    the user tries to instantiate Win32Output.
    r"   Nonec                   s<   dt jddv }|rdt jd }nd}t | d S )NxtermTERM zFound {}, while expecting a Windows console. Maybe try to run this program using "winpty" or run it in cmd.exe instead. Or otherwise, in case of Cygwin, use the Python executable that is compiled for Cygwin.z2No Windows console found. Are you running cmd.exe?)osenvirongetformatsuper__init__)selfr*   message	__class__r%   r&   r2   F   s   z#NoConsoleScreenBufferError.__init__r"   r)   )__name__
__module____qualname____doc__r2   __classcell__r%   r%   r5   r&   r(   @   s    r(   _Tc                   @  s  e Zd ZdZ		dmdnddZdoddZdpddZdqddZdqddZdrddZ	dsd"d#Z
dtd%d&Zdud(d)Zdvd*d+Zdvd,d-Zdvd.d/Zdvd0d1Zdwd5d6Zdvd7d8Zdxd=d>Zdvd?d@ZdvdAdBZdydzdFdGZd{dIdJZd{dKdLZd{dMdNZd{dOdPZdvdQdRZdodSdTZdvdUdVZdvdWdXZdvdYdZZdvd[d\Z dvd]d^Z!dvd_d`Z"dvdadbZ#d|dedfZ$dvdgdhZ%e&dvdidjZ'd}dkdlZ(dS )~r    zW
    I/O abstraction for rendering to Windows consoles.
    (cmd.exe and similar.)
    FNstdoutr   use_complete_widthbooldefault_color_depthColorDepth | Noner"   r)   c                 C  sn   || _ || _g | _|| _ttjt| _	d| _
d| _t | _|  }|r(|jnd| _tr5ttd| _d S d S )NF   ab)r?   rA   _bufferr>   r   r   kernel32GetStdHandler   hconsole_in_alternate_screen_hiddenColorLookupTablecolor_lookup_tableget_win32_screen_buffer_infowAttributesdefault_attrs_DEBUG_RENDER_OUTPUTopen_DEBUG_RENDER_OUTPUT_FILENAMELOG)r3   r>   r?   rA   infor%   r%   r&   r2   `   s   zWin32Output.__init__intc                 C  s
   | j  S )zReturn file descriptor.)r>   filenor3   r%   r%   r&   rV   y   s   
zWin32Output.filenostrc                 C  s   | j jS )z Return encoding used for stdout.)r>   encodingrW   r%   r%   r&   rY   }   s   zWin32Output.encodingdatac                 C  s"   | j r	dt| }| j| d S )N )rJ   r   rE   appendr3   rZ   r%   r%   r&   write   s   zWin32Output.writec                 C  s   |  | dS )z>For win32, there is no difference between write and write_raw.N)r^   r]   r%   r%   r&   	write_raw   s   zWin32Output.write_rawr   c                 C  s^   |   }| jr|jj}n|jj|jj }|jj|jj d }|jjd }t	||}t
||dS )Nr   )rowscolumns)rM   r?   dwSizer$   srWindowRightLeftBottomTopminr   )r3   rT   widthheightmaxwidthr%   r%   r&   get_size   s   

zWin32Output.get_sizefuncCallable[..., _T]aobjectkwr=   c                 O  s   |    trA| j|j d  | jdddd |D d d  | jdddd |D d d  | j   z||i |W S  tyk } ztrf| jd|jd	|d	| d
   d}~ww )z2
        Flush and call win API function.
           
s        z, c                 S  s   g | ]}|qS r%   r%   .0ir%   r%   r&   
<listcomp>   s    z'Win32Output._winapi.<locals>.<listcomp>zutf-8c                 S  s   g | ]}t |qS r%   )typers   r%   r%   r&   rv      s    z    Error in r[   
N)flushrP   rS   r^   r8   encodejoinr   )r3   rm   ro   rq   er%   r%   r&   _winapi   s,    
&zWin32Output._winapir   c                 C  s.   |    t }tj| jt|}|r|S t)z,
        Return Screen buffer info.
        )ry   r   r   rF   GetConsoleScreenBufferInforH   r   r(   )r3   sbinfosuccessr%   r%   r&   rM      s   
z(Win32Output.get_win32_screen_buffer_infotitlec                 C  s   |  tjj| dS )z%
        Set terminal title.
        Nr}   r   rF   SetConsoleTitleW)r3   r   r%   r%   r&   	set_title   s   zWin32Output.set_titlec                 C  s   |  tjjd d S )Nr,   r   rW   r%   r%   r&   clear_title   s   zWin32Output.clear_titlec                 C  s@   t dd}|  }|jj|jj }| jddd | || d S )Nr   )rowcolumn)r   rM   rb   r$   r#   cursor_goto_erase)r3   startr   lengthr%   r%   r&   erase_screen   s
   
zWin32Output.erase_screenc                 C  sD   |   }|j}|j}|j|j |j|j|jj   }| || d S N)rM   rb   dwCursorPositionr$   r#   r   )r3   r   sizer   r   r%   r%   r&   
erase_down   s
    zWin32Output.erase_downc                 C  s.   |   }|j}|jj|jj }| || dS )r,   N)rM   r   rb   r$   r   )r3   r   r   r   r%   r%   r&   erase_end_of_line   s   zWin32Output.erase_end_of_liner   r   r   c              	   C  s`   t  }| tjj| jtdt|t|t	| | 
 }| tjj| j|j|t|t	| d S )N    )r	   r}   r   rF   FillConsoleOutputCharacterArH   r   r   r'   r   rM   FillConsoleOutputAttributerN   )r3   r   r   chars_writtenr   r%   r%   r&   r      s$   
zWin32Output._erasec                 C  s    |  tjj| j| j d| _dS )z.Reset the console foreground/background color.FN)r}   r   rF   SetConsoleTextAttributerH   rO   rJ   rW   r%   r%   r&   reset_attributes  s   
zWin32Output.reset_attributesattrsr   color_depthr   c              	   C  s   |\	}}}}}}}	}
}t || _| j}|tjkr4|r&|d@ }|| j|O }|r4|d@ }|| j|O }|
rF|d@ |d@ d> B |d@ d? B }| t	j
j| j| d S )Niii rC         )r@   rJ   rO   r   DEPTH_1_BITrL   lookup_fg_colorlookup_bg_colorr}   r   rF   r   rH   )r3   r   r   fgcolorbgcolorbold	underlinestrikeitalicblinkreversehidden	win_attrsr%   r%   r&   set_attributes  s8   



zWin32Output.set_attributesc                 C     d S r   r%   rW   r%   r%   r&   disable_autowrapC     zWin32Output.disable_autowrapc                 C  r   r   r%   rW   r%   r%   r&   enable_autowrapG  r   zWin32Output.enable_autowrapr   r   r   c                 C  s(   t ||d}| tjj| jt| d S Nr$   r#   )r   r}   r   rF   SetConsoleCursorPositionrH   r'   )r3   r   r   posr%   r%   r&   r   K  s   zWin32Output.cursor_gotoamountc                 C  s:   |   j}t|j|j| d}| tjj| j	t
| d S r   )rM   r   r   r$   r#   r}   r   rF   r   rH   r'   r3   r   srr   r%   r%   r&   	cursor_upQ  s
   
zWin32Output.cursor_upc                 C     |  |  d S r   )r   r3   r   r%   r%   r&   cursor_downX     zWin32Output.cursor_downc                 C  s@   |   j}ttd|j| |jd}| tjj	| j
t| d S )Nr   r   )rM   r   r   maxr$   r#   r}   r   rF   r   rH   r'   r   r%   r%   r&   cursor_forward[  s
   
zWin32Output.cursor_forwardc                 C  r   r   )r   r   r%   r%   r&   cursor_backwardd  r   zWin32Output.cursor_backwardc                 C  s   | j s
| j  dS d| j }tr"| j| d  | j  |D ]}t }t	j
| j|dt|d}|dks<J q$g | _ dS )z3
        Write to output stream and flush.
        Nr,   rr   r   r   )rE   r>   ry   r{   rP   rS   r^   rz   r   r   rF   WriteConsoleWrH   r   )r3   rZ   bwrittenretvalr%   r%   r&   ry   g  s   


zWin32Output.flushc                 C  s   |   }|jj|jj d S )Nr   )rM   rc   rf   r   r#   )r3   rT   r%   r%   r&   get_rows_below_cursor_position  s   z*Win32Output.get_rows_below_cursor_positionc                 C  s   |   }|j}|j}t }d|_|j|j |_|j|j }d|j|j   k r-|d k r4n n|j|_nt	||j|_|j| |_| 
tjj| jdt| dS )z
        To be called before drawing the prompt. This should scroll the console
        to left, with the cursor at the bottom (if possible).
        r   r   TN)rM   rc   r   r   re   rd   rf   rg   r#   r   r}   r   rF   SetConsoleWindowInforH   r   )r3   rT   r   
cursor_posresult
win_heightr%   r%   r&   scroll_buffer_to_prompt  s   $
z#Win32Output.scroll_buffer_to_promptc              	   C  sZ   | j s+d}d}t| tjj||B tddtdd}| tjj| || _d| _ dS dS )z0
        Go to alternate screen buffer.
        l        i   @r   Nr   T)	rI   r   r}   r   rF   CreateConsoleScreenBufferr   SetConsoleActiveScreenBufferrH   )r3   GENERIC_READGENERIC_WRITEhandler%   r%   r&   enter_alternate_screen  s"   
z"Win32Output.enter_alternate_screenc                 C  sP   | j r&t| tjjt}| tjj| | tjj| j	 || _	d| _ dS dS )z6
        Make stdout again the active buffer.
        FN)
rI   r   r}   r   rF   rG   r   r   CloseHandlerH   )r3   r>   r%   r%   r&   quit_alternate_screen  s   
z!Win32Output.quit_alternate_screenc                 C  sV   d}d}t tjt}t }| tjj|t| | tjj	||j
|B | @  d S )N   @   r   r   rF   rG   r   r   r}   GetConsoleModer
   SetConsoleModevalue)r3   ENABLE_MOUSE_INPUTENABLE_QUICK_EDIT_MODEr   original_moder%   r%   r&   enable_mouse_support  s   z Win32Output.enable_mouse_supportc                 C  sN   d}t tjt}t }| tjj|t| | tjj	||j
| @  d S )Nr   r   )r3   r   r   r   r%   r%   r&   disable_mouse_support  s   
z!Win32Output.disable_mouse_supportc                 C  r   r   r%   rW   r%   r%   r&   hide_cursor     zWin32Output.hide_cursorc                 C  r   r   r%   rW   r%   r%   r&   show_cursor  r   zWin32Output.show_cursorcursor_shaper   c                 C  r   r   r%   )r3   r   r%   r%   r&   set_cursor_shape  r   zWin32Output.set_cursor_shapec                 C  r   r   r%   rW   r%   r%   r&   reset_cursor_shape  r   zWin32Output.reset_cursor_shapec                 C  s,   t tj }d}tj|ddt| dS )a$  
        Call win32 API to refresh the whole Window.

        This is sometimes necessary when the application paints background
        for completion menus. When the menu disappears, it leaves traces due
        to a bug in the Windows Console. Sending a repaint request solves it.
        r   N)r   r   rF   GetConsoleWindowuser32RedrawWindowr   )clsr   RDW_INVALIDATEr%   r%   r&   win32_refresh_window  s   
z Win32Output.win32_refresh_windowc                 C  s   | j dur| j S tjS )z
        Return the default color depth for a windows terminal.

        Contrary to the Vt100 implementation, this doesn't depend on a $TERM
        variable.
        N)rA   r   DEPTH_4_BITrW   r%   r%   r&   get_default_color_depth  s   
z#Win32Output.get_default_color_depth)FN)r>   r   r?   r@   rA   rB   r"   r)   )r"   rU   )r"   rX   )rZ   rX   r"   r)   )r"   r   )rm   rn   ro   rp   rq   rp   r"   r=   )r"   r   )r   rX   r"   r)   r7   )r   r   r   rU   r"   r)   )r   r   r   r   r"   r)   )r   r   )r   rU   r   rU   r"   r)   )r   rU   r"   r)   )r   r   r"   r)   )r"   r   ))r8   r9   r:   r;   r2   rV   rY   r^   r_   rl   r}   rM   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ry   r   r   r   r   r   r   r   r   r   r   classmethodr   r   r%   r%   r%   r&   r    Z   sR    







$



	



&




	










c                   @  0   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
S )FOREGROUND_COLORr   r   r      r               Nr8   r9   r:   BLACKBLUEGREENCYANREDMAGENTAYELLOWGRAY	INTENSITYr%   r%   r%   r&   r         r   c                   @  r   )BACKGROUND_COLORr   r       0   r   P   `   p      Nr   r%   r%   r%   r&   r     r   r   	color_cls/type[FOREGROUND_COLOR] | type[BACKGROUND_COLOR]dict[str, int]c                 C  s   i d| j d| j d| jd| j | jB d| j| jB d| jd| jd| jd	| jd
| jd| jd| j| jB d| j| jB d| j| jB d| j| jB d| j| jB d| j| jB S )zHCreate a table that maps the 16 named ansi colors to their Windows code.ansidefault	ansiblackansigrayansibrightblack	ansiwhiteansired	ansigreen
ansiyellowansiblueansimagentaansicyanansibrightredansibrightgreenansibrightyellowansibrightblueansibrightmagentaansibrightcyan)	r   r   r   r   r   r   r   r   r   )r  r%   r%   r&   _create_ansi_color_dict*  sF   	
r  c                   @  sP   e Zd ZdZdddZedddZdddZdddZdddZ	d ddZ
dS )!rK   z8
    Inspired by pygments/formatters/terminal256.py
    r"   r)   c                 C  s   |   | _i | _d S r   )_build_color_table_win32_colors
best_matchrW   r%   r%   r&   r2   Q  s   

zColorLookupTable.__init__$list[tuple[int, int, int, int, int]]c                  C  sl  t } t}ddd| j|jfddd| j|jfddd| j|jfddd| j|jfddd| j|jfddd| j|jfddd| j|jfddd| j	|j	fddd| j| j
B |j|j
B fddd| j| j
B |j|j
B fddd| j| j
B |j|j
B fddd| j| j
B |j|j
B fddd| j| j
B |j|j
B fddd| j| j
B |j|j
B fddd| j| j
B |j|j
B fddd| j	| j
B |j	|j
B fgS )z<
        Build an RGB-to-256 color conversion table
        r         D      )r   r   r   r   r   r   r   r   r   r   r   )FGBGr%   r%   r&   r  W  s&   z#ColorLookupTable._build_color_tablerrU   gr   tuple[int, int]c                 C  sn   d}d}d}| j D ])\}}}	}
}|| }|| }||	 }|| ||  ||  }||k r2|
}|}|}q	||fS )Ni r   )r  )r3   r!  r"  r   distancefg_matchbg_matchr_g_b_fg_bg_rdgdbddr%   r%   r&   _closest_colorr  s   zColorLookupTable._closest_colorcolorrX   c                 C  s|   | j |d }|d u r<z	tt|d}W n ty   d}Y nw |d? d@ }|d? d@ }|d@ }| |||}|| j |< |S )Nr   r   r  r   )r  r/   rU   rX   
ValueErrorr0  )r3   r1  indexesrgbr!  r"  r   r%   r%   r&   _color_indexes  s   
zColorLookupTable._color_indexesfg_colorc                 C     |t v rt | S | |d S )z
        Return the color for use in the
        `windll.kernel32.SetConsoleTextAttribute` API call.

        :param fg_color: Foreground as text. E.g. 'ffffff' or 'red'
        r   )FG_ANSI_COLORSr5  )r3   r6  r%   r%   r&   r        z ColorLookupTable.lookup_fg_colorbg_colorc                 C  r7  )z
        Return the color for use in the
        `windll.kernel32.SetConsoleTextAttribute` API call.

        :param bg_color: Background as text. E.g. 'ffffff' or 'red'
        r   )BG_ANSI_COLORSr5  )r3   r:  r%   r%   r&   r     r9  z ColorLookupTable.lookup_bg_colorNr7   )r"   r  )r!  rU   r"  rU   r   rU   r"   r#  )r1  rX   r"   r#  )r6  rX   r"   rU   )r:  rX   r"   rU   )r8   r9   r:   r;   r2   staticmethodr  r0  r5  r   r   r%   r%   r%   r&   rK   L  s    



rK   )r!   r   r"   r   )r  r  r"   r  )9
__future__r   sysplatformr-   ctypesr   r   r   r   r   r	   r
   ctypes.wintypesr   r   typingr   r   r   prompt_toolkit.cursor_shapesr   prompt_toolkit.data_structuresr   prompt_toolkit.stylesr   r   prompt_toolkit.utilsr   prompt_toolkit.win32_typesr   r   r   r   r   utilsr   baser   r   r   r   __all__r'   rP   rR   	Exceptionr(   r=   r    r   r   r  r8  r;  setrK   r%   r%   r%   r&   <module>   sH    $
   ;
