U
    /ePZ                     @  sz  d Z ddlmZ ddlZee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 ddlmZ dd	lmZmZ dd
lmZ ddlmZmZmZm Z  ddl!m"Z" ddl#m$Z% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2 erXddlm3Z3 ddl4m5Z5 ddlm6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z= ddl&m>Z> dZ?eG dd dee/e(e'Z@dS )z` Provide a base class for all objects (called Bokeh Models) that can go in
a Bokeh |Document|.

    )annotationsN)isclass)loads)TYPE_CHECKINGAnyClassVarDictIterableListSetType   )
properties)HasPropsabstract)serialize_json)IDRefReferenceJsonUnknown)Event)default)EventCallbackManagerPropertyCallbackManager)make_id   )	html_reprprocess_example)HasDocumentRefcollect_modelsqualified_model(visit_value_and_its_immediate_references)Setter)SelectorType)JSON)Document)DocumentPatchedEvent)Callback)PropertyCallback)Modelc                      sr  e Zd ZU dZi Zded< e fddZded< d d fd	d
Zddd fddZ	ddddZ
e
ZddddZeddddZejejddZded< ejejddZded< ejejeedddZejejd dZejejeedd!dZejd"d#d$Zd%ed&< ed'dd(d)Zed*dd+d,Zd-d.dd/d0d1Zdidd dd3dd4d5d6Z dd.dd/d7d8Z!dd9dd: fd;d<Z"d=dd>d?Z#d@dAdBdCdDZ$d@dEdBdFdGZ%dHdIddJdKdLZ&d%dMdNdOdPZ'd%ddNdQdRZ(djddSdSdTdUddV fdWdXZ)dYddZd[d\Z*eddd]d^Z+ddd_d`Z,d%dadbdcZ-dddddeZ.dfddgdhZ/  Z0S )kr)   zH Base class for all objects stored in Bokeh  |Document| instances.

    z ClassVar[Dict[str, Type[Model]]]model_class_reverse_mapc                   s   t    d| jkr| j| _d| jkr.| j| _t| }|| _| j	
|d }|d k	rpt| dsptd| d| | | j	|< t|  d S )N__view_model____view_module____implementation__z*Duplicate qualified model declaration of 'z'. Previous definition: )super__init_subclass____dict____name__r+   
__module__r,   r    __qualified_model__r*   gethasattrWarningr   )clsZ	qualifiedprevious	__class__ 5/tmp/pip-unpacked-wheel-f5fndrjf/bokeh/model/model.pyr/   \   s    



zModel.__init_subclass__r   _id)returnc                   s    t  | }|dt |_|S Nid)r.   __new__popr   r=   )r7   argskwargsobjr9   r;   r<   rA   t   s    zModel.__new__r   None)rD   r>   c                   s(   | dd  t jf | t|  d S r?   )rB   r.   __init__default_themeapply_to_model)selfrD   r9   r;   r<   rG   y   s    zModel.__init__strc                 C  s   | j j}| d| jdS )Nz(id=z, ...))r:   r1   r@   )rJ   namer;   r;   r<   __str__   s    zModel.__str__c                 C  s   d| _ d| _| j  dS )z; Clean up references to the document and property

        N)	_documentZ_temp_documentZ_property_valuesclearrJ   r;   r;   r<   destroy   s    zModel.destroyc                 C  s   | j S N)r=   rP   r;   r;   r<   r@      s    zModel.ida  
    An arbitrary, user-supplied name for this model.

    This name can be useful when querying the document to retrieve specific
    Bokeh models.

    .. code:: python

        >>> plot.circle([1,2,3], [4,5,6], name="temp")
        >>> plot.select(name="temp")
        [GlyphRenderer(id='399d53f5-73e9-44d9-9527-544b761c7705', ...)]

    .. note::
        No uniqueness guarantees or other conditions are enforced on any names
        that are provided, nor is the name used directly by Bokeh for any
        reason.

    )helpz
str | NonerL   a  
    An optional list of arbitrary, user-supplied values to attach to this
    model.

    This data can be useful when querying the document to retrieve specific
    Bokeh models:

    .. code:: python

        >>> r = plot.circle([1,2,3], [4,5,6])
        >>> r.tags = ["foo", 10]
        >>> plot.select(tags=['foo', 10])
        [GlyphRenderer(id='1de4c3df-a83d-480a-899b-fb263d3d5dd9', ...)]

    Or simply a convenient way to attach any necessary metadata to a model
    that can be accessed by ``CustomJS`` callbacks, etc.

    .. note::
        No uniqueness guarantees or other conditions are enforced on any tags
        that are provided, nor are the tags used directly by Bokeh for any
        reason.

    z	List[Any]tagszbokeh.models.callbacks.CustomJSaQ  
    A mapping of event names to lists of ``CustomJS`` callbacks.

    Typically, rather then modifying this property directly, callbacks should be
    added using the ``Model.js_on_event`` method:

    .. code:: python

        callback = CustomJS(code="console.log('tap event occurred')")
        plot.js_on_event('tap', callback)
    z
    List of events that are subscribed to by Python callbacks. This is
    the set of events that will be communicated from BokehJS back to
    Python for this model.
    a  
    A mapping of attribute names to lists of ``CustomJS`` callbacks, to be set up on
    BokehJS side when the document is created.

    Typically, rather then modifying this property directly, callbacks should be
    added using the ``Model.js_on_change`` method:

    .. code:: python

        callback = CustomJS(code="console.log('stuff')")
        plot.x_range.js_on_change('start', callback)

    Ta  
    Indicates whether this model should be synchronized back to a Bokeh server when
    updated in a web browser. Setting to ``False`` may be useful to reduce network
    traffic when dealing with frequently updated objects whose updated values we
    don't need.

    .. note::
        Setting this property to ``False`` will prevent any ``on_change()`` callbacks
        on this object from triggering. However, any JS-side callbacks will still
        work.

    )r   rS   boolsyncabler   c                 C  s   t | jdS )N)r@   )r   r=   rP   r;   r;   r<   ref   s    z	Model.refr   c                 C  sR   t | j| ji d}d| jjkrN|d d}| j|d< d||d< | j|d< |S )a;   A Bokeh protocol "structure" of this model, i.e. a dict of the form:

        .. code-block:: python

            {
                'type' : << view model name >>
                'id'   : << unique model id >>
            }

        Additionally there may be a `subtype` field if this model is a subtype.

        )r@   type
attributes__subtype__rX   .subtype)	r   r@   r3   r:   r0   splitr+   joinrZ   )rJ   thispartsr;   r;   r<   struct   s    

zModel.structzstr | Type[Event]JSEventCallback)event	callbacksr>   c                 G  sr   t |trn*t |tr(t|tr(|j}ntd| t| j	|g }|D ]}||krL|
| qL|| j|< d S )Nz/expected string event name or event class, got )
isinstancerK   rX   
issubclassr   Z
event_name
ValueErrorlistjs_event_callbacksr4   append)rJ   rd   re   Zall_callbackscallbackr;   r;   r<   js_on_event  s    
zModel.js_on_eventNzint | str | None)attrother
other_attrattr_selectorr>   c           
      C  s   | j |dd}|dkr&td|| f t|ts<td| |j |dd}|dkrbtd||f ddlm} |dk	rd	|d
nd}|t|dd|j d|j | d}	| ||	 dS )a   Link two Bokeh model properties using JavaScript.

        This is a convenience method that simplifies adding a CustomJS callback
        to update one Bokeh model property whenever another changes value.

        Args:

            attr (str) :
                The name of a Bokeh property on this model

            other (Model):
                A Bokeh model to link to self.attr

            other_attr (str) :
                The property on ``other`` to link together

            attr_selector (Union[int, str]) :
                The index to link an item in a subscriptable ``attr``

        Added in version 1.1

        Raises:

            ValueError

        Examples:

            This code with ``js_link``:

            .. code :: python

                select.js_link('value', plot, 'sizing_mode')

            is equivalent to the following:

            .. code:: python

                from bokeh.models import CustomJS
                select.js_on_change('value',
                    CustomJS(args=dict(other=plot),
                             code="other.sizing_mode = this.value"
                    )
                )

            Additionally, to use attr_selector to attach the left side of a range slider to a plot's x_range:

            .. code :: python

                range_slider.js_link('value', plot.x_range, 'start', attr_selector=0)

            which is equivalent to:

            .. code :: python

                from bokeh.models import CustomJS
                range_slider.js_on_change('value',
                    CustomJS(args=dict(other=plot.x_range),
                             code="other.start = this.value[0]"
                    )
                )

        FZraisesNz!%r is not a property of self (%r)z 'other' is not a Bokeh model: %rz"%r is not a property of other (%r)r   CustomJS[] )ro   zother.z = this.)rC   code)	lookuprh   rf   r)   bokeh.modelsrt   dictrL   js_on_change)
rJ   rn   ro   rp   rq   
descriptorZother_descriptorrt   selectorcbr;   r;   r<   js_link#  s    ?
&zModel.js_linkc                   s   t |dkrtdddlm  t fdd|D s>td| j|dd}|d	k	r`d
|j }dd | j D }|| jkrg | j|< |D ]$}|| j| krq| j| 	| q| 
d|| j d	S )a   Attach a ``CustomJS`` callback to an arbitrary BokehJS model event.

        On the BokehJS side, change events for model properties have the
        form ``"change:property_name"``. As a convenience, if the event name
        passed to this method is also the name of a property on the model,
        then it will be prefixed with ``"change:"`` automatically:

        .. code:: python

            # these two are equivalent
            source.js_on_change('data', callback)
            source.js_on_change('change:data', callback)

        However, there are other kinds of events that can be useful to respond
        to, in addition to property change events. For example to run a
        callback whenever data is streamed to a ``ColumnDataSource``, use the
        ``"stream"`` event on the source:

        .. code:: python

            source.js_on_change('streaming', callback)

        r   zRjs_on_change takes an event name and one or more callbacks, got only one parameterrs   c                 3  s   | ]}t | V  qd S rR   )rf   ).0xrs   r;   r<   	<genexpr>  s     z%Model.js_on_change.<locals>.<genexpr>z.not all callback values are CustomJS instancesFrr   Nzchange:c                 S  s    i | ]\}}|d d |D qS )c                 S  s   g | ]}|qS r;   r;   )r   r   r;   r;   r<   
<listcomp>  s     z1Model.js_on_change.<locals>.<dictcomp>.<listcomp>r;   )r   kZcbsr;   r;   r<   
<dictcomp>  s      z&Model.js_on_change.<locals>.<dictcomp>js_property_callbacks)lenrh   rz   rt   allry   rL   r   itemsrk   trigger)rJ   rd   re   r}   oldrl   r;   rs   r<   r|   t  s     

zModel.js_on_changer(   )rn   re   r>   c                   s"   |  |}t j|jf|  dS )ay   Add a callback on this object to trigger when ``attr`` changes.

        Args:
            attr (str) : an attribute name on this object
            *callbacks (callable) : callback functions to register

        Returns:
            None

        Example:

        .. code-block:: python

            widget.on_change('value', callback1, callback2, ..., callback_n)

        N)ry   r.   	on_changerL   )rJ   rn   re   r}   r9   r;   r<   r     s    
zModel.on_changez
Set[Model]c                 C  s   t t| S )zE Returns all ``Models`` that this object has references to.

        )setr   rP   r;   r;   r<   
references  s    zModel.referencesr#   zIterable[Model])r~   r>   c                 C  s   ddl m} ||  |S )z Query this object and all of its references for objects that
        match the given selector.

        Args:
            selector (JSON-like) :

        Returns:
            seq[Model]

        r   )find)
core.queryr   r   )rJ   r~   r   r;   r;   r<   select  s    zModel.selectzModel | Nonec                 C  sB   t | |}t|dkr*td||f t|dkr:dS |d S )a5   Query this object and all of its references for objects that
        match the given selector.  Raises an error if more than one object
        is found.  Returns single matching object, or None if nothing is found
        Args:
            selector (JSON-like) :

        Returns:
            Model
        r   z*Found more than one object matching %s: %rr   N)ri   r   r   rh   )rJ   r~   resultr;   r;   r<   
select_one  s    
zModel.select_onezType[Model] | SelectorTypezDict[str, Unknown])r~   updatesr>   c                 C  sN   t |rt|trt|d}| |D ]"}| D ]\}}t||| q2q&dS )z Update objects that match a given selector with the specified
        attribute/value updates.

        Args:
            selector (JSON-like) :
            updates (dict) :

        Returns:
            None

        )rX   N)r   rg   r)   r{   r   r   setattr)rJ   r~   r   rE   keyvalr;   r;   r<   
set_select  s
    
zModel.set_selectr$   )include_defaultsr>   c                 C  s   t | j|dS )a   Returns a dictionary of the attributes of this object,
        containing only "JSON types" (string, number, boolean,
        none, dict, list).

        References to other objects are serialized as "refs" (just
        the object ID and type info), so the deserializer will
        need to separately have the full attributes of those
        other objects.

        There's no corresponding ``from_json()`` because to
        deserialize an object is normally done in the context of a
        Document (since the Document can resolve references).

        For most purposes it's best to serialize and deserialize
        entire documents.

        Args:
            include_defaults (bool) : whether to include attributes
                that haven't been changed from the default

        r   )r   to_json_string)rJ   r   r;   r;   r<   to_json  s    zModel.to_jsonc                 C  s   | j |d}| j|d< t|S )a   Returns a JSON string encoding the attributes of this object.

        References to other objects are serialized as references
        (just the object ID and type info), so the deserializer
        will need to separately have the full attributes of those
        other objects.

        There's no corresponding ``from_json_string()`` because to
        deserialize an object is normally done in the context of a
        Document (since the Document can resolve references).

        For most purposes it's best to serialize and deserialize
        entire documents.

        Args:
            include_defaults (bool) : whether to include attributes
                that haven't been changed from the default

        r   r@   )_to_json_liker@   r   )rJ   r   Z	json_liker;   r;   r<   r     s    
zModel.to_json_stringr   zDocumentPatchedEvent | NonezSetter | None)rn   r   newhintsetterr>   c                   sv   |dkrPd dd fdd}| j dk	rPt|| t||  dkrP| jj  | |}t j|j||||d dS )z


        Nr   r   _c                   s    d7  d S )Nr   r;   r   Zdirty_countr;   r<   
mark_dirty-  s    z!Model.trigger.<locals>.mark_dirty)r   r   )	rN   r!   documentmodelsZ
invalidatery   r.   r   rL   )rJ   rn   r   r   r   r   r   r}   r9   r   r<   r     s    



zModel.triggerr%   )docr>   c                 C  sF   | j |krdS | j dk	r(td| d|j|  || _ |   dS )z Attach a model to a Bokeh |Document|.

        This private interface should only ever called by the Document
        implementation to set the private ._document field properly

        Nz0Models must be owned by only a single document, z is already in a doc)r   RuntimeErrorZthemerI   Z_update_event_callbacks)rJ   r   r;   r;   r<   _attach_document9  s    

zModel._attach_documentc                 C  s   dd | j  D | _ d S )Nc                 S  sF   i | ]>\}}t |d ddkrt |dddkrt |dddkr||qS )r-   NZ__javascript__Z__css__)getattr)r   r   vr;   r;   r<   r   L  s    z+Model._clear_extensions.<locals>.<dictcomp>)r*   r   )r7   r;   r;   r<   _clear_extensionsJ  s    zModel._clear_extensionsc                 C  s   d| _ t|  dS )z Detach a model from a Bokeh |Document|.

        This private interface should only ever called by the Document
        implementation to unset the private ._document field properly

        N)r   rH   rI   rP   r;   r;   r<   _detach_documentS  s    zModel._detach_documentr   c           	      C  s   | j |d}t| jdd}|dk	r^|| jjkr^i }| D ] \}}|| jjkrRq:q:|||< q:n|}| D ]&\}}t|trj|tdkrjd||< qj|S )a   Returns a dictionary of the attributes of this object, in
        a layout corresponding to what BokehJS expects at unmarshalling time.

        This method does not convert "Bokeh types" into "plain JSON types,"
        for example each child Model will still be a Model, rather
        than turning into a reference, numpy isn't handled, etc.
        That's what "json like" means.

        This method should be considered "private" or "protected",
        for use internal to Bokeh; use ``to_json()`` instead because
        it gives you only plain JSON-compatible types.

        Args:
            include_defaults (bool) : whether to include attributes
                that haven't been changed from the default.

        r   rZ   Ninf)Zproperties_with_valuesr   r:   r+   r   r0   rf   float)	rJ   r   Z	all_attrsr]   attrsrn   valuer   r   r;   r;   r<   r   ]  s    
zModel._to_json_likec                 C  s   t | S rR   )r   rP   r;   r;   r<   _repr_html_  s    zModel._repr_html_z
int | Nonec                 C  s   d S rR   r;   rP   r;   r;   r<   _sphinx_height_hint  s    zModel._sphinx_height_hint)N)NN)1r1   r2   __qualname____doc__r*   __annotations__classmethodr/   rA   rG   rM   __repr__rQ   propertyr@   pZNullableStringrL   r
   ZAnyRefrT   r   ZInstancerj   Zsubscribed_eventsr   ZBoolrV   rW   rb   rm   r   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r;   r;   r9   r<   r)   T   sX   

Q-   
-r)   )Ar   
__future__r   logging	getLoggerr1   loginspectr   jsonr   typingr   r   r   r   r	   r
   r   r   corer   r   Zcore.has_propsr   r   Zcore.json_encoderr   Z
core.typesr   r   r   r   eventsr   Zthemesr   rH   Zutil.callback_managerr   r   Zutil.serializationr   Zdocsr   r   utilr   r   r    r!   r"   r   r#   r$   r   r%   Zdocument.eventsr&   Zmodels.callbacksr'   rc   r(   __all__r)   r;   r;   r;   r<   <module>   s6   
(