a
    Df                     @  s  d Z ddlm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
Z
ddlZddlmZmZ ddlmZ ddlmZ ddlmZ ddlmZ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' dd
l(m)Z) ddl*m+Z+ ddl,Z,ddl-m.Z. ddl/m0Z0 ddl1m2Z3 ddl4m5Z6 ddl7m8Z8m9Z9 ddlm:Z:m;Z; e<dZ=er ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZG ddlHmIZI ddl4mJZJ ddlKmLZL ddlMmNZN ddlOmPZP ddlQmRZR dd lSmTZT dd!lUmVZV dd"lWmXZX dd#lYmZZZ dd$l[m\Z\ e&d%Z]ed&d'd(d)Z^d&d*d+d,Z_G d-d. d.Z`e'ejeejgejf e ej f ZaG d/d0 d0e,jbZcec ZddS )1zH
Various utilities for recording and embedding state in a rendered app.
    )annotationsN)Counterdefaultdict)Iterator)contextmanager)
ContextVar)partialwraps)TYPE_CHECKINGAny	AwaitableCallableClassVar	CoroutineDictr   ListLiteralOptionalTupleTypeTypeVarUnion)urljoin)WeakKeyDictionary)Document)UnlockedDocumentProxy)curdoc)CommManager   )decode_tokenparse_timedelta   )LOG_SESSION_RENDEREDLOG_USER_MSGzpanel.state)Future)Model)ImportedStyleSheet)BokehSessionContext)Server)DisplayHandle)CommIOLoop)BaseTemplate)Viewable)BooleanIndicatorBrowserInfoPeriodicCallbackLocationNotificationArea)StoppableThreadTr   docc              	   c  s6   t j| }zd V  W t j| nt j| 0 d S N)state_curdocsetreset)r;   token rB   [/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/panel/io/state.py
set_curdoc?   s    rD   returnc                  C  s4   z
t  } W n ty   Y d S 0 t| tr0| j} | S r<   )r>   RuntimeError
isinstancer   Z_docr:   rB   rB   rC   curdoc_lockedG   s    

rI   c                   @  s   e Zd ZdS )
_UndefinedN)__name__
__module____qualname__rB   rB   rB   rC   rJ   P       rJ   c                	   @  sX  e Zd ZU dZejddddZejddddZej	i dd	Z
ejd
dd	ZejddddZej	ddi ddd	Zejd
dd	Zejddd	Zej	i dd	Zedd
dZdZded< e Zded< d
Zd
ZeZded< d
Zded< i Ze Zded< d
Z d ed!< e Z!d"ed#< d
Z"d$ed%< e Z#d&ed'< d
Z$d(ed)< e Z%d*ed+< d
Z&d,ed-< e Z'd.ed/< i Z(d0ed1< g Z)d2ed3< i Z*d4ed5< i Z+d6ed7< e Z,d8ed9< i Z-d:ed;< e Z.e Z/d<ed=< g Z0d>ed?< g Z1d>ed@< g Z2d>edA< e Z3dBedC< d
Z4i Z5dDedE< e Z6dFedG< g Z7dHedI< g Z8ej	e9e:dZ;i Z<e Z=dJedK< e Z>dLedM< dNe?@ iZAdOedP< i ZBi ZCe9e:ZDe9eEZFe ZGdQedR< i ZHeI ZJdSdTdUdVZKeLdWdTdXdYZMeLdZd[ ZNeLd\dTd]d^ZOeLd_dTd`daZPeLd_dTdbdcZQeLdddTdedfZReRjSdgdhdidjdfZRdkd_dldmdnZTejUdoddpdqdr ZVejUdsddpdhdTdtduZWdvdw ZXdxdy ZYeLdzd{ ZZdSd|d}d~Z[dkdhdlddZ\dddhdlddZ]d dSd_dhdddZ^dd Z_dddkdhdddZ`dhdTddZaddddZbddSddgddddZcdddgddgd_ddddZdddSd_dddZedd Zfdd ZgddddhdddZhdSdddZidhdTddZjddSdSdhdddZkddd_dddZlddhdddZmddhdddZnddSdddhdddÄZoddń Zpd	dSddddd_dhdʜdd̄ZqddhdΜddЄZrd
dd҄ZsddԄ ZteLd\dTddքZueLd\dTdd؄ZveLddTddۄZweLddTddބZxexjSdkdhdlddބZxeLddTddZyeLddTddZzeLd_dTddZ{eLddTddZ|eLdd Z}eLddTddZ~eLd\dTddZeLdd ZeLddTddZeLddTddZeLd\dTddZeLddTddZd
S (  _statezw
    Holds global state associated with running apps, allowing running
    apps to indicate their state to a user.
    /Tz&
       Base URL for all server paths.)defaultreadonlyr;   FzT
       Whether the application is currently busy processing a user
       callback.z
       Global location you can use to cache large datasets or expensive computation results
       across multiple client sessions for a given server.)rQ   r;   Nz}
       Object with encrypt and decrypt methods to support encryption
       of secret variables including OAuth information. z
       Relative path from the current app being served to the root URL.
       If application is embedded in a different server via autoload.js
       this will instead reflect an absolute path.r   )totallivesessionsz>
       Tracks information and statistics about user sessions.z>
      Selenium webdriver used to export bokeh models to pngs.z:
       Count of active callbacks current being processed.z1
       A dictionary used by the cache decorator.r   )rQ   zClassVar[bool]_holdz*ClassVar[WeakKeyDictionary[Document, int]]_thread_id_zClassVar[Type[_CommManager]]_comm_managerz$ClassVar[BokehSessionContext | None]_jupyter_kernel_contextz*ClassVar[WeakKeyDictionary[Document, Any]]_ipykernelszClassVar[BrowserInfo | None]_browserz2ClassVar[WeakKeyDictionary[Document, BrowserInfo]]	_browserszClassVar[Location | None]	_locationz/ClassVar[WeakKeyDictionary[Document, Location]]
_locationsz!ClassVar[NotificationArea | None]_notificationz7ClassVar[WeakKeyDictionary[Document, NotificationArea]]_notificationszClassVar[BaseTemplate | None]	_templatez3ClassVar[WeakKeyDictionary[Document, BaseTemplate]]
_templateszBClassVar[Dict[str, Tuple[Viewable, Model, Document, Comm | None]]]_viewszClassVar[List[str]]_fake_rootszKClassVar[Dict[str, Tuple[Server, Viewable | BaseTemplate, List[Document]]]]_serversz$ClassVar[Dict[str, StoppableThread]]_threadsz0ClassVar[WeakKeyDictionary[Any, Dict[str, Any]]]_server_configz/ClassVar[Dict[str, [DisplayHandle, List[str]]]]_handlesz,ClassVar[Dict[Document, Callable[[], None]]]_onloadz3ClassVar[List[Callable[[BokehSessionContext], []]]]_on_session_created_on_session_created_internal_on_session_destroyedz+ClassVar[WeakKeyDictionary[Document, bool]]_loadedz=ClassVar[Dict[str, Tuple[Iterator[int], Callable[[], None]]]]
_scheduledz=ClassVar[WeakKeyDictionary[Document, List[PeriodicCallback]]]	_periodicz ClassVar[List[BooleanIndicator]]_indicatorszDClassVar[WeakKeyDictionary[Document, Dict[str, ImportedStyleSheet]]]_stylesheetsz0ClassVar[WeakKeyDictionary[Document, List[str]]]_extensions_mainz#ClassVar[Dict[str, threading.Lock]]_cache_locksz5ClassVar[WeakKeyDictionary[Document, Dict[str, Any]]]_session_outputsstrrE   c                 C  sN   g }| j  D ]&\}}}|d|jp(d|j| q|s>dS dd|S )Nz{}:{:d} - {!r}	localhostzstate(servers=[])zstate(servers=[
  {}
])z,
  )rf   valuesappendformataddressportjoin)selfZserver_infoserverZpanelZ_docsrB   rB   rC   __repr__   s    z_state.__repr__z'IOLoop'c                 C  s&   t jrt S ddlm} | S d S )Nr   r+   )r=   _is_pyodideasyncioZget_running_looptornado.ioloopr,   current)r   r,   rB   rB   rC   _ioloop   s    z_state._ioloopc                 C  s"   | j }|r|| jv sd S | j| S r<   )r   rs   r   r;   rB   rB   rC   _extensions   s    z_state._extensionsz
str | Nonec                 C  s   t  S r<   )	threading	get_identr   rB   rB   rC   _current_thread   s    z_state._current_threadboolc                 C  s,   | j }|r|jr|jjsdS t|jjj S )NF)r   session_contextserver_contextr   rV   r   r   rB   rB   rC   _is_launching   s    z_state._is_launchingc                 C  s
   dt jv S )NZ_pyodide)sysmodulesr   rB   rB   rC   r     s    z_state._is_pyodidez
int | Nonec                 C  s   | j r| j| j S d S r<   )r   rX   getr   rB   rB   rC   
_thread_id  s    z_state._thread_idintNone)	thread_idrF   c                 C  s   | j r|| j| j < d S r<   )r   rX   )r   r   rB   rB   rC   r   	  s    r   )r;   rF   c                 C  s4   || j u o2| j| jdfv o2| p2|j p2| j|S )a  
        Indicates whether Document events can be dispatched or have
        to scheduled on the event loop. Events can only be safely
        dispatched if:

        1. The Document to be modified is the same one that the server
           is currently processing.
        2. We are on the same thread that the Document was created on.
        3. The application has fully loaded and the Websocket is open.
        N)r   r   r   r   rn   r   r   rB   rB   rC   
_unblocked  s    z_state._unblocked_busy_counter)watchc                 C  s   | j dk| _d S )Nr!   )r   busyr   rB   rB   rC   _update_busy_counter  s    z_state._update_busy_counterr   c                 C  s   | j D ]}| j|_qd S r<   )rq   r   valuer   	indicatorrB   rB   rC   _update_busy"  s    
z_state._update_busyc                 C  s   | j jsd S ddlm} | j jj}| jd |i }|dd urFd S |tt| j  | jd  d7  < |	dt
j  i | jd d S )Nr!   )loggerrV   renderedrU   session_info)r   r   r   r   idr   r   infor"   updatedtdatetimenow	timestampparamtrigger)r   eventr   
session_idr   rB   rB   rC   _init_session'  s    
z_state._init_sessionc           	   	   C  s  |j }| jd }||v rl|| d d u rl|| }|d d urN| jd  d8  < tj  |d< | jd |j}|| j	v r| j	| D ]&}z|
| W q ty   Y q0 q| j	|= || jv rtj| }|| tj|= || jv r| j| }|| tj|= || jv r| j|= d S )NrV   Zendedr   rU   r!   r   )r   r   r   r   r   r   r   r   	_documentrp   _cleanup	Exceptionr_   r=   Z_server_destroyra   rc   )	r   r   r   rV   sessionr;   cblocZnotificationrB   rB   rC   _destroy_session6  s4    






z_state._destroy_sessionc                 C  s>   t  }| j|d }|d u r:ddlm} | }|| j|< |S )Nr!   )_Stack)r   current_thread_stacksr   cacher   )r   r   stackr   rB   rB   rC   _current_stackZ  s    
z_state._current_stack)endpointc                   s   i   fdd}|S )Nc                    sJ  | d }|j d u r|jn|j }j d }||vr8d S t|g   fdd| D sbd S tt|< |D ]}t|v rqvzrz|jjf i  W n ty    Y n0 W t|v rfddt| D }|r|t|< n
t|= qvt|v rBfddt| D }|r8|t|< n
t|= 0 qvd S )Nr   c                   s    i | ]}|j  vr|j |jqS rB   )namenew).0r   )updatingrB   rC   
<dictcomp>m  s   
z6_state._get_callback.<locals>.link.<locals>.<dictcomp>c                   s   g | ]}| vr|qS rB   rB   )r   p)ry   rB   rC   
<listcomp>{  rN   z6_state._get_callback.<locals>.link.<locals>.<listcomp>)	objcls_rest_endpointsr   r   listr   r   r   )eventsr   r   parameterizedsparameterizedZnot_updatedZ	_updatingr   r   )r   ry   rC   linkf  s6    
z"_state._get_callback.<locals>.linkrB   )r   r   r   rB   r   rC   _get_callbackd  s    z_state._get_callbackc                 C  s:   | j r,| j | j|}|t| j|d n
| | d S )Nr:   )_thread_poolsubmit_on_loadadd_done_callbackr   _handle_future_exception)r   r;   r   futurerB   rB   rC   _schedule_on_load  s    z_state._schedule_on_loadzOptional[Document]c              	   C  sp  |p| j }|| jvr"d| j|< d S ddlm} ddlm} t| |rT|| jv sZ|js|| jv r| j	|D ]\}}| j
||rdndd qpqZd| j|< W d    d S ||jH}|| jv r| j	|D ]\}}| j
||rdndd qqW d    n1 s0    Y  |jjj}| j|d	 |jf  |7  < | jd
 W d    n1 sX0    Y  d| j|< d S )NTr   configr!   )profile_ctxthreadFschedulez:on_load	_profiles)r   rj   rn   r   profiler   rD   
_launchingZprofilerpopexecuter   requestpathr   r   r   )r   r;   r   r   r   threadedrV   r   rB   rB   rC   r     s*    





:
,z_state._on_load)r   r   rF   c           	   
     s   || j vrd S | j | \}}zt|}W n tyF   d }| j |= Y n0 |d ur~tj  }|| }| jj|t	| j
|d z| j||rdndd W n. ty } z| | W Y d }~n
d }~0 0 d S )Ndelaycallbackr   autor   )ro   nextr   r   r   r   r   r   
call_laterr   _scheduled_cbr   _handle_exception)	r   r   r   diterr   atr   call_time_secondserB   rB   rC   r     s     
z_state._scheduled_cbc                   s   t   fdd}|S )Nc               
     sD   z | i |W S  t y> } z| W Y d }~n
d }~0 0 d S r<   )r   r   )argskwr   r   r   rB   rC   wrapper  s    z1_state._handle_exception_wrapper.<locals>.wrapper)r	   )r   r   r   rB   r   rC   _handle_exception_wrapper  s    z _state._handle_exception_wrapperr$   )r   r;   rF   c                 C  sJ   |  }|d u rd S t| | | W d    n1 s<0    Y  d S r<   )	exceptionrD   r   )r   r   r;   r   rB   rB   rC   r     s
    
z_state._handle_future_exceptionc                 C  sF   ddl m } |jr|| n$t|tr.|n| jd| dd d S )Nr   r   z"Exception of unknown type raised: error)level)r   Zexception_handlerrH   BaseExceptionlog)r   r   r   rB   rB   rC   r     s    
z_state._handle_exceptionr'   )r   c                 C  s   | j D ]}|j| qd S r<   )rm   r   on_session_destroyed)r   r   r   rB   rB   rC   _register_session_destroyed  s    
z"_state._register_session_destroyedzCallable[[], T]r9   )keyfnttlrF   c           
      K  sV  |ft dd t| D  }|r0t | nd}| jd 8 || jv rV| j| }nt  | j|< }W d   n1 s|0    Y  z|r || jv r| j	|\}}n
t
d }}|t
u s|dur|t k r|f i ||f \}}	| j|< W d   n1 s0    Y  W | sR|| jv rR| j|= n | sP|| jv rP| j|= 0 |S )a&  
        Caches the return value of a function globally across user sessions, memoizing on the given
        key and supplied keyword arguments.

        Note: Keyword arguments must be hashable.

        Example:

        >>> def load_dataset(name):
        >>>     # some slow operation that uses name to load a dataset....
        >>>     return dataset
        >>> penguins = pn.state.as_cached('dataset-penguins', load_dataset, name='penguins')

        Arguments
        ---------
        key: (str)
          The key to cache the return value under.
        fn: (callable)
          The function or callable whose return value will be cached.
        ttl: (int)
          The number of seconds to keep an item in the cache, or None
          if the cache should not expire. The default is None.
        **kwargs: dict
          Additional keyword arguments to supply to the function,
          which will be memoized over as well.

        Returns
        -------
        Returns the value returned by the cache or the value in
        the cache.
        c                 s  s   | ]\}}||fV  qd S r<   rB   r   kvrB   rB   rC   	<genexpr>  rN   z#_state.as_cached.<locals>.<genexpr>Nrt   )tuplesorteditemstime	monotonicru   r   Lockr   r   rJ   locked)
r   r   r   r   kwargsZ
new_expirylockretZexpiry_rB   rB   rC   	as_cached  s$      
0

B

z_state.as_cached  z.Callable[[], None] | Coroutine[Any, Any, None]zOptional[int]r3   )r   periodcounttimeoutstartrF   c                 C  s\   ddl m} |||||d}|r(|  | jrX| j| jvrFg | j| j< | j| j | |S )a  
        Schedules a periodic callback to be run at an interval set by
        the period. Returns a PeriodicCallback object with the option
        to stop and start the callback.

        Arguments
        ---------
        callback: callable
          Callable function to be executed at periodic interval.
        period: int
          Interval in milliseconds at which callback will be executed.
        count: int
          Maximum number of times callback will be invoked.
        timeout: int
          Timeout in seconds when the callback should be stopped.
        start: boolean (default=True)
          Whether to start callback immediately.

        Returns
        -------
        Return a PeriodicCallback object with start and stop methods.
        r!   r2   )r   r  r  r  )	callbacksr3   r  r   rp   rz   )r   r   r  r  r  r  r3   r   rB   rB   rC   add_periodic_callback
  s    z_state.add_periodic_callback)r   waitc                 C  sD   || j vrtd|d|r8d| j | d f| j |< n| j |= dS )a  
        Cancel a task scheduled using the `state.schedule_task` method by name.

        Arguments
        ---------
        name: str
            The name of the scheduled task.
        wait: boolean
            Whether to wait until after the next execution.
        zNo task with the name z has been scheduled.Nr!   )ro   KeyError)r   r   r  rB   rB   rC   cancel_task1  s
    
z_state.cancel_taskc              	   C  s^   | j  D ]D}|  t|dr
|j  zt|j W q
 t	yL   Y q
0 q
| j   dS )zE
        Clears caches generated by panel.io.cache function.
        	directoryN)
_memoize_cachery   clearhasattrr   closeshutilrmtreer  OSError)r   r   rB   rB   rC   clear_cachesC  s    

z_state.clear_cachesc                 C  sT   t |8 tj|r$tj| n| j|dd W d    n1 sF0    Y  d S )NFr   )rD   r   r   iscoroutinefunctionasync_executorr   )r   r;   r   rB   rB   rC   _execute_on_threadQ  s    
z_state._execute_on_threadr   zCallable([], None)z bool | Literal['auto', 'thread'])r   r   rF   c              
   C  s   | j }|dkr@tjstdtjt| j||}|| j nt	j
|rZt	j
| np|r|jr|dks~|dkr| |s|| | n:z
|  W n. ty } zt| W Y d}~n
d}~0 0 dS )aR  
        Executes both synchronous and asynchronous callbacks
        appropriately depending on the context the application is
        running in. When running on the server callbacks are scheduled
        on the event loop ensuring the Bokeh Document lock is acquired
        and models can be modified directly.

        Arguments
        ---------
        callback: Callable[[], None]
          Callback to execute
        schedule: boolean | Literal['auto', 'thread']
          Whether to schedule the callback on the event loop, on a thread
          or execute them immediately.
        r   z_Cannot execute callback on thread. Ensure you have enabled threading setting `config.nthreads`.Tr   N)r   r=   r   rG   r   r   r%  r   r   r   r   r#  r$  r   r   Zadd_next_tick_callbackr   r   r   )r   r   r   r;   r   r   rB   rB   rC   r   X  s     $
z_state.executer   c                   s0   ddl m} | fddtj D d d S )z
        Returns the requested profiling output.

        Arguments
        ---------
        profile: str
          The name of the profiling output to return.

        Returns
        -------
        Profiling output wrapped in a pane.
        r!   )get_profilesc                   s&   i | ]\\}}}| kr||f|qS rB   rB   )r   nr   Zpsr&  rB   rC   r     s   z&_state.get_profile.<locals>.<dictcomp>r   )r   r'  r=   r   r  )r   r   r'  rB   r&  rC   get_profile  s    z_state.get_profilec              	   C  sh   | j D ]H}|| jv r$| j|   qz| j | d   W q tyL   Y q0 q| j   | j  dS )zI
        Stop all servers and clear them from the current state.
        r   N)rf   rg   stopAssertionErrorr  )r   Z	server_idrB   rB   rC   kill_all_servers  s    


z_state.kill_all_serversr   )msgr   rF   c                 C  s@   d}| j r"t| j f}tj|d}tt| |g|R   dS )z
        Logs user messages to the Panel logger.

        Arguments
        ---------
        msg: str
          Log message
        level: str
          Log level as a string, i.e. 'debug', 'info', 'warning' or 'error'.
        rB   )r-  N)r   r   r#   r{   getattr_state_loggerlower)r   r-  r   r   rB   rB   rC   r     s
    z
_state.logz@Callable[[], None | Awaitable[None]] | Coroutine[Any, Any, None])r   r   c                 C  sp   | j du s| js| jr>| jr,| j|dd n| j|dd dS | j | jvrVg | j| j < | j| j  ||f dS )aC  
        Callback that is triggered when a session has been served.

        Arguments
        ---------
        callback: Callable[[], None] | Coroutine[Any, Any, None]
           Callback that is executed when the application is loaded
        threaded: bool
          Whether the onload callback can be threaded
        Nr   r   F)r   r   loadedr   r   rj   rz   )r   r   r   rB   rB   rC   onload  s    z_state.onloadz%Callable[[BokehSessionContext], None])r   rF   c                 C  s&   | j r| j jrtd| j| dS )zG
        Callback that is triggered when a session is created.
        zCannot register session creation callback from within a session. If running a Panel application from the CLI set up the callback in a --setup script, if starting a server dynamically set it up before starting the server.N)r   r   rG   rk   rz   )r   r   rB   rB   rC   on_session_created  s
    z_state.on_session_createdc                 C  s@   | j }|r|| n&| j| jvr0| j| j | j| dS )zI
        Callback that is triggered when a session is destroyed.
        N)r   r   r   rk   rz   rm   )r   r   r;   rB   rB   rC   r     s    z_state.on_session_destroyedzparam.ParameterizedzOptional[List[str]])r   r   
parametersrF   c                   s    du rt |j |dr(|dd }|| jv r| j| \}}}t t|krZtd fdd|d j  D }|jjf i | |	| n| 
|}|g |f| j|< |j|  dS )a  
        Publish parameters on a Parameterized object as a REST API.

        Arguments
        ---------
        endpoint: str
          The endpoint at which to serve the REST API.
        parameterized: param.Parameterized
          The Parameterized object to publish parameters from.
        parameters: list(str) or None
          A subset of parameters on the Parameterized to publish.
        NrP   r!   z<Param REST API output parameters must match across sessions.c                   s   i | ]\}}| v r||qS rB   rB   r   r4  rB   rC   r     rN   z"_state.publish.<locals>.<dictcomp>r   )r   r   
startswithr   r?   
ValueErrorry   r  r   rz   r   r   )r   r   r   r4  r   Zold_parametersr   ry   rB   r5  rC   publish  s    


 
z_state.publishc                 C  s   |    | j  d| _| j  | j  | j  | j  | j  | j	  | j
durr| j
jdd d| _
| j  | j  | j  | j  dS )zz
        Resets the state object killing running servers and clearing
        any other state held by the server.
        NF)r  )r,  rq   r  r^   r_   rc   rd   rn   r   ro   r   shutdown	_sessions_session_key_funcsrk   rm   r   rB   rB   rC   r@     s     










z_state.resetzCallable[[], None]Tatzstr | dt.timedeltazOptional[str])r   r   r   r  cronr   rF   c                   s  || j v r:|| j | d ur6| jd|d|d dS t|dddrTtd	|du rttrnt fd
d}| }n,ddl	m	}	  du rt
j n }
|	||
}t
j  }zt|| }W n ty   Y dS 0 ||f| j |< | jj|t| j||d dS )ac  
        Schedules a task at a specific time or on a schedule.

        By default the starting time is immediate but may be
        overridden with the `at` keyword argument. The scheduling may
        be declared using the `period` argument or a cron expression
        (which requires the `croniter` library). Note that the `at`
        time should be in local time but if a callable is provided it
        must return a UTC time.

        Note that the scheduled callback must not be defined within a
        script served using `panel serve` because the script and all
        its contents are cleaned up when the user session is
        destroyed. Therefore the callback must be imported from a
        separate module or should be scheduled from a setup script
        (provided to `panel serve` using the `--setup` argument). Note
        also that scheduling is idempotent, i.e.  if a callback has
        already been scheduled under the same name subsequent calls
        will have no effect. This is ensured that even if you schedule
        a task from within your application code, the task is only
        scheduled once.

        Arguments
        ---------
        name: str
          Name of the scheduled task
        callback: callable
          Callback to schedule
        at: datetime.datetime, Iterator or callable
          Declares a time to schedule the task at. May be given as a
          datetime or an Iterator of datetimes in the local timezone
          declaring when to execute the task. Alternatively may also
          declare a callable which is given the current UTC time and
          must return a datetime also in UTC.
        period: str or datetime.timedelta
          The period between executions, may be expressed as a
          timedelta or a string:

            - Week:   '1w'
            - Day:    '1d'
            - Hour:   '1h'
            - Minute: '1m'
            - Second: '1s'

        cron: str
          A cron expression (requires croniter to parse)
        threaded: bool
          Whether the callback should be run on a thread (requires
          config.nthreads to be set).
        r!   z5A separate task was already scheduled under the name zk. The new task will be ignored. If you want to replace the existing task cancel it with `state.cancel_task(z7)` before adding adding a new task under the same name.NrL   rS   
bokeh_app_zCannot schedule a task from within the context of an application. Either import the task callback from a separate module or schedule the task from a setup script that you provide to `panel serve` using the --setup commandline argument.c                  3  s   t  tr t } |  V  q
nVt r` tj } | d u rBt| j	tj
jd  V  q(nd u rv  V  t ptj }| V  |7 }qd S )N)tzinfo)rH   r   r   r   callabler   r   utcnowStopIterationreplacetimezoneutc
astimezoner   )r   Znew_timer   r  rB   rC   dgen`  s    


z"_state.schedule_task.<locals>.dgenr   )croniterr   )ro   r   warningr.  r6  rG   rH   rw   r    rI  r   r   r   r   r   rB  r   r   r   r   )r   r   r   r   r  r=  r   rH  r   rI  baser   r   rB   rG  rC   schedule_task  s>    7


z_state.schedule_taskr/   )r   rF   c                 C  s2   t |jjtjstd|| jvr.| j| dS )z
        Syncs the busy state with an indicator with a boolean value
        parameter.

        Arguments
        ---------
        indicator: An BooleanIndicator to sync with the busy property
        z:Busy indicator must have a value parameterof Boolean type.N)rH   r   r   Booleanr7  rq   rz   r   rB   rB   rC   	sync_busy  s    	
z_state.sync_busyc                 C  sH   ddl m} ddlm} | j|}|d u r0d S ||j||}| |S )Nr   decode_signed_valuer   r   )tornado.webrP  r   cookiesr   cookie_secret_decrypt_cookie)r   Zcookie_namecookierP  r   rB   rB   rC   _decode_cookie  s    z_state._decode_cookiec                 C  s&   | j d u r|dS | j |dS )Nutf-8)
encryptiondecodeZdecrypt)r   rU  rB   rB   rC   rT    s    

z_state._decrypt_cookiec                 C  s   | j | jv r,d| j| j  v r,| j| j  d S | d}|s>dS zt|}W n ty`   | Y S 0 |d tjtjj	
 krdS |S )z<
        Returns the OAuth access_token if enabled.
        access_tokenNexp)user_oauth_user_overridesrV  r   r   r   r   r   rD  rE  r   )r   rZ  decoded_tokenrB   rB   rC   rZ    s    

z_state.access_tokenc                 C  s>   | j s
dS | j jjjj}|dr.|dd n|}t| j|S )zN
        Returns the URL of the app that is currently being executed.
        NrP   r!   )r   r   r   Zapplication_contexturlr6  r   base_url)r   app_urlrB   rB   rC   ra    s
    z_state.app_urlzBrowserInfo | Nonec                 C  s   ddl m } ddlm} |jrL| jrL| jjrL| j| jvrL|  }| j| j< nB| jd u rv| jd u rn|jrn| | _| j}n| jr| j| jnd }|S )Nr   r   r!   r0   )	r   browserr1   browser_infor   r   r]   r\   r   )r   r   r1   rb  rB   rB   rC   rc    s     
z_state.browser_infozDocument | Nonec                 C  sZ   | j  }|r|S z.t }| jo(dtjv}|r>|js8|r>|W S W n tyT   Y dS 0 dS )zH
        Returns the Document that is currently being executed.
        Zpyodide_kernelN)r>   r   rI   r   r   r   r   r   )r   r   r;   Zpyodide_sessionrB   rB   rC   r     s    

z_state.curdocc                 C  s   | j | dS )z1
        Overrides the current Document.
        N)r>   r?   r   rB   rB   rC   r     s    zDict[str, str]c                 C  s   | j r| j jr| j jjjS i S )z[
        Returns the cookies associated with the request that started the session.
        )r   r   r   rR  r   rB   rB   rC   rR    s    z_state.cookieszDict[str, str | List[str]]c                 C  s   | j r| j jr| j jjjS i S )zZ
        Returns the header associated with the request that started the session.
        )r   r   r   headersr   rB   rB   rC   rd    s    z_state.headersc                 C  s,   | j }|r(|| jv r| j| S |jr(dS dS )z@
        Whether the application has been fully loaded.
        FT)r   rn   r   r   rB   rB   rC   r1    s    

z_state.loadedzLocation | Nonec                 C  sz   | j rL| j | jvrLddlm} | j jr8|| j jj}n| }|| j| j < n*| j d u r^| j}n| j rr| j| j nd }|S )Nr!   r4   )	r   r_   locationr5   r   Zfrom_requestr   r^   r   )r   r5   r   rB   rB   rC   re     s    
z_state.locationc                 C  s   ddl m} |S )Nr!   )log_terminal)Zadminrf  )r   rf  rB   rB   rC   rf    s    z_state.log_terminalzNotificationArea | Nonec                 C  s   ddl m } |jr| jr| jjr| j| jvrddlm} i }|jrTd|jdd|d< |jrjd	|jd
|d< ||d | j| j< }|S | jd u s| jjd u r| jS | jr| j	| jS d S d S )Nr   r   r!   r6   successi  )typemessagedurationZdocument_readyr   )rh  ri  Zconnection_lost)	js_events)
r   notificationsr   r   ra   r7   Zready_notificationZdisconnect_notificationr`   r   )r   r   r7   rk  rl  rB   rB   rC   rl    s     z_state.notificationsc                 C  s   | j | jv r&d| jv r&| j| j  d S | d}|s8dS zt|}W n tyZ   | Y S 0 |d tjtjj	
 kr|dS |S )zK
        Returns the OAuth refresh_token if enabled and available.
        refresh_tokenNr[  )r\  r]  rV  r   r7  r   r   r   rD  rE  r   )r   rm  r^  rB   rB   rC   rm  %  s    

z_state.refresh_tokenc                 C  s6   zt  d jjd dW S  ty0   Y dS 0 dS )zx
        Whether we are currently inside a script or notebook that is
        being served using `panel serve`.
        r!   rK   r>  FN)inspectr   frame	f_globalsr6  r   r   rB   rB   rC   served7  s    z_state.servedzDict[str, List[bytes]]c                 C  s   | j r| j jr| j jjjS i S )ze
        Returns the request arguments associated with the request that started the session.
        )r   r   r   	argumentsr   rB   rB   rC   session_argsB  s    z_state.session_argszBaseTemplate | Nonec                 C  sj   ddl m } | j| jv r$| j| j S | jd u r:| jr:| jS |j|jd}| jd u rZ|| _n|| j| j< |S )Nr   r   )theme)r   r   rc   rb   templatert  )r   r   ru  rB   rB   rC   ru  I  s    
z_state.templatec                 C  sb   ddl m} ddlm} | jd}|r,dS | jd}|du sJ|jdu rNdS ||jd|d	S )
z4
        Returns the OAuth user if enabled.
        r   rO  r   r   is_guestguestr\  NrW  )rQ  rP  r   rR  r   rS  rY  )r   rP  r   rv  r\  rB   rB   rC   r\  W  s    z_state.userzDict[str, Any] | Nonec                 C  s8   | j d}|rdddS | d}|du r0dS t|S )z@
        Returns the OAuth user information if enabled.
        rv  rw  )r\  usernameid_tokenN)rR  r   rV  r   )r   rv  ry  rB   rB   rC   	user_infoh  s    

z_state.user_info)N)F)N)N)r  NNT)F)r   )r   )F)N)NNNF)N)rK   rL   rM   __doc__r   Stringr`  rM  r   r   r   	ParameterrX  rel_pathr   Z	webdriverZIntegerr   r  r   r>   rW   __annotations__r   rX   r   Z_admin_context_CommManagerrY   rZ   Z_kernelsr[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   r   rj   rk   rl   rm   rn   Z_setup_modulero   rp   rq   r   r   r   r   r   rr   rs   r   r	  ru   r:  r;  Z_cell_outputsdictZ_cell_layoutsrv   r]  r   Z_active_usersr   propertyr   r   r   r   r   r   setterr   dependsr   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r"  r%  r   r)  r,  r   r2  r3  r   r8  r@   rL  rN  rV  rT  rZ  ra  rc  r   rR  rd  r1  re  rf  rl  rm  rq  rs  ru  r\  rz  rB   rB   rB   rC   rO   T   s.  



$
			6 '
'   m




rO   )er{  
__future__r   r   r   r   rn  loggingr  r   r   r  collectionsr   r   collections.abcr   
contextlibr   Zcontextvarsr   	functoolsr   r	   typingr
   r   r   r   r   r   r   Z	TIteratorr   r   r   r   r   r   r   urllib.parser   weakrefr   r   Zbokeh.documentr   Zbokeh.document.lockingr   Zbokeh.ior   r>   Zpyviz_commsr   r  utilr   r    r"   r#   	getLoggerr/  concurrent.futuresr$   Zbokeh.modelr%   Zbokeh.modelsr&   Zbokeh.server.contextsr'   Zbokeh.server.serverr(   ZIPython.displayr)   r*   r   r,   Ztemplate.baser-   Zviewabler.   Zwidgets.indicatorsr/   rb  r1   r  r3   re  r5   rl  r7   r   r8   r9   rD   rI   rJ   r<  ZParameterizedrO   r=   rB   rB   rB   rC   <module>   st   D
	$        )