
    L                     v   d dl mZ d dlmZmZmZ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mZmZmZmZ d dlZd dlZdZd	 Zd
ZdZ G d de      Z G d de      Z G d d      Z  G d d      Z!d Z" e"e       Z# e"e!      Z$ e%e#       e%e      k(  sJ  e%e$       e%e      k(  sJ  G d de&      Z'y)    )unicode_literals)windllbyrefArgumentErrorc_charc_longc_ulongc_uintpointer)DWORD)Output)ANSI_COLOR_NAMES)CONSOLE_SCREEN_BUFFER_INFOSTD_OUTPUT_HANDLESTD_INPUT_HANDLECOORD
SMALL_RECTN)Win32Outputc                 R    t        | j                  dz  | j                  dz  z        S )aH  
    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 runing ``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)coords    7lib/third_party/prompt_toolkit/terminal/win32_output.py_coord_byvalr      s&     %''G#egg&6677    Fz!prompt-toolkit-windows-output.logc                   "     e Zd ZdZ fdZ xZS )NoConsoleScreenBufferErrorz
    Raised when the application is not running inside a Windows Console, but
    the user tries to instantiate Win32Output.
    c                     dt         j                  j                  dd      v }|rdt         j                  d   z  }nd}t        t        |   |       y )NxtermTERM zFound %s, 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superr   __init__)selfr   message	__class__s      r   r&   z#NoConsoleScreenBufferError.__init__0   sR    2::>>&"556 9;

68J	KG KG($8Ar   )__name__
__module____qualname____doc__r&   __classcell__)r)   s   @r   r   r   +   s    B Br   r   c                       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 Z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d Zd Zd Z d Z!d  Z"d! Z#e$d"        Z%y#)&r   zW
    I/O abstraction for rendering to Windows consoles.
    (cmd.exe and similar.)
    c                 ,   || _         g | _        || _        t        j                  j                  t              | _        d| _        t               | _
        | j                         }|r|j                  nd| _        t        rt        t         d      | _        y y )NF   ab)use_complete_width_bufferstdoutr   kernel32GetStdHandler   hconsole_in_alternate_screenColorLookupTablecolor_lookup_tableget_win32_screen_buffer_infowAttributesdefault_attrs_DEBUG_RENDER_OUTPUTopen_DEBUG_RENDER_OUTPUT_FILENAMELOG)r'   r5   r3   infos       r   r&   zWin32Output.__init__D   s{    "4445FG$)!"2"4 00215T--294@DH  r   c                 6    | j                   j                         S )z Return file descriptor. )r5   filenor'   s    r   rE   zWin32Output.filenoV   s    {{!!##r   c                 .    | j                   j                  S )z" Return encoding used for stdout. )r5   encodingrF   s    r   rH   zWin32Output.encodingZ   s    {{###r   c                 :    | j                   j                  |       y N)r4   appendr'   datas     r   writezWin32Output.write^   s    D!r   c                 &    | j                  |       y)z@ For win32, there is no difference between write and write_raw. N)rN   rL   s     r   	write_rawzWin32Output.write_rawa   s    

4r   c                    ddl m} | j                         }| j                  r|j                  j
                  }n-|j                  j                  |j                  j                  z
  }|j                  j                  |j                  j                  z
  dz   }|j                  j
                  dz
  }t        ||      } |||      S )Nr   )Size   )rowscolumns)prompt_toolkit.layout.screenrR   r<   r3   dwSizer   srWindowRightLeftBottomTopmin)r'   rR   rC   widthheightmaxwidths         r   get_sizezWin32Output.get_sizee   s    5002
 ""KKMMEMM''$--*<*<<E%%(9(99A= ;;==1$He$ //r   c                    | j                          t        r| j                  j                  d|j                  z  j                  d      dz          | j                  j                  ddj                  |D cg c]  }d|z  	 c}      j                  d      z   dz          | j                  j                  ddj                  |D cg c]  }dt        |      z   c}      j                  d      z   dz          | j                  j                          	  ||i |S c c}w c c}w # t        $ rS}t        rC| j                  j                  d|j                  d|d|dj                  d             Y d	}~y	Y d	}~y	d	}~ww xY w)
z2
        Flush and call win API function.
        %rutf-8   
s        z, z    Error in  
N)	flushr?   rB   rN   r*   encodejointyper   )r'   funcakwies         r   _winapizWin32Output._winapiz   s3    	

HHNND4==088AEIJHHNN8dii10E1a10E&F&M&Mg&VVY^^_HHNN8dii0KAQ0K&L&S&ST[&\\_ddeHHNN	d>b>! 1F0K
  	d#T]]Aq QYYZabcc $	ds%   6DD"D' '	F0AE>>Fc                     | j                          t               }t        j                  j	                  | j
                  t        |            }|r|S t        )z,
        Return Screen buffer info.
        )rh   r   r   r6   GetConsoleScreenBufferInfor8   r   r   )r'   sbinfosuccesss      r   r<   z(Win32Output.get_win32_screen_buffer_info   sD    , 	

+-//<<T]]ERXMZ
 M,,r   c                     t        |t        j                        sJ | j                  t        j
                  j                  |       y)z%
        Set terminal title.
        N)
isinstancesix	text_typerq   r   r6   SetConsoleTitleW)r'   titles     r   	set_titlezWin32Output.set_title   s0     %///V__55u=r   c                 X    | j                  t        j                  j                  d       y )Nr!   )rq   r   r6   rz   rF   s    r   clear_titlezWin32Output.clear_title   s    V__55r:r   c                     t        dd      }| j                         }|j                  j                  |j                  j                  z  }| j                  dd       | j                  ||       y )Nr   )rowcolumn)r   r<   rW   r   r   cursor_goto_erase)r'   startrt   lengths       r   erase_screenzWin32Output.erase_screen   sV    a2246==??2Qq)E6"r   c                    | j                         }|j                  }|j                  }|j                  |j                  z
  |j                  |j                  |j                  j                  z
  z  z   }| j                  ||       y rJ   )r<   rW   dwCursorPositionr   r   r   )r'   rt   sizer   r   s        r   
erase_downzWin32Output.erase_down   sf    224}}''66DFF?dff9P9P9R9R0R&SSE6"r   c                     | j                         }|j                  }|j                  j                  |j                  j                  z
  }| j	                  ||       y)z	
        N)r<   r   rW   r   r   )r'   rt   r   r   s       r   erase_end_of_linezWin32Output.erase_end_of_line   sI     224''6#:#:#<#<<E6"r   c           
         t               }| j                  t        j                  j                  | j
                  t        d      t        |      t        |      t        |             | j                         }| j                  t        j                  j                  | j
                  |j                  |t        |      t        |             y )N    )r	   rq   r   r6   FillConsoleOutputCharacterAr8   r   r   r   r   r<   FillConsoleOutputAttributer=   )r'   r   r   chars_writtenrt   s        r   r   zWin32Output._erase   s    	V__@@]]F4L%-eAT=)	+
 224V__??]]F$6$6U@S=)	+r   c                     | j                  t        j                  j                  | j                  | j
                         y)z0 Reset the console foreground/background color. N)rq   r   r6   SetConsoleTextAttributer8   r>   rF   s    r   reset_attributeszWin32Output.reset_attributes   s)    V__<<dmm''	)r   c                 `   |\  }}}}}}}| j                   }|#|dz  }|| j                  j                  |      z  }|#|dz  }|| j                  j                  |      z  }|r|dz  |dz  dz  z  |dz  dz	  z  }| j	                  t
        j                  j                  | j                  |       y )Niii r1         )	r>   r;   lookup_fg_colorlookup_bg_colorrq   r   r6   r   r8   )	r'   attrsfgcolorbgcolorbold	underlineitalicblinkreverses	            r   set_attributeszWin32Output.set_attributes   s    DIA$	65' "" DLET,,<<WEEE EMET,,<<WEEE U]'9:ut|PQ>QREV__<<dmmUSr   c                      y rJ    rF   s    r   disable_autowrapzWin32Output.disable_autowrap       r   c                      y rJ   r   rF   s    r   enable_autowrapzWin32Output.enable_autowrap   r   r   c                     t        ||      }| j                  t        j                  j                  | j
                  t        |             y )N)xy)r   rq   r   r6   SetConsoleCursorPositionr8   r   )r'   r   r   poss       r   r   zWin32Output.cursor_goto  s2    f$V__==t}}l[^N_`r   c                     | j                         j                  }t        |j                  |j                  |z
        }| j                  t        j                  j                  | j                  t        |             y rJ   )r<   r   r   r   r   rq   r   r6   r   r8   r   r'   amountsrr   s       r   	cursor_upzWin32Output.cursor_up  sR    ..0AABDD"$$-(V__==t}}l[^N_`r   c                 (    | j                  |        y rJ   )r   r'   r   s     r   cursor_downzWin32Output.cursor_down  s    wr   c                    | j                         j                  }t        t        d|j                  |z         |j
                        }| j                  t        j                  j                  | j                  t        |             y )Nr   )r<   r   r   maxr   r   rq   r   r6   r   r8   r   r   s       r   cursor_forwardzWin32Output.cursor_forward  s[    ..0AA C244&=)2440V__==t}}l[^N_`r   c                 (    | j                  |        y rJ   )r   r   s     r   cursor_backwardzWin32Output.cursor_backward  s    VG$r   c           	         | j                   s| j                  j                          ydj                  | j                         }t        rJ| j
                  j                  d|z  j                  d      dz          | j
                  j                          |D ]I  }t               }t        j                  j                  | j                  |dt        |      d      }|dk7  rIJ  g | _         y)z3
        Write to output stream and flush.
        Nr!   rc   rd   re   rS   r   )r4   r5   rh   rj   r?   rB   rN   ri   r   r   r6   WriteConsoleWr8   r   )r'   rM   bwrittenretvals        r   rh   zWin32Output.flush  s     || KKwwt||$HHNND4K//85@AHHNN
 AgG__224==!QgX\]FQ;;	  r   c                     | j                         }|j                  j                  |j                  j                  z
  dz   S )NrS   )r<   rX   r[   r   r   )r'   rC   s     r   get_rows_below_cursor_positionz*Win32Output.get_rows_below_cursor_position4  s6    002}}##d&;&;&=&==AAr   c                 4   | j                         }|j                  }|j                  }t               }d|_        |j
                  |j                  z
  |_        |j                  |j                  z
  }d|j                  |j                  z
  cxk  r|dz
  k  rn n|j                  |_        nt        ||j                        |_        |j                  |z
  |_        | j                  t        j                  j                  | j                  dt        |             y)z
        To be called before drawing the prompt. This should scroll the console
        to left, with the cursor at the bottom (if possible).
        r   rS   TN)r<   rX   r   r   rZ   rY   r[   r\   r   r   rq   r   r6   SetConsoleWindowInfor8   r   )r'   rC   r   
cursor_posresult
win_heights         r   scroll_buffer_to_promptz#Win32Output.scroll_buffer_to_prompt8  s     002]]**
 xx"'') YY'
ryy:<<'8*q.8IIFM
JLL9FM]]Z/
 	V__994==$PUV\P]^r   c           	         | j                   sd}d}| j                  t        j                  j                  ||z  t        d      dt        d      d      }| j                  t        j                  j                  |       || _        d| _         yy)z0
        Go to alternate screen buffer.
        l        i   @r   NrS   T)r9   rq   r   r6   CreateConsoleScreenBufferr   SetConsoleActiveScreenBufferr8   )r'   GENERIC_READGENERIC_WRITEhandles       r   enter_alternate_screenz"Win32Output.enter_alternate_screenT  s{     ((%L&M \\&//"K"K\ZgMg"'(D%(DBF LLEEvN"DM(,D% )r   c                 R   | j                   r| j                  t        j                  j                  t
              }| j                  t        j                  j                  |       | j                  t        j                  j                  | j                         || _        d| _         yy)z6
        Make stdout again the active buffer.
        FN)	r9   rq   r   r6   r7   r   r   CloseHandler8   )r'   r5   s     r   quit_alternate_screenz!Win32Output.quit_alternate_screend  sp     $$\\&//">">@QRFLLEEvNLL44dmmD"DM(-D% %r   c                 :   d}t         j                  j                  t              }t	               }| j                  t         j                  j                  |t        |             | j                  t         j                  j                  ||j                  |z         y N   
r   r6   r7   r   r   rq   GetConsoleModer   SetConsoleModevaluer'   ENABLE_MOUSE_INPUTr   original_modes       r   enable_mouse_supportz Win32Output.enable_mouse_supporto  si    !--.>?V__33VW]=STV__33V]=P=PSe=efr   c                 <   d}t         j                  j                  t              }t	               }| j                  t         j                  j                  |t        |             | j                  t         j                  j                  ||j                  | z         y r   r   r   s       r   disable_mouse_supportz!Win32Output.disable_mouse_supportw  sl    !--.>?V__33VW]=STV__33V]=P=PUgSg=ghr   c                      y rJ   r   rF   s    r   hide_cursorzWin32Output.hide_cursor      r   c                      y rJ   r   rF   s    r   show_cursorzWin32Output.show_cursor  r   r   c                     t         j                  j                         }d}t         j                  j	                  |ddt        |             y)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.
        rS   N)r   r6   GetConsoleWindowuser32RedrawWindowr
   )clsr   RDW_INVALIDATEs      r   win32_refresh_windowz Win32Output.win32_refresh_window  s8     113""64vn7MNr   N)F)r   r   )&r*   r+   r,   r-   r&   rE   rH   rN   rP   ra   rq   r<   r|   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   rh   r   r   r   r   r   r   r   r   classmethodr   r   r   r   r   r   ?   s    A$$$"0*d$ -D>;###+)
T,aa
 a%8B_8- 	.gi O O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
)FOREGROUND_COLORr   rS         r               Nr*   r+   r,   BLACKBLUEGREENCYANREDMAGENTAYELLOWGRAY	INTENSITYr   r   r   r   r     /    EDEDCGFDIr   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
)BACKROUND_COLORr   r       0   @   P   `   p      Nr   r   r   r   r   r     r   r   r   c                    i d| j                   d| j                   d| j                   | j                  z  d| j                  d| j                  | j                  z  d| j                  d| j                  d| j
                  d	| j                  d
| j                  d| j                  d| j                  | j                  z  d| j                  | j                  z  d| j
                  | j                  z  d| j                  | j                  z  d| j                  | j                  z  d| j                  | j                  z  S )zJ Create a table that maps the 16 named ansi colors to their Windows code. ansidefault	ansiblackansidarkgrayansilightgray	ansiwhiteansidarkredansidarkgreen	ansibrownansidarkblue
ansipurpleansitealansired	ansigreen
ansiyellowansiblueansifuchsiaansiturquoise)	r   r   r   r   r   r   r   r   r   )	color_clss    r   _create_ansi_color_dictr    sx    	9+>+>> 		
 	)*=*== 	9== 	9?? 	9++ 	9>> 	9,, 	9>>  	)--)*=*==!" 	)//I,?,??#$ 	)**Y-@-@@%& 	)..9+>+>>'( 	)++i.A.AA)* 	)..9+>+>>+ r   c                   >    e Zd ZdZd Zed        Zd Zd Zd Z	d Z
y)	r:   z8
    Inspired by pygments/formatters/terminal256.py
    c                 <    | j                         | _        i | _        y rJ   )_build_color_table_win32_colors
best_matchrF   s    r   r&   zColorLookupTable.__init__  s    !446r   c                     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                  z  |j                  |j                  z  fddd| j                  | j                  z  |j                  |j                  z  fddd| j
                  | j                  z  |j
                  |j                  z  fddd| j                  | j                  z  |j                  |j                  z  fddd| j                  | j                  z  |j                  |j                  z  fddd| j                  | j                  z  |j                  |j                  z  fddd| j                  | j                  z  |j                  |j                  z  fddd| j                  | j                  z  |j                  |j                  z  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BGs     r   r  z#ColorLookupTable._build_color_table  s
   
  4rxx24rww04rxx24rww04rvvrvv.4rzz2::64ryy"))44rww04rww5rww7MN4rxx",,62<<8OP4rww5rww7MN4rvv4bffr||6KL4rzzBLL8"**r||:ST4ryy2<<7R\\9QR4rxx",,62<<8OP4rww5rww7MN%
 	
r   c                     d}d}d}| j                   D ]4  \  }}}	}
}||z
  }||z
  }||	z
  }||z  ||z  z   ||z  z   }||k  s/|
}|}|}6 ||fS )Ni r   )r  )r'   rgr   distancefg_matchbg_matchr_g_b_fg_bg_rdgdbdds                   r   _closest_colorzColorLookupTable._closest_color  s     $($6$6 BBSRBRBRBR"r'!BG+A8| %7 !!r   c                     | j                   j                  |d       }|M	 t        t        |      d      }|dz	  dz  }|dz	  dz  }|dz  }| j                  |||      }|| j                   |<   |S # t        $ r d}Y Fw xY w)Nr   r   r%  r   )r   r$   intstr
ValueErrorr7  )r'   colorindexesrgbr)  r*  r   s          r   _color_indexeszColorLookupTable._color_indexes  s    //%%eT2?#e*b) d"AT!Ad
A))!Q2G%,DOOE"  s   A. .A<;A<c                 L    |t         v r	t         |   S | j                  |      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_COLORSr?  )r'   fg_colors     r   r   z ColorLookupTable.lookup_fg_color  -     ~%!(++&&x033r   c                 L    |t         v r	t         |   S | j                  |      d   S )z
        Return the color for use in the
        `windll.kernel32.SetConsoleTextAttribute` API call.

        :param bg_color: Background as text. E.g. 'ffffff' or 'red'
        rS   )BG_ANSI_COLORSr?  )r'   bg_colors     r   r   z ColorLookupTable.lookup_bg_color!  rC  r   N)r*   r+   r,   r-   r&   staticmethodr  r7  r?  r   r   r   r   r   r:   r:     s4     
 
8"$44r   r:   )(
__future__r   ctypesr   r   r   r   r   r	   r
   r   ctypes.wintypesr   prompt_toolkit.rendererr   prompt_toolkit.stylesr   prompt_toolkit.win32_typesr   r   r   r   r   r"   rx   __all__r   r?   rA   	Exceptionr   r   r   r   r  rA  rE  setobjectr:   r   r   r   <module>rR     s    ' Y Y Y ! * 2 y y 	 

8*   D B B(SO& SOl
	 		 	4 ))9:(9
>c"233 33
>c"233 33^4v ^4r   