a
    lc                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dl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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mZmZmZmZm Z m!Z!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/m0Z0 d d
l1m2Z2m3Z3 d dl4m5Z5 d dl6m7Z7 d dl8m9Z9m:Z: d dl;m<Z<m=Z= d dl>m?Z?m@Z@mAZAmBZB d dlCmDZD d dlEmFZF d dlGmHZHmIZI d dlJmKZK d dlLmMZM d dlNmOZO d dlPmQZQmRZRmSZSmTZTmUZUmVZVmWZW d dlXmYZYmZZZ d dl[m\Z\ d dl]m^Z^ d dl_m`Z`maZa d dlbmcZcmdZd d dlemfZf d dlgmhZhmiZi d dljmkZkmlZl d dlmmnZnmoZo d d lpmqZq d d!lrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZz d d"l{m|Z|m}Z} d#d$l~mZmZ d#d%lmZmZ zd dlZW n& ey   d dlm  mZ Y n0 d&gZeYZe&d'Zed(gdf Zeed)dZeed*dZG d+d& d&ee ZG d,d- d-eUZeDdd.d/d0Zeeg df ed1 d2d3d4ZdS )5    N)AbstractEventLoopCancelledErrorFutureTaskensure_futurenew_event_loopset_event_loopsleep)	ExitStackcontextmanager)Popen)	format_tb)Any	AwaitableCallable	CoroutineDict	FrozenSet	GeneratorGenericHashableIterableIteratorListOptionalTupleTypeTypeVarUnioncastoverload)Buffer)SimpleCache)	ClipboardInMemoryClipboard)AnyCursorShapeConfigto_cursor_shape_config)Size)EditingMode)get_traceback_from_contextrun_in_executor_with_context)call_soon_threadsafeget_event_loop)	ConditionFilterFilterOrBool	to_filter)AnyFormattedText)Input)get_typeaheadstore_typeahead)load_page_navigation_bindings)load_key_bindings)
EmacsState)BindingConditionalKeyBindingsGlobalOnlyKeyBindingsKeyBindingsKeyBindingsBase	KeysTuplemerge_key_bindings)KeyPressEventKeyProcessor)ViState)Keys)	ContainerWindow)BufferControl	UIControl)create_dummy_layout)Layoutwalk)
ColorDepthOutput)Rendererprint_formatted_text)SearchState)	BaseStyle
DummyStyleDummyStyleTransformationDynamicStyleStyleTransformationdefault_pygments_styledefault_ui_stylemerge_styles)Eventin_main_thread   )get_app_sessionset_app)in_terminalrun_in_terminalApplication
_AppResultzApplication[_AppResult]SIGWINCHSIGTSTPc                   @   s  e Zd ZdZdddddddddddejdddddddddddddfee ee e	ee
 ee ee eeeeg eedf f df e	ee	 e	eee	eeedf eeedf ee ee eed ed ed ed ee ee ddd	d
ZeedddZeedddZeedddZeedddZddddZddddZ eedddZ!d_eddddZ"ddddZ#ddd d!Z$e%dd"d#d$Z&ddd%d&Z'd`eeg df  dd'd(d)Z(daeeg df  eeee)d*d+d,Z*dbeeg df  eeee)d-d.d/Z+e,e-e.e/f dd0d1d2Z0e1e2d3 dd4d5Z3e%e%dd6d7d8Z4e5e/e/df d9d:d;d<Z6ddd=d>Z7ddd?d@Z8dddAdBZ9e:dddCdDZ;e:dEdFe)e.ddGdHdDZ;e:dEdFee<e=e< f e.ddIdJdDZ;dcee) eee<e=e< f  e.ddKdLdDZ;dddMdNZ>dde.ee?e.ddPdQdRZ@deeddSdTdUZAdfe?ee ddVdWdXZBeeddYdZZCeedd[d\ZDeEe. dd]d^ZFdS )gr^   a'  
    The main Application class!
    This glues everything together.

    :param layout: A :class:`~prompt_toolkit.layout.Layout` instance.
    :param key_bindings:
        :class:`~prompt_toolkit.key_binding.KeyBindingsBase` instance for
        the key bindings.
    :param clipboard: :class:`~prompt_toolkit.clipboard.Clipboard` to use.
    :param full_screen: When True, run the application on the alternate screen buffer.
    :param color_depth: Any :class:`~.ColorDepth` value, a callable that
        returns a :class:`~.ColorDepth` or `None` for default.
    :param erase_when_done: (bool) Clear the application output when it finishes.
    :param reverse_vi_search_direction: Normally, in Vi mode, a '/' searches
        forward and a '?' searches backward. In Readline mode, this is usually
        reversed.
    :param min_redraw_interval: Number of seconds to wait between redraws. Use
        this for applications where `invalidate` is called a lot. This could cause
        a lot of terminal output, which some terminals are not able to process.

        `None` means that every `invalidate` will be scheduled right away
        (which is usually fine).

        When one `invalidate` is called, but a scheduled redraw of a previous
        `invalidate` call has not been executed yet, nothing will happen in any
        case.

    :param max_render_postpone_time: When there is high CPU (a lot of other
        scheduled calls), postpone the rendering max x seconds.  '0' means:
        don't postpone. '.5' means: try to draw at least twice a second.

    :param refresh_interval: Automatically invalidate the UI every so many
        seconds. When `None` (the default), only invalidate when `invalidate`
        has been called.

    :param terminal_size_polling_interval: Poll the terminal size every so many
        seconds. Useful if the applications runs in a thread other then then
        main thread where SIGWINCH can't be handled, or on Windows.

    Filters:

    :param mouse_support: (:class:`~prompt_toolkit.filters.Filter` or
        boolean). When True, enable mouse support.
    :param paste_mode: :class:`~prompt_toolkit.filters.Filter` or boolean.
    :param editing_mode: :class:`~prompt_toolkit.enums.EditingMode`.

    :param enable_page_navigation_bindings: When `True`, enable the page
        navigation key bindings. These include both Emacs and Vi bindings like
        page-up, page-down and so on to scroll through pages. Mostly useful for
        creating an editor or other full screen applications. Probably, you
        don't want this for the implementation of a REPL. By default, this is
        enabled if `full_screen` is set.

    Callbacks (all of these should accept an
    :class:`~prompt_toolkit.application.Application` object as input.)

    :param on_reset: Called during reset.
    :param on_invalidate: Called when the UI has been invalidated.
    :param before_render: Called right before rendering.
    :param after_render: Called right after rendering.

    I/O:
    (Note that the preferred way to change the input/output is by creating an
    `AppSession` with the required input/output objects. If you need multiple
    applications running at the same time, you have to create a separate
    `AppSession` using a `with create_app_session():` block.

    :param input: :class:`~prompt_toolkit.input.Input` instance.
    :param output: :class:`~prompt_toolkit.output.Output` instance. (Probably
                   Vt100_Output or Win32Output.)

    Usage:

        app = Application(...)
        app.run()

        # Or
        await app.run_async()
    NTFg{Gz?      ?z#ApplicationEventHandler[_AppResult])layoutstyleinclude_default_pygments_stylestyle_transformationkey_bindings	clipboardfull_screencolor_depthmouse_supportenable_page_navigation_bindings
paste_modeediting_modeerase_when_donereverse_vi_search_directionmin_redraw_intervalmax_render_postpone_timerefresh_intervalterminal_size_polling_intervalcursoron_reseton_invalidatebefore_renderafter_renderinputoutputreturnc                    s  |
d u rt  fdd}
t|}t|	}	t|}t|
}
t|}|d u rNt }|d u r\t }| _| _| _t  _t	  _
| _|pt  _| _| _|	 _| _| _| _| _|
 _| _| _| _| _t| _t | _t | _t | _t | _ t! }|p"|j" _"|p0|j# _#g  _$d _%d  _&d  _'d  _(d _)t*  _+t,  _-d _.d _/ 0| _1t2 j1 j"||	 j3d _4d _5d _6g  _7d _8t9t:  _;d _<d  _= >  d S )	Nc                      s    j S N)ri    selfr~   b/var/www/html/django/DPS/env/lib/python3.9/site-packages/prompt_toolkit/application/application.py<lambda>       z&Application.__init__.<locals>.<lambda>Frb   g      ?)ri   rk   cpr_not_supported_callbackr   g        )?r-   r0   rG   rQ   rd   rf   rg   r6   _default_bindingsr5   _page_navigation_bindingsrc   r$   rh   ri   _color_depthrk   rm   rn   ro   rp   rl   rq   rr   rs   rt   r&   ru   rW   rw   rv   rx   ry   rZ   r{   rz   pre_run_callables_is_runningfutureloopcontextZquoted_insertrA   vi_stater7   emacs_statettimeoutlenZ
timeoutlen_create_merged_style_merged_stylerL   r   rendererrender_counter_invalidated_invalidate_events_last_redraw_timer@   _CombinedRegistrykey_processor_running_in_terminal_running_in_terminal_freset)r   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   sessionr~   r   r   __init__   s    $
	zApplication.__init__)re   r|   c                    sB   t   t ttd fdd}tt |tfddgS )z
        Create a `Style` object that merges the default UI style, the default
        pygments style, and the custom user style.
        r|   c                      s    r
S  S d S r}   r~   r~   )dummy_stylere   pygments_styler~   r   conditional_pygments_stylei  s    zDApplication._create_merged_style.<locals>.conditional_pygments_stylec                      s    j S r}   rd   r~   r   r~   r   r   t  r   z2Application._create_merged_style.<locals>.<lambda>)rP   rT   rR   rO   rV   rU   )r   re   r   r~   )r   re   r   r   r   r   a  s    z Application._create_merged_styler   c                 C   s*   | j }t|r| }|du r&| j }|S )a  
        The active :class:`.ColorDepth`.

        The current value is determined as follows:

        - If a color depth was given explicitly to this application, use that
          value.
        - Otherwise, fall back to the color depth that is reported by the
          :class:`.Output` implementation. If the :class:`.Output` class was
          created using `output.defaults.create_output`, then this value is
          coming from the $PROMPT_TOOLKIT_COLOR_DEPTH environment variable.
        N)r   callabler{   Zget_default_color_depth)r   depthr~   r~   r   rj   x  s    
zApplication.color_depthc                 C   s   | j jptddS )a  
        The currently focused :class:`~.Buffer`.

        (This returns a dummy :class:`.Buffer` when none of the actual buffers
        has the focus. In this case, it's really not practical to check for
        `None` values or catch exceptions every time.)
        zdummy-buffer)name)rc   current_bufferr!   r   r~   r~   r   r     s    	
zApplication.current_bufferc                 C   s"   | j j}t|tr|jS t S dS )zv
        Return the current :class:`.SearchState`. (The one for the focused
        :class:`.BufferControl`.)
        N)rc   current_control
isinstancerE   Zsearch_staterN   )r   Z
ui_controlr~   r~   r   current_search_state  s    
z Application.current_search_statec                 C   s~   d| _ g | _| j  | j  | j  | j  | j  | j	  | j}|j
 sz| D ]}|j r`||_ qzq`dS )z?
        Reset everything, for reading the next input.
         N)
exit_stylebackground_tasksr   r   r   rc   r   r   rv   firer   Zis_focusableZfind_all_windowscontentcurrent_window)r   rc   wr~   r~   r   r     s    	







zApplication.resetc                    s   j s
dS jdu sj r"dS jr,dS d_jjj ddfddddfddjrt j	   jk rdd fdd	jfd
d q  n  dS )zW
        Thread safe way of sending a repaint trigger to the input event loop.
        NTr   c                      s   d _    d S NF)r   _redrawr~   r   r~   r   redraw  s    z&Application.invalidate.<locals>.redrawc                      s   t  jjd d S )N)Zmax_postpone_timer   )r+   rr   r   r~   )r   r   r~   r   schedule_redraw  s    
z/Application.invalidate.<locals>.schedule_redrawc                      s$   t ttj  I d H    d S r}   )r	   r   floatrq   r~   )diffr   r   r~   r   redraw_in_future  s    z0Application.invalidate.<locals>.redraw_in_futurec                      s      S r}   )create_background_taskr~   )r   r   r~   r   r     r   z(Application.invalidate.<locals>.<lambda>)
r   r   	is_closedr   r+   rw   r   rq   timer   r   r~   )r   r   r   r   r   r   
invalidate  s&    
zApplication.invalidatec                 C   s   | j S )z0True when a redraw operation has been scheduled.)r   r   r~   r~   r   invalidated  s    zApplication.invalidated)render_as_doner|   c                    s2   dd fdd}j dur.j  | dS )z
        Render the command line again. (Not thread safe!) (From other threads,
        or if unsure, use :meth:`.Application.invalidate`.)

        :param render_as_done: make sure to put the cursor after the UI.
        Nr   c                      s   j rjsjrt _ jd7  _j   r`jrJj	
  qpj	jj d nj	j j  j    d S )NrY   )is_done)r   r   rq   r   r   r   rx   r   ro   r   eraserenderrc   Zupdate_parents_relationsry   _update_invalidate_eventsr~   r   r   r~   r   run_in_context  s    



z+Application._redraw.<locals>.run_in_context)r   copyrun)r   r   r   r~   r   r   r     s    !
zApplication._redrawc                    s<    j dur8 j dkr8tdd fdd} | j  dS )zi
        Start a while/true loop in the background for automatic invalidation of
        the UI.
        Nr   )rs   r|   c                    s   t | I d H     q d S r}   )r	   r   )rs   r   r~   r   auto_refresh6  s    z:Application._start_auto_refresh_task.<locals>.auto_refresh)rs   r   r   )r   r   r~   r   r   _start_auto_refresh_task/  s    z$Application._start_auto_refresh_taskc                    sV    j D ]}| j8 }qttt  d fdd}t|  _  j D ]}| j7 }qBdS )zg
        Make sure to attach 'invalidate' handlers to all invalidate events in
        the UI.
        r   c                  3   s"    j  D ]} |  E d H  q
d S r}   )rc   find_all_controlsZget_invalidate_events)cr   r~   r   gather_eventsI  s    z<Application._update_invalidate_events.<locals>.gather_eventsN)r   _invalidate_handlerr   rW   objectlist)r   evr   r~   r   r   r   =  s    

z%Application._update_invalidate_events)senderr|   c                 C   s   |    dS )a  
        Handler for invalidate events coming from UIControls.

        (This handles the difference in signature between event handler and
        `self.invalidate`. It also needs to be a method -not a nested
        function-, so that we can remove it again .)
        N)r   )r   r   r~   r~   r   r   R  s    zApplication._invalidate_handlerc                 C   s"   | j jdd |   |   dS )z
        When the window size changes, we erase the current output and request
        again the cursor position. When the CPR answer arrives, the output is
        drawn again.
        F)Zleave_alternate_screenN)r   r   !_request_absolute_cursor_positionr   r   r~   r~   r   
_on_resize\  s    zApplication._on_resize)pre_runr|   c                 C   s,   |r
|  | j D ]
}|  q| j dd= dS )a  
        Called during `run`.

        `self.future` should be set to the new future at the point where this
        is called in order to avoid data races. `pre_run` can be used to set a
        `threading.Event` to synchronize with UI termination code, running in
        another thread that would call `Application.exit`. (See the progress
        bar code for an example.)
        N)r   )r   r   r   r~   r~   r   _pre_runh  s
    

zApplication._pre_run)r   set_exception_handlerhandle_sigintslow_callback_durationr|   c              	      s  j rJ dt rtjdkr"d dtdfdd}ttt dfd	d
}ttd dfdd}tttd d fdd}tttd dfdd}	tttd dfdd}
ttddfdd}t }|	|  d_
|	| }|	|| |	|	| |	|
| |	t |	  |	||}z,||I dH W  I dH  W  d   S  I dH  0 W d   n1 s0    Y  dsJ ddS )aY  
        Run the prompt_toolkit :class:`~prompt_toolkit.application.Application`
        until :meth:`~prompt_toolkit.application.Application.exit` has been
        called. Return the value that was passed to
        :meth:`~prompt_toolkit.application.Application.exit`.

        This is the main entry point for a prompt_toolkit
        :class:`~prompt_toolkit.application.Application` and usually the only
        place where the event loop is actually running.

        :param pre_run: Optional callable, which is called right after the
            "reset" of the application.
        :param set_exception_handler: When set, in case of an exception, go out
            of the alternate screen and hide the application, display the
            exception, and wait for the user to press ENTER.
        :param handle_sigint: Handle SIGINT signal if possible. This will call
            the `<sigint>` key binding when a SIGINT is received. (This only
            works in the main thread.)
        :param slow_callback_duration: Display warnings if code scheduled in
            the asyncio event loop takes more time than this. The asyncio
            default of `0.1` is sometimes not sufficient on a slow system,
            because exceptionally, the drawing of the app, which happens in the
            event loop, can take a bit longer from time to time.
        zApplication is already running.win32Fzasyncio.Future[_AppResult])fr|   c                    sN  t  _d    jtj j	  d d fdd}d dfdd d dfddj
  j| tjR         zI d H }W zjdd	 W j  d
_jD ]}|j8 }qg _jjr6j I d H  j}|rL|I d H  tjj  nrj  d
_jD ]}|j8 }qvg _jjrj I d H  j}|r|I d H  tjj  0 nzjdd	 W j  d
_jD ]}|j8 }qg _jjr,j I d H  j}|rB|I d H  tjj  nrj  d
_jD ]}|j8 }qlg _jjrj I d H  j}|r|I d H  tjj  0 0 |W  d    W  d    W  d    S 1 s 0    Y  W d    n1 s 0    Y  W d    n1 s@0    Y  d S )Nr   c                     sj   j sjjsd S j } j|  j  jjrN	 sf
t nrZ    d S r}   )r   r   Zwaiting_for_cprrz   Z	read_keysr   feed_multipleprocess_keyscloseddoneset_exceptionEOFErrorcancelr   keys)auto_flush_inputr   
flush_taskr   r~   r   read_from_input  s    

zBApplication.run_async.<locals>._run_async.<locals>.read_from_inputc                      s   t jI d H     d S r}   )r	   r   r~   )flush_inputr   r~   r   r     s    zCApplication.run_async.<locals>._run_async.<locals>.auto_flush_inputc                     s<   j s8j } j|  j  jjr8 t d S r}   )	r   rz   Z
flush_keysr   r   r   r   r   r   r   )r   r   r~   r   r     s    

z>Application.run_async.<locals>._run_async.<locals>.flush_inputT)r   F)contextvarscopy_contextr   r   r   r   r   r3   rz   r   Zraw_modeattachattach_winch_signal_handlerr   r   r   r   r   _poll_output_sizer   r   r   r   r{   responds_to_cprZwait_for_cpr_responsesr   r4   Zempty_queue)r   r   resultr   Zprevious_run_in_terminal_f)r   r   )r   r   r   r   r   
_run_async  s    


















z)Application.run_async.<locals>._run_asyncr   c                  3   s*   t  } |  _z| V  W d  _nd  _0 d S r}   )r,   r   r   r   r~   r   get_loop  s
    z'Application.run_async.<locals>.get_loopNc                   3   s$   d _ zd V  W d _ nd _ 0 d S )NTFr   r~   r   r~   r   set_is_running!  s    z-Application.run_async.<locals>.set_is_running)r   r|   c              	   3   sN   rD  tj fdd zd V  W  tj qJ tj 0 nd V  d S )Nc                     s     jjS r}   )r+   r   Zsend_sigint)_)r   r   r~   r   r   .  s   zBApplication.run_async.<locals>.set_handle_sigint.<locals>.<lambda>)add_signal_handlersignalSIGINTremove_signal_handlerr   )r   r   r   r   set_handle_sigint)  s    z0Application.run_async.<locals>.set_handle_sigintc              	   3   sF   r<|   }|  j zd V  W | | qB| | 0 nd V  d S r}   )get_exception_handlerr   _handle_exception)r   Zprevious_exc_handler)r   r   r~   r   set_exception_handler_ctx9  s    z8Application.run_async.<locals>.set_exception_handler_ctxc                 3   s*   | j } | _ zd V  W || _ n|| _ 0 d S r}   r   )r   Zoriginal_slow_callback_durationr   r~   r   set_callback_durationF  s
    z4Application.run_async.<locals>.set_callback_durationz$Iterator[asyncio.Future[_AppResult]]c                 3   s,   |   }| _z|V  W d  _nd  _0 d S r}   )create_futurer   )r   r   r   r~   r   r   Q  s
    z,Application.run_async.<locals>.create_futureZunreachable)r   rX   sysplatformr_   r   r   r   r
   enter_contextr   r[   _enable_breakpointhook$cancel_and_wait_for_background_tasks)r   r   r   r   r   r   r   r   r   r   r   r   stackr   r   r~   )r   r   r   r   r   r   	run_asyncz  sD    u	
0zApplication.run_async)r   r   r   	in_threadr|   c                    s   |rNd dd fdd}t j|d}|  |   durJ S z
t }W n  tyx   t }t| Y n0 |j	|dS )a*  
        A blocking 'run' call that waits until the UI is finished.

        This will start the current asyncio event loop. If no loop is set for
        the current thread, then it will create a new loop. If a new loop was
        created, this won't close the new loop (if `in_thread=False`).

        :param pre_run: Optional callable, which is called right after the
            "reset" of the application.
        :param set_exception_handler: When set, in case of an exception, go out
            of the alternate screen and hide the application, display the
            exception, and wait for the user to press ENTER.
        :param in_thread: When true, run the application in a background
            thread, and block the current thread until the application
            terminates. This is useful if we need to be sure the application
            won't use the current event loop (asyncio does not support nested
            event loops). A new event loop will be created in this background
            thread, and that loop will also be closed when the background
            thread terminates. When this is used, it's especially important to
            make sure that all asyncio background tasks are managed through
            `get_appp().create_background_task()`, so that unfinished tasks are
            properly cancelled before the event loop is closed. This is used
            for instance in ptpython.
        :param handle_sigint: Handle SIGINT signal. Call the key binding for
            `Keys.SIGINT`. (This only works in the main thread.)
        Nr   c               
      s   z^zj ddW n( ty> }  z|  W Y d } ~ n
d } ~ 0 0 W t }||  |  nt }||  |  0 d S )NFr   r   r   )r   BaseExceptionr,   run_until_completeshutdown_asyncgensclose)er   	exceptionr   r   r   r   r~   r   run_in_thread  s    

z&Application.run.<locals>.run_in_thread)targetr  )
	threadingThreadstartjoinr,   RuntimeErrorr   r   r  r  )r   r   r   r   r  r  threadr   r~   r  r   r     s*    !
zApplication.run)r   r   r|   c                    s8   t  }dt|dd fdd}t|  dS )zr
        Handler for event loop exceptions.
        This will print the exception, using run_in_terminal.
        r   Nr   c                	      sp   t  4 I d H H td t td d tdI d H  W d   I d H  ql1 I d H sb0    Y  d S )Nz#
Unhandled exception in event loop:zException {}r  Press ENTER to continue...)r\   printformatget_do_wait_for_enterr~   r   Zformatted_tbr~   r   in_term  s
    z.Application._handle_exception.<locals>.in_term)r)   r  r   r   )r   r   r   tbr  r~   r  r   r     s    
zApplication._handle_exceptionNNNc                 c   sH   t jdkr>t jt jkr>| jt _zdV  W t jt _qDt jt _0 ndV  dS )z
        Install our custom breakpointhook for the duration of this context
        manager. (We will only install the hook if no other custom hook was
        set.)
        )      N)r   version_infobreakpointhook__breakpointhook___breakpointhookr   r~   r~   r   r    s    z"Application._enable_breakpointhook)akwr|   c                    sd   | ddl }ddlm  t ttgtf G  fddd|j}t j	}|tj
d| dS )z
        Breakpointhook which uses PDB, but ensures that the application is
        hidden and input echoing is restored during each debugger dispatch.
        r   N)	FrameTypec                       s*   e Zd Zeed fddZ  ZS )z.Application._breakpointhook.<locals>.CustomPdb)frameeventargr|   c              	      s   j   j X j . t |||W  d    W  d    S 1 sT0    Y  W d    n1 sr0    Y  d S r}   )r   r   rz   detachZcooked_modesupertrace_dispatch)r   r(  r)  r*  )	__class__appr~   r   r-    s    
z=Application._breakpointhook.<locals>.CustomPdb.trace_dispatch)__name__
__module____qualname__strr   r-  __classcell__r~   r'  ZTraceDispatchr/  )r.  r   	CustomPdb  s   r6  )stdout)pdbtypesr'  r   r3  r   ZPdbr   	_getframef_back
__stdout__	set_trace)r   r%  r&  r8  r6  r(  r~   r5  r   r$    s    
zApplication._breakpointhookzasyncio.Task[None])	coroutiner|   c                 C   s   t  |}| j| |S )ae  
        Start a background task (coroutine) for the running application. When
        the `Application` terminates, unfinished background tasks will be
        cancelled.

        If asyncio had nurseries like Trio, we would create a nursery in
        `Application.run_async`, and run the given coroutine in that nursery.

        Not threadsafe.
        )r,   create_taskr   append)r   r>  taskr~   r~   r   r   %  s    z"Application.create_background_taskc              	      sF   | j D ]}|  q| j D ]&}z|I dH  W q ty>   Y q0 qdS )a"  
        Cancel all background tasks, and wait for the cancellation to be done.
        If any of the background tasks raised an exception, this will also
        propagate the exception.

        (If we had nurseries like Trio, this would be the `__aexit__` of a
        nursery.)
        N)r   r   r   )r   rA  r~   r~   r   r  6  s    	


z0Application.cancel_and_wait_for_background_tasksc                    sR   d}| j }|du rdS t|I dH  | j }|durH||krH|   |}qdS )z
        Coroutine for polling the terminal dimensions.

        Useful for situations where `attach_winch_signal_handler` is not sufficient:
        - If we are not running in the main thread.
        - On Windows.
        N)rt   asyncior	   r{   get_sizer   )r   sizeintervalnew_sizer~   r~   r   r   H  s    
zApplication._poll_output_sizec                    s*    j jsdS dd fdd}t| dS )zT
        Called when we don't receive the cursor position response in time.
        Nr   c                      s    j d  j   d S )NzHWARNING: your terminal doesn't support cursor position requests (CPR).
)r{   writeflushr~   r   r~   r   r\   e  s    z;Application.cpr_not_supported_callback.<locals>.in_terminal)r{   r   r]   )r   r\   r~   r   r   r   ^  s    z&Application.cpr_not_supported_callbackc                 C   s   dS )zExit without arguments.Nr~   r   r~   r~   r   exitm  s    zApplication.exitr   r   )r   rd   r|   c                C   s   dS )zExit with `_AppResult`.Nr~   )r   r   rd   r~   r~   r   rI  q  s    )r  rd   r|   c                C   s   dS )zExit with exception.Nr~   )r   r  rd   r~   r~   r   rI  u  s    )r   r  rd   r|   c                 C   sj   |du s|du sJ | j du r&td| j  r8td|| _|durT| j | n| j tt| dS )a  
        Exit application.

        .. note::

            If `Application.exit` is called before `Application.run()` is
            called, then the `Application` won't exit (because the
            `Application.future` doesn't correspond to the current run). Use a
            `pre_run` hook and an event to synchronize the closing if there's a
            chance this can happen.

        :param result: Set this result for the application.
        :param exception: Set this exception as the result for an application. For
            a prompt, this is often `EOFError` or `KeyboardInterrupt`.
        :param style: Apply this style on the whole content when quitting,
            often this is 'class:exiting' for a prompt. (Used when
            `erase_when_done` is not set.)
        Nz6Application is not running. Application.exit() failed.z4Return value already set. Application.exit() failed.)r   	Exceptionr   r   r   
set_resultr   r_   )r   r   r  rd   r~   r~   r   rI  {  s    

c                 C   s   | j js| js| j  dS )z#
        Send CPR request.
        N)r   Zinput_queuer   r   Z request_absolute_cursor_positionr   r~   r~   r   r     s    z-Application._request_absolute_cursor_positionr  )commandwait_for_enterdisplay_before_text	wait_textr|   c              	      s   t  4 I dH  zj W n ty:   tj Y n0 zj W n tyf   tj Y n0 dd fdd}t|I dH  |rt	|I dH  W d  I dH  q1 I dH s0    Y  dS )a  
        Run system command (While hiding the prompt. When finished, all the
        output will scroll above the prompt.)

        :param command: Shell command to be executed.
        :param wait_for_enter: FWait for the user to press enter, when the
            command is finished.
        :param display_before_text: If given, text to be displayed before the
            command executes.
        :return: A `Future` object.
        Nr   c                     s&     t dd} |   d S )NT)shellstdinr7  )
print_textr   wait)prL  rN  Zinput_fdZ	output_fdr   r~   r   run_command  s    
z3Application.run_system_command.<locals>.run_command)
r\   rz   filenoAttributeErrorr   rQ  r{   r7  r*   r  )r   rL  rM  rN  rO  rV  r~   rU  r   run_system_command  s    zApplication.run_system_command)suspend_groupr|   c                    s&   t dur"dd fdd}t| dS )z
        (Not thread safe -- to be called from inside the key bindings.)
        Suspend process.

        :param suspend_group: When true, suspend the whole process group.
            (This is the default, and probably what you want.)
        Nr   c                     s0   t tt}  rtd|  ntt |  d S )Nr   )r   int_SIGTSTPoskillgetpid)r   rZ  r~   r   r     s    
z.Application.suspend_to_background.<locals>.run)r\  r]   )r   rZ  r   r~   r`  r   suspend_to_background  s    
z!Application.suspend_to_background)textrd   r|   c                 C   s"   t | j||p| j| j| jd dS )a\  
        Print a list of (style_str, text) tuples to the output.
        (When the UI is running, this method has to be called through
        `run_in_terminal`, otherwise it will destroy the UI.)

        :param text: List of ``(style_str, text)`` tuples.
        :param style: Style class to use. Defaults to the active style in the CLI.
        )r{   Zformatted_textrd   rj   rf   N)rM   r{   r   rj   rf   )r   rb  rd   r~   r~   r   rR    s    zApplication.print_textc                 C   s   | j S )z8`True` when the application is currently active/running.r   r   r~   r~   r   
is_running  s    zApplication.is_runningc                 C   s   | j r| j  S dS r   )r   r   r   r~   r~   r   r     s    
zApplication.is_donec                 C   s&   | j j}|r"tdd | D S g S )z|
        Return a list of used style strings. This is helpful for debugging, and
        for writing a new `Style`.
        c                 s   s    | ]}t d d| V  qdS )z\s+ N)resubstrip).0Z	style_strr~   r~   r   	<genexpr>  s   z5Application.get_used_style_strings.<locals>.<genexpr>)r   Z_attrs_for_stylesortedr   )r   Zattrs_for_styler~   r~   r   get_used_style_strings  s    z"Application.get_used_style_strings)F)N)NTTrb   )NTTF)NNr   )Tr   r  )T)N)Gr0  r1  r2  __doc__r(   ZEMACSr   rH   rO   r/   rS   r<   r#   boolr   rJ   r   r   r[  r%   r2   rK   r   r.   r   propertyrj   r!   r   rN   r   r   r   r   r   r   r   r   r   r   r   r_   r  r   r   r   r3  r   r   r   r   r  r$  r   r   r  r   r   r    rI  r  r   r   r1   rY  ra  rR  rc  r   r   rk  r~   r~   r~   r   r^   t   s2  R  5,
          X!   '   * c                   @   s   e Zd ZdZee ddddZeedddZ	e
e dd	d
Zee
e edddZeedddZee
e dddZee
e dddZdS )r   z
    The `KeyBindings` of key bindings for a `Application`.
    This merges the global key bindings with the one of the current user
    control.
    N)r/  r|   c                 C   s   || _ t | _d S r}   )r/  r"   _cache)r   r/  r~   r~   r   r   %  s    z_CombinedRegistry.__init__r   c                 C   s   t dS zZNot needed - this object is not going to be wrapped in another
        KeyBindings object.NNotImplementedErrorr   r~   r~   r   _version+  s    z_CombinedRegistry._versionc                 C   s   t dS rp  rq  r   r~   r~   r   bindings1  s    z_CombinedRegistry.bindings)r   other_controlsr|   c           	      C   s   g }t  }|}|| | }|dur2|| | r<q\| jj|}|du rVq\q|}qt|D ]*}||vrd| }|durd|t	| qd| jj
r|| jj
 |t| jj| jj || jj |ddd }t|S )z
        Create a `KeyBindings` object that merges the `KeyBindings` from the
        `UIControl` with all the parent controls and the global key bindings.
        N)setaddZget_key_bindingsr@  Zis_modalr/  rc   Z
get_parentrI   r:   rg   r9   r   rl   r   r>   )	r   r   ru  rg   Zcollected_containers	containerkbparentr   r~   r~   r   _create_key_bindings6  s:    

z&_CombinedRegistry._create_key_bindingsc                    s@   j jj tj j  tf}j| fddS )Nc                      s     S r}   )r|  r~   r   ru  r   r~   r   r   s  r   z1_CombinedRegistry._key_bindings.<locals>.<lambda>)r/  rc   r   r   r   	frozensetro  r  )r   keyr~   r}  r   _key_bindingsl  s    
z_CombinedRegistry._key_bindings)r   r|   c                 C   s   | j |S r}   )r  get_bindings_for_keysr   r   r~   r~   r   r  v  s    z'_CombinedRegistry.get_bindings_for_keysc                 C   s   | j |S r}   )r  get_bindings_starting_with_keysr  r~   r~   r   r  y  s    z1_CombinedRegistry.get_bindings_starting_with_keys)r0  r1  r2  rl  r^   r_   r   rn  r   rs  r   r8   rt  rD   rF   r<   r|  r  r=   r  r  r~   r~   r~   r   r     s   6	r   )rO  r|   c                    sh   ddl m} t }|dtdddd}|tjtdddd	}|| |d
}|j I dH  dS )z
    Create a sub application to wait for the enter key press.
    This has two advantages over using 'input'/'raw_input':
    - This will share the same input/output I/O.
    - This doesn't block the event loop.
    r   )PromptSessionZenterN)r)  r|   c                 S   s   | j   d S r}   )r/  rI  r)  r~   r~   r   _ok  s    z_do_wait_for_enter.<locals>._okc                 S   s   dS )zDisallow typing.Nr~   r  r~   r~   r   _ignore  s    z#_do_wait_for_enter.<locals>._ignore)messagerg   )	Zprompt_toolkit.shortcutsr  r;   rx  ErB   r   r/  r  )rO  r  rg   r  r  r   r~   r~   r   r  }  s    
r  r  )handlerr|   c              	   c   s   t tdd}|du st s$dV  dS t }t |di |}z@|||  dV  W || |dur|j||jg|jR   n,|| |dur|j||jg|jR   0 dS )a  
    Attach the given callback as a WINCH signal handler within the context
    manager. Restore the original signal handler when done.

    The `Application.run` method will register SIGWINCH, so that it will
    properly repaint when the terminal window resizes. However, using
    `run_in_terminal`, we can temporarily send an application to the
    background, and run an other app in between, which will then overwrite the
    SIGWINCH. This is why it's important to restore the handler when the app
    terminates.
    r`   N_signal_handlers)	getattrr   rX   r,   r  r   r   	_callback_args)r  Zsigwinchr   Zprevious_winch_handlerr~   r~   r   r     s2    


r   )rB  r]  re  r   r   r  r   r   r   r   r   r   r   r   r	   
contextlibr
   r   
subprocessr   	tracebackr   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    Zprompt_toolkit.bufferr!   Zprompt_toolkit.cacher"   Zprompt_toolkit.clipboardr#   r$   Zprompt_toolkit.cursor_shapesr%   r&   Zprompt_toolkit.data_structuresr'   Zprompt_toolkit.enumsr(   Zprompt_toolkit.eventloopr)   r*   Zprompt_toolkit.eventloop.utilsr+   r,   Zprompt_toolkit.filtersr-   r.   r/   r0   Zprompt_toolkit.formatted_textr1   Zprompt_toolkit.input.baser2   Zprompt_toolkit.input.typeaheadr3   r4   Z3prompt_toolkit.key_binding.bindings.page_navigationr5   Z#prompt_toolkit.key_binding.defaultsr6   Z&prompt_toolkit.key_binding.emacs_stater7   Z'prompt_toolkit.key_binding.key_bindingsr8   r9   r:   r;   r<   r=   r>   Z(prompt_toolkit.key_binding.key_processorr?   r@   Z#prompt_toolkit.key_binding.vi_staterA   Zprompt_toolkit.keysrB   Z prompt_toolkit.layout.containersrC   rD   Zprompt_toolkit.layout.controlsrE   rF   Zprompt_toolkit.layout.dummyrG   Zprompt_toolkit.layout.layoutrH   rI   Zprompt_toolkit.outputrJ   rK   Zprompt_toolkit.rendererrL   rM   Zprompt_toolkit.searchrN   Zprompt_toolkit.stylesrO   rP   rQ   rR   rS   rT   rU   rV   Zprompt_toolkit.utilsrW   rX   currentrZ   r[   r]   r\   r   ImportErrorZ*prompt_toolkit.eventloop.dummy_contextvarsZ	eventloopZdummy_contextvars__all__r  r_   ZApplicationEventHandlerr  Z	_SIGWINCHr\  r^   r   r  r   r~   r~   r~   r   <module>   s   (
T$	(
         3_
