
    6OneM                        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 n#  d dlmZ Y nxY wd dlZddlm	Z	 e j
                            e j
                            e                    Z ee j
                            edd                    5 Z ej        e          Zddd           n# 1 swxY w Y   d Z	  e             n# e$ r dZY nw xY we j
                            e j
                            e                    Z ee j
                            ed                    5 Zd	e                                z   Zddd           n# 1 swxY w Y    G d
 dej                  ZdZdZdZdZ  G d de!          Z" G d dej#                  Z$ G d de$          Z% G d de%          Z& G d de'          Z( G d de(          Z)dS )    N)StringIO   )__version__labextensionzpackage.jsonc                  $    dt           d         dgS )Nr   name)srcdest)data     4lib/python3.11/site-packages/pyviz_comms/__init__.py_jupyter_labextension_pathsr      s     V   r   znotebook.jsz

c                   j    e Zd ZdZg Zg ZdZdZd Ze	d             Z
e	d             Ze	d             ZdS )	extensionz]
    Base class for pyviz extensions, which allow defining shared cleanup
    utilities.
    NFc                     	 t                      j        }|| j        k    t          _        |t          _        n# t
          $ r Y nw xY wt          j        j        | g|R i |S N)	get_ipythonexecution_count_last_execution_countr   _repeat_execution_in_cell	ExceptionparamParameterizedFunction__new__)clsargskwargs
exec_counts       r   r   zextension.__new__7   st    	$6J3=AZ3ZI/ /9I++ 	 	 	D	*23HHHHHHHs   47 
AAc                 :    | j                             |           d S r   )_delete_actionsappendr   actions     r   add_delete_actionzextension.add_delete_actionB   s    ""6*****r   c                 :    | j                             |           d S r   )_server_delete_actionsr"   r#   s     r   add_server_delete_actionz"extension.add_server_delete_actionF   s    "))&11111r   c                     |d         }|dk    r| j         D ]} ||d                    dS |dk    r| j        D ]} ||d                    dS dS )ze
        Processes comm messages to handle global actions such as
        cleaning up plots.
        
event_typedeleteidserver_deleteN)r!   r'   )r   msgr*   r$   s       r   _process_comm_msgzextension._process_comm_msgJ   s     &
!!- " "s4y!!!!" "?**4 " "s4y!!!! +*" "r   )__name__
__module____qualname____doc__r!   r'   r   r   r   classmethodr%   r(   r/   r   r   r   r   r   '   s          O   ! %	I 	I 	I + + [+ 2 2 [2 " " [" " "r   r   z
if ((window.PyViz === undefined) || (window.PyViz instanceof HTMLElement)) {
  window.PyViz = {comms: {}, comm_status:{}, kernels:{}, receivers: {}, plot_index: []}
}
a*  
if (!window.PyViz) {{
  return;
}}
var events = [];
var receiver = window.PyViz.receivers['{plot_id}'];
if (receiver &&
        receiver._partial &&
        receiver._partial.content &&
        receiver._partial.content.events) {{
    events = receiver._partial.content.events;
}}

var value = cb_obj['{change}'];

{transform}

for (var event of events) {{
  if ((event.kind === 'ModelChanged') && (event.attr === '{change}') &&
      (cb_obj.id === event.model.id) &&
      (JSON.stringify(value) === JSON.stringify(event.new))) {{
    return;
  }}
}}
a9  
var plot_id = "{plot_id}";

if ((plot_id in window.PyViz.plot_index) && (window.PyViz.plot_index[plot_id] != null)) {{
  var plot = window.PyViz.plot_index[plot_id];
}} else if ((Bokeh !== undefined) && (plot_id in Bokeh.index)) {{
  var plot = Bokeh.index[plot_id];
}}

if (plot == null) {{
  return
}}

if (plot_id in window.PyViz.receivers) {{
  var receiver = window.PyViz.receivers[plot_id];
}} else {{
  var receiver = new Bokeh.protocol.Receiver();
  window.PyViz.receivers[plot_id] = receiver;
}}

if ((buffers != undefined) && (buffers.length > 0)) {{
  receiver.consume(buffers[0].buffer)
}} else {{
  receiver.consume(msg)
}}

const comm_msg = receiver.message;
if ((comm_msg != null) && (Object.keys(comm_msg.content).length > 0)) {{
  plot.model.document.apply_json_patch(comm_msg.content, comm_msg.buffers)
}}
aZ
  
function unique_events(events) {{
  // Processes the event queue ignoring duplicate events
  // of the same type
  var unique = [];
  var unique_events = [];
  for (var i=0; i<events.length; i++) {{
    var _tmpevent = events[i];
    event = _tmpevent[0];
    data = _tmpevent[1];
    if (unique_events.indexOf(event)===-1) {{
      unique.unshift(data);
      unique_events.push(event);
      }}
  }}
  return unique;
}}

function process_events(comm_status) {{
  // Iterates over event queue and sends events via Comm
  var events = unique_events(comm_status.event_buffer);
  for (var i=0; i<events.length; i++) {{
    var data = events[i];
    var comm = window.PyViz.comms[data["comm_id"]];
    comm.send(data);
  }}
  comm_status.event_buffer = [];
}}

function on_msg(msg) {{
  // Receives acknowledgement from Python, processing event
  // and unblocking Comm if event queue empty
  var metadata = msg.metadata;
  var comm_id = metadata.comm_id
  var comm_status = window.PyViz.comm_status[comm_id];
  if (comm_status.event_buffer.length) {{
    process_events(comm_status);
    comm_status.blocked = true;
    comm_status.time = Date.now()+{debounce};
  }} else {{
    comm_status.blocked = false;
  }}
  comm_status.event_buffer = [];
  if ((metadata.msg_type == "Ready") && metadata.content) {{
    console.log("Python callback returned following output:", metadata.content);
  }} else if (metadata.msg_type == "Error") {{
    console.log("Python failed with the following traceback:", metadata.traceback)
  }}
}}

// Initialize Comm
if ((window.PyViz == undefined) || (window.PyViz.comm_manager == undefined)) {{ return }}
var comm = window.PyViz.comm_manager.get_client_comm("{plot_id}", "{comm_id}", on_msg);
if (!comm) {{
  return
}}

// Initialize event queue and timeouts for Comm
var comm_status = window.PyViz.comm_status["{comm_id}"];
if (comm_status === undefined) {{
  comm_status = {{event_buffer: [], blocked: false, time: Date.now()}}
  window.PyViz.comm_status["{comm_id}"] = comm_status
}}

// Add current event to queue and process queue if not blocked
var event_name = cb_obj.event_name;
if (event_name === undefined) {{
  // we are a widget not an event... fake a key.
  event_name = Object.keys(data).join(',');
}}
data['comm_id'] = "{comm_id}";
var timeout = comm_status.time + {timeout};
if ((comm_status.blocked && (Date.now() < timeout))) {{
  comm_status.event_buffer.unshift([event_name, data]);
}} else {{
  comm_status.event_buffer.unshift([event_name, data]);
  setTimeout(function() {{ process_events(comm_status); }}, {debounce});
  comm_status.blocked = true;
  comm_status.time = Date.now()+{debounce};
}}
c                       e Zd ZdZd Zd ZdS )StandardOutputz
    Context manager to capture standard output for any code it
    is wrapping and make it available as a list, e.g.:

    >>> with StandardOutput() as stdout:
    ...   print('This gets captured')
    >>> print(stdout[0])
    This gets captured
    c                 f    t           j        | _        t                      xt           _        | _        | S r   )sysstdout_stdoutr   	_stringioselfs    r   	__enter__zStandardOutput.__enter__   s"    z&.jj0
T^r   c                     |                      | j                                                                                   | j        t
          _        d S r   )extendr;   getvalue
splitlinesr:   r8   r9   )r=   r   s     r   __exit__zStandardOutput.__exit__   s;    DN++--88::;;;\


r   N)r0   r1   r2   r3   r>   rC   r   r   r   r6   r6      s<           
" " " " "r   r6   c                        e Zd ZdZdZ ej        d          ZdZd fd	Z	ddZ
d	 Zddg fd
Zed             Zed             Zd Z xZS )Comma  
    Comm encompasses any uni- or bi-directional connection between
    a python process and a frontend allowing passing of messages
    between the two. A Comms class must implement methods
    send data and handle received message events.

    If the Comm has to be set up on the frontend a template to
    handle the creation of the comms channel along with a message
    handler to process incoming messages must be supplied.

    The template must accept three arguments:

    * id          -  A unique id to register to register the comm under.
    * msg_handler -  JS code which has the msg variable in scope and
                     performs appropriate action for the supplied message.
    * init_frame  -  The initial frame to render on the frontend.
    z@
    <div id="fig_{plot_id}">
      {init_frame}
    </div>
    z'Unique identifier of this Comm instance)doc Nc                     || _         || _        || _        || _        d| _        t          t          |                               |r|nt          j	                    j
                   dS ),
        Initializes a Comms object
        N)r,   )_on_msg	_on_error
_on_stdout_on_open_commsuperrE   __init__uuiduuid4hex)r=   r,   on_msgon_error	on_stdouton_open	__class__s         r   rP   zComm.__init__  sa     !#
dD""b(Fdjll6F"GGGGGr   c                     dS )z,
        Initializes comms channel.
        Nr   )r=   rT   s     r   initz	Comm.init*        r   c                     dS ,
        Closes the comm connection
        Nr   r<   s    r   closez
Comm.close/  r[   r   c                     dS )z,
        Sends data to the frontend
        Nr   r=   r   metadatabufferss       r   sendz	Comm.send4  r[   r   c                     |S )z@
        Decode incoming message, e.g. by parsing json.
        r   r   r.   s     r   decodezComm.decode9  s	    
 
r   c                 <    | j         st          d          | j         S )NzComm has not been initialized)rN   
ValueErrorr<   s    r   commz	Comm.comm@  s#    z 	><===zr   c                    d}	 g }|                      |          }|                    dd          }| j        r[t                      5 }|                     |           ddd           n# 1 swxY w Y   |r	 |                     |           n#  Y nxY w|rdd                    |          z   nd}d|d}n# t          $ r}	 |                     |           n#  Y nxY wd}t          j	        t          j                    d                   }|d	d         D ]+}|\  }	}
}}t          ||	|

          }| dj        di |z  },|d                    t          |          j        t!          |                    z  }|r/dd                    |          z   }d                    ||g          }d|d}Y d}~nd}~ww xY w|r||d<   |                     |           dS )zn
        Decode received message before passing it to on_msg callback
        if it has been defined.
        Ncomm_idz
	rG   Ready)msg_typecontent
   i)fnfnamelinez{fname} {fn} L{line}
z	{type}: {error})typeerrorError)rn   	traceback)rb   r   )rg   poprJ   r6   rL   joinr   rK   rx   
extract_tbr8   exc_infodictformatru   r0   strrd   )r=   r.   rl   r9   replyerv   framesframers   linenorr   texterror_kwargss                 r   _handle_msgzComm._handle_msgF  s   
  	=F++c""Cggi..G| 	 $%% &LL%%%& & & & & & & & & & & & & & & ////$ 4:AVFKK////rF!(V<<EE%  	> 	> 	>q!!!!E)#,..*;<<F I I',$fR#rVDDD818HH<HHH(//T!WW5ESQRVV/TTTE 3F 3 33		65/22!(u==EEEEEE	>,  	'&E)		5	!!!!!sg   AB6 A(B6 (A,,B6 /A,0B6 6B B6 BB6 6
F:CF5CCF55F:NNNNNr   )r0   r1   r2   r3   html_templater   Stringr,   js_templaterP   rZ   r_   rd   r4   rg   propertyrj   r   __classcell__rX   s   @r   rE   rE     s         $M 
C	D	D	DBK	H 	H 	H 	H 	H 	H   
  
 tR    
   [   X
," ," ," ," ," ," ,"r   rE   c                   F    e Zd ZdZdZd Zed             Zd Zddg fdZ	dS )JupyterCommz~
    JupyterComm provides a Comm for the notebook which is initialized
    the first time data is pushed to the frontend.
    a  
    function msg_handler(msg) {{
      var metadata = msg.metadata;
      var buffers = msg.buffers;
      var msg = msg.content.data;
      if ((metadata.msg_type == "Ready")) {{
        if (metadata.content) {{
          console.log("Python callback returned following output:", metadata.content);
        }}
      }} else if (metadata.msg_type == "Error") {{
        console.log("Python failed with the following traceback:", metadata.traceback)
      }} else {{
        {msg_handler}
      }}
    }}
    if ((window.PyViz == undefined) || (!window.PyViz.comm_manager)) {{
      console.log("Could not find comm manager")
    }} else {{
      window.PyViz.comm_manager.register_target('{plot_id}', '{comm_id}', msg_handler);
    }}
    c                     ddl m} | j        rd S  || j        i           | _        | j                            | j                   | j        r|                     i            d S d S )Nr   )rE   )target_namer   )ipykernel.commrE   rN   r,   rT   r   rM   )r=   IPyComms     r   rZ   zJupyterComm.init  s    222222: 	FWr:::

$*+++= 	MM"	 	r   c                     |d         d         S )z
        Decodes messages following Jupyter messaging protocol.
        If JSON decoding fails data is assumed to be a regular string.
        ro   r   r   rf   s     r   rg   zJupyterComm.decode  s     9~f%%r   c                 J    | j         r| j                                          dS dS r]   )rN   r_   r<   s    r   r_   zJupyterComm.close  s2     : 	J	 	r   Nc                 v    | j         s|                                  | j                            |||           dS z1
        Pushes data across comm socket.
        )rb   rc   N)rN   rZ   rj   rd   ra   s       r   rd   zJupyterComm.send  s;     z 	IIKKK	th@@@@@r   )
r0   r1   r2   r3   r   rZ   r4   rg   r_   rd   r   r   r   r   r   u  s         
K,   & & [&   tR A A A A A Ar   r   c                   X     e Zd ZdZdZed             Zd	 fd	Zd Zd Z	ddg fdZ
 xZS )
JupyterCommJSz
    JupyterCommJS provides a comms channel for the Jupyter notebook,
    which is initialized on the frontend. This allows sending events
    initiated on the frontend to python.
    a  
    <script>
      function msg_handler(msg) {{
        var msg = msg.content.data;
        var buffers = msg.buffers
        {msg_handler}
      }}
      var comm = window.PyViz.comm_manager.get_client_comm("{comm_id}");
      comm.on_msg(msg_handler);
    </script>
    c                     t          |d         d                   }d|v r"d t          |d                   D             |d<   |S )Nro   r   rc   c                     i | ]\  }}||	S r   r   ).0ivs      r   
<dictcomp>z(JupyterCommJS.decode.<locals>.<dictcomp>  s    "N"N"NDAq1a"N"N"Nr   _buffers)r}   	enumerate)r   r.   decodeds      r   rg   zJupyterCommJS.decode  sL    s9~f-.."N"NIc)n4M4M"N"N"NGJr   Nc                     ddl m} t          t          |                               |||||            |            j        j        | _        | j                            | j	        | j
                   dS )rI   r   )r   N)IPythonr   rO   r   rP   kernelcomm_managermanagerregister_targetr,   _handle_open)r=   r,   rT   rU   rV   rW   r   rX   s          r   rP   zJupyterCommJS.__init__  ss     	('''''mT""++B)WUUU"{}}+8$$TWd.?@@@@@r   c                     | j         r| j                                          dS | j        | j        j        v r| j        j        | j        = dS t          d| j        z            )r^   z"JupyterCommJS %s is already closedN)rN   r_   r,   r   targetsAssertionErrorr<   s    r   r_   zJupyterCommJS.close  sf     : 	UJw$,...L(111$%IDG%STTTr   c                     || _         | j                             | j                   | j        r|                     |           d S d S r   )rN   rT   r   rM   )r=   rj   r.   s      r   r   zJupyterCommJS._handle_open  sN    

$*+++= 	MM#	 	r   c                 @    | j                             |||           dS r   )rj   rd   ra   s       r   rd   zJupyterCommJS.send  s$     		th@@@@@r   r   )r0   r1   r2   r3   r   r4   rg   rP   r_   r   rd   r   r   s   @r   r   r     s         
K   [A A A A A A
U 
U 
U   tR A A A A A A A Ar   r   c                   R    e Zd ZdZdZi ZeZeZe	dd            Z
e	dd            ZdS )CommManagerzu
    The CommManager is an abstract baseclass for establishing
    websocket comms on the client and the server.
    z
    function CommManager() {
    }

    CommManager.prototype.register_target = function() {
    }

    CommManager.prototype.get_client_comm = function() {
    }

    window.PyViz.comm_manager = CommManager()
    Nc                 V    |                      |||||          }|| j        |j        <   |S r   )server_comm_commsr,   r   rT   r,   rU   rV   rW   rj   s          r   get_server_commzCommManager.get_server_comm  .    r68YHH"
47r   c                 V    |                      |||||          }|| j        |j        <   |S r   )client_commr   r,   r   s          r   get_client_commzCommManager.get_client_comm  r   r   r   )r0   r1   r2   r3   
js_managerr   rE   r   r   r4   r   r   r   r   r   r   r     st         
J FKK   [
    [  r   r   c                       e Zd ZdZdZeZeZdS )JupyterCommManagerak  
    The JupyterCommManager is used to establishing websocket comms on
    the client and the server via the Jupyter comms interface.

    There are two cases for both the register_target and get_client_comm
    methods: one to handle the classic notebook frontend and one to
    handle JupyterLab. The latter case uses the globally available PyViz
    object which is made available by each PyViz project requiring the
    use of comms. This object is handled in turn by the JupyterLab
    extension which keeps track of the kernels associated with each
    plot, ensuring the corresponding comms can be accessed.
    a  
    function JupyterCommManager() {
    }

    JupyterCommManager.prototype.register_target = function(plot_id, comm_id, msg_handler) {
      if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {
        var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;
        comm_manager.register_target(comm_id, function(comm) {
          comm.on_msg(msg_handler);
        });
      } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {
        window.PyViz.kernels[plot_id].registerCommTarget(comm_id, function(comm) {
          comm.onMsg = msg_handler;
        });
      } else if (typeof google != 'undefined' && google.colab.kernel != null) {
        google.colab.kernel.comms.registerTarget(comm_id, (comm) => {
          var messages = comm.messages[Symbol.asyncIterator]();
          function processIteratorResult(result) {
            var message = result.value;
            console.log(message)
            var content = {data: message.data, comm_id};
            var buffers = []
            for (var buffer of message.buffers || []) {
              buffers.push(new DataView(buffer))
            }
            var metadata = message.metadata || {};
            var msg = {content, buffers, metadata}
            msg_handler(msg);
            return messages.next().then(processIteratorResult);
          }
          return messages.next().then(processIteratorResult);
        })
      }
    }

    JupyterCommManager.prototype.get_client_comm = function(plot_id, comm_id, msg_handler) {
      if (comm_id in window.PyViz.comms) {
        return window.PyViz.comms[comm_id];
      } else if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {
        var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;
        var comm = comm_manager.new_comm(comm_id, {}, {}, {}, comm_id);
        if (msg_handler) {
          comm.on_msg(msg_handler);
        }
      } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {
        var comm = window.PyViz.kernels[plot_id].connectToComm(comm_id);
        comm.open();
        if (msg_handler) {
          comm.onMsg = msg_handler;
        }
      } else if (typeof google != 'undefined' && google.colab.kernel != null) {
        var comm_promise = google.colab.kernel.comms.open(comm_id)
        comm_promise.then((comm) => {
          window.PyViz.comms[comm_id] = comm;
          if (msg_handler) {
            var messages = comm.messages[Symbol.asyncIterator]();
            function processIteratorResult(result) {
              var message = result.value;
              var content = {data: message.data};
              var metadata = message.metadata || {comm_id};
              var msg = {content, metadata}
              msg_handler(msg);
              return messages.next().then(processIteratorResult);
            }
            return messages.next().then(processIteratorResult);
          }
        }) 
        var sendClosure = (data, metadata, buffers, disposeOnDone) => {
          return comm_promise.then((comm) => {
            comm.send(data, metadata, buffers, disposeOnDone);
          });
        };
        var comm = {
          send: sendClosure
        };
      }
      window.PyViz.comms[comm_id] = comm;
      return comm;
    }
    window.PyViz.comm_manager = new JupyterCommManager();
    N)	r0   r1   r2   r3   r   r   r   r   r   r   r   r   r   r     s-         PJd KKKKr   r   )*osr8   rQ   rx   jsonr   ior   _versionr   pathabspathdirname__file__HEREopenrz   fidloadr   r   r   	NameError	comm_pathfread
nb_mime_jsr   r   PYVIZ_PROXYABORT_JSbokeh_msg_handlerJS_CALLBACKlistr6   ParameterizedrE   r   r   objectr   r   r   r   r   <module>r      s   				 



      !!!!!!!  ! ! ! ! ! !	wrwx0011	T"',,t^^
<
<== 49S>>D                +----   +++ GOOBGOOH5566		T"',,y-
0
011 #Q!&&(("J# # # # # # # # # # # # # # #/" /" /" /" /"+ /" /" /"d6 @Pf" " " " "T " " "*p" p" p" p" p"5 p" p" p"f:A :A :A :A :A$ :A :A :Az9A 9A 9A 9A 9AK 9A 9A 9Az# # # # #& # # #Nb  b  b  b  b  b  b  b  b  b s>    'B((B,/B,7
C CC%E		EE