U
    /eg                     @  s4  d Z ddlmZ ddlZeeZddl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 ddlmZ ddlmZmZ e	redede
f d	Zd
ddddZn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( ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0 e	rbddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: dZ;e	rxee2e6f Z<eded  d	Z=ddd!d"d#Z>d$d%d!d&d'Z?d(d)d*d+d,Z@d(d-d.d/ZAG d0d1 d1eBZCG d2d  d eCd3ZDe
ZEG d4d5 d5eZFG d6d7 d7eZGG d8d9 d9eZHG d:d; d;eHZId<ZJdS )=a   Provide a base class for objects that can have declarative, typed,
serializable properties.

.. note::
    These classes form part of the very low-level machinery that implements
    the Bokeh model and property system. It is unlikely that any of these
    classes or their methods will be applicable to any standard usage or to
    anyone who is not directly developing on Bokeh's own infrastructure.

    )annotationsN)TYPE_CHECKINGAnyCallableDictIterableListMappingNoReturnSetTupleTypeTypeVarUnionoverload)warn)Literal	TypedDictF.)boundz
int | NonezCallable[[F], F])argreturnc                 C  s   d S N )r   r   r   8/tmp/pip-unpacked-wheel-f5fndrjf/bokeh/core/has_props.py	lru_cache7       r   )r      )append_docstring	nice_join   )PropertyDescriptorFactory)PropertyDescriptorUnsetValueError)Override)	Undefined)PropertyValueContainer)IDJSONUnknown)ClientSession)StaticSerializer)ServerSession)PropertyDataSpec)abstractHasPropsMetaHasPropsCr1   )clsr   c                 C  s,   t | tst| j dt| jt| _| S )zI A decorator to mark abstract base classes derived from |HasProps|.

    z is not a subclass of HasProps)
issubclassr1   	TypeError__name__r   __doc___ABSTRACT_ADMONITIONr4   r   r   r   r0   b   s    
r0   zType[HasProps]boolc                 C  s*   ddl m} t| to(t| ddo(| |kS )Nr   )	DataModelZ__data_model__F)modelr<   r5   r1   getattr)r4   r<   r   r   r   is_DataModelk   s    r?   Dict[str, Any]Dict[str, Unknown])
class_dictr   c                 C  s>   i }t |  D ](\}}t|tr| |= |jr|j||< q|S r   )tupleitems
isinstancer$   Zdefault_overriddendefault)rB   overridden_defaultsnamepropr   r   r   _overridden_defaultso   s    
rJ   )rB   c                 C  s6   i }t |  D ] \}}t|tr| |= |||< q|S r   )rC   rD   rE   r!   )rB   
generatorsrH   	generatorr   r   r   _generatorsx   s    

rM   c                      sV   e Zd ZU dZded< ded< ded< ddd	d
 fddZddddddZ  ZS )r2   aY   Specialize the construction of |HasProps| classes.

    This class is a `metaclass`_ for |HasProps| that is responsible for
    creating and adding the |PropertyDescriptor| instances that delegate
    validation and serialization to |Property| attributes.

    .. _metaclass: https://docs.python.org/3/reference/datamodel.html#metaclasses

    Dict[str, Property[Any]]__properties__rA   __overridden_defaults____themed_values__strzTuple[type, ...]r@   )
class_namebasesrB   c                   s   t |}t|}i }| D ]P\}}||}	|	D ]8}
|
j}||krXtd| d| |
||< |
j||< q2q||d< ||d< t | |||S )


        z%Two property generators both created .rO   rP   )	rJ   rM   rD   Zmake_descriptorsrH   RuntimeErrorpropertysuper__new__)r4   rS   rT   rB   rG   rK   
propertiesrH   rL   Zdescriptors
descriptor	__class__r   r   rZ      s    
zMetaHasProps.__new__None)rS   rT   r   c           	      C  s   i }dd |D D ]}| |jdd qdd | j D }| | @ }|rptd|d| j d	td
d | j | jdd  }|rtd| d| j dtd
d d S )Nc                 s  s   | ]}t |tr|V  qd S r   )r5   r1   ).0xr   r   r   	<genexpr>   s     
 z(MetaHasProps.__init__.<locals>.<genexpr>T_with_propsc                 S  s    i | ]\}}t |tr||qS r   )rE   r"   r`   kvr   r   r   
<dictcomp>   s     
  z)MetaHasProps.__init__.<locals>.<dictcomp>zProperties z
 in class z were previously declared on a parent class. It never makes sense to do this. Redundant properties should be deleted here, or onthe parent class. Override() can be used to change a default value of a base class property.r   )
stacklevelzOverrides of z does not override anything.)	updater[   __dict__rD   keysr   r7   RuntimeWarningrP   )	r4   rS   rT   _Zbase_propertiesbaseZown_propertiesZ
redeclaredZunused_overridesr   r   r   __init__   s     zMetaHasProps.__init__)r7   
__module____qualname__r8   __annotations__rZ   rp   __classcell__r   r   r]   r   r2      s   

r2   c                      s  e Zd ZU dZdZded< ded< ded< ded< d	d
d fddZddd
d fddZddd fddZddddddZ	ddddZ
e
Zd dddd Zded!< ded"< ed#d$d%d&d'Zd	d	d%d(d)Zd*d*d+dd,d-d.d
d/d0d1Zd	d
d2d3d4Zd*d*d+d5d6d.d
d7d8d9Zeed:d;dd<d=d>d?d@Zeedd;ddAdBd>dCd@Zed:d;dddBd>dDd@Zeeed*ddEdAdFdGdHdIZeeed*d:dEd<dJdGdKdIZeed*ddEddLdGdMdIZeed*dJddNdOZeed*dPddQdRZd:ddSddddTdUdVZedddWdXZd:ddSdYddddZd[d\Zd]dd^d_Zdd
d`dadbZd
ddcddZd ddedfZ  Z S )gr1   zX Base class for all class types that have Bokeh properties.

    .. autoclasstoc::

    Fr;   _initializedrA   _property_values_unstable_default_values_unstable_themed_valuesr   r_   )r[   r   c                   sD   t    i | _i | _i | _| D ]\}}t| || q$d| _dS )rU   TN)rY   rp   rv   rw   rx   rD   setattrru   )selfr[   rH   valuer]   r   r   rp      s    
zHasProps.__init__rR   r)   )rH   r{   r   c                   sp   | drt ||S | jdd}||kr:t ||S t| j|d}t|tr`t ||S | || dS a   Intercept attribute setting on HasProps in order to special case
        a few situations:

        * short circuit all property machinery for ``_private`` attributes
        * suggest similar attribute names on attribute errors

        Args:
            name (str) : the name of the attribute to set on this object
            value (obj) : the value to set

        Returns:
            None

        rn   Trc   N)	
startswithrY   __setattr__r[   r>   r^   rE   rX   #_raise_attribute_error_with_matches)rz   rH   r{   r[   r\   r]   r   r   r~      s    

zHasProps.__setattr__)rH   r   c                   sj   | drt |S | jdd}||kr6t |S t| j|d}t|trZt |S | || dS r|   )	r}   rY   __getattr__r[   r>   r^   rE   rX   r   )rz   rH   r[   r\   r]   r   r   r      s    

zHasProps.__getattr__zIterable[str]r
   )rH   r[   r   c              
   C  sT   t | |d }}|s(t|d }}td|d| jj d| dt| d S )NZsimilarpossiblezunexpected attribute z to z, z attributes are )difflibget_close_matcheslowersortedAttributeErrorr^   r7   r   )rz   rH   r[   matchestextr   r   r   r   
  s    z,HasProps._raise_attribute_error_with_matches)r   c                 C  s   | j j}| dS )Nz(...))r^   r7   )rz   rH   r   r   r   __str__  s    zHasProps.__str__)otherr   c                 C  s$   t || jsdS |  | kS dS )z Structural equality of models.

        Args:
            other (HasProps) : the other instance to compare to

        Returns:
            True, if properties are structurally equal, otherwise False

        FN)rE   r^   properties_with_values)rz   r   r   r   r   equals   s    
zHasProps.equals__view_model____view_module__r+   ModelRef)
serializerr   c                 C  s   | | }|d k	r|S dd | jD }t|dkr8d }n$t|dkrT|d |}ntd| j}| j}|dks|dd dkrd }g }g }| jD ].}	| 	|	}
d }|
j
j}|t|	||d	 qt| d
i  D ]\}	}|t|	|d qt|||||d}t||d}|| || |S )Nc                 S  s   g | ]}t |r|qS r   )r?   )r`   Zbaseclsr   r   r   
<listcomp>;  s      z3HasProps.static_to_serializable.<locals>.<listcomp>r   r    z multiple bases are not supported__main__rV   Zbokeh)rH   kindrF   rP   )rH   rF   )rH   moduleextendsr[   	overrides)rH   r   )Zget_ref	__bases__lenstatic_to_serializablerW   r   r   splitrO   lookuprX   _defaultappendPropertyDefr>   rD   OverrideDefModelDefr   Zadd_ref)r4   r   ZmodelrefrT   r   rH   r   r[   r   Z	prop_namer\   r   rF   Zmodeldefr   r   r   r   4  s4    


zHasProps.static_to_serializablec                 C  s   d S r   r   )rz   r   r   r   r   to_serializable]  s    zHasProps.to_serializableNmodelssetterr(   zDict[ID, HasProps] | NonezSetter | None)rH   jsonr   r   r   c                C  s\   || j ddkrJtd|d| d| | |}|j| |||d ntd||  dS )	a   Set a property value on this object from JSON.

        Args:
            name: (str) : name of the attribute to set

            json: (JSON-value) : value to set to the attribute to

            models (dict or None, optional) :
                Mapping of model ids to models (default: None)

                This is needed in cases where the attributes to update also
                have values that have references.

            setter(ClientSession or ServerSession or None, optional) :
                This is used to prevent "boomerang" updates to Bokeh apps.

                In the context of a Bokeh server application, incoming updates
                to properties will be annotated with the session that is
                doing the updating. This value is propagated through any
                subsequent change notifications that the update triggers.
                The session can compare the event setter to itself, and
                suppress any updates that originate from itself.

        Returns:
            None

        Trc   zPatching attribute z of z with r   zeJSON had attr %r on obj %r, which is a client-only or invalid attribute that shouldn't have been sentN)r[   logtracer   set_from_jsonwarning)rz   rH   r   r   r   r\   r   r   r   r   `  s
    
zHasProps.set_from_json)kwargsr   c                 K  s"   |  D ]\}}t| || qdS )a   Updates the object's properties from the given keyword arguments.

        Returns:
            None

        Examples:

            The following are equivalent:

            .. code-block:: python

                from bokeh.models import Range1d

                r = Range1d

                # set properties individually:
                r.start = 10
                r.end = 20

                # update properties together:
                r.update(start=10, end=20)

        N)rD   ry   )rz   r   rf   rg   r   r   r   rj     s    zHasProps.updatezDict[str, JSON]zMapping[ID, HasProps] | None)json_attributesr   r   r   c                C  s(   |  D ]\}}| j||||d qdS )a   Updates the object's properties from a JSON attributes dictionary.

        Args:
            json_attributes: (JSON-dict) : attributes and values to update

            models (dict or None, optional) :
                Mapping of model ids to models (default: None)

                This is needed in cases where the attributes to update also
                have values that have references.

            setter(ClientSession or ServerSession or None, optional) :
                This is used to prevent "boomerang" updates to Bokeh apps.

                In the context of a Bokeh server application, incoming updates
                to properties will be annotated with the session that is
                doing the updating. This value is propagated through any
                subsequent change notifications that the update triggers.
                The session can compare the event setter to itself, and
                suppress any updates that originate from itself.

        Returns:
            None

        r   N)rD   r   )rz   r   r   r   rf   rg   r   r   r   update_from_json  s    zHasProps.update_from_jsonT)raiseszLiteral[True]zPropertyDescriptor[Any])rH   r   r   c                C  s   d S r   r   r4   rH   r   r   r   r   r     s    zHasProps.lookupzLiteral[False]zPropertyDescriptor[Any] | Nonec                C  s   d S r   r   r   r   r   r   r     s    c                C  s>   t | |d}|dk	s |dkr$|s$|S t| j d| ddS )aX   Find the ``PropertyDescriptor`` for a Bokeh property on a class,
        given the property name.

        Args:
            name (str) : name of the property to search for
            raises (bool) : whether to raise or return None if missing

        Returns:
            PropertyDescriptor : descriptor for property named ``name``

        NrV   z# property descriptor does not exist)r>   r   r7   )r4   rH   r   attrr   r   r   r     s    rc   zSet[str])rd   r   c                C  s   d S r   r   r4   rd   r   r   r   r[     s    zHasProps.propertiesrN   c                C  s   d S r   r   r   r   r   r   r[     s    z)Union[Set[str], Dict[str, Property[Any]]]c                C  s2   i }| j D ]}|t|di  q
|s.t|S |S )ae   Collect the names of properties on this class.

        .. warning::
            In a future version of Bokeh, this method will return a dictionary
            mapping property names to property objects. To future-proof this
            current usage of this method, wrap the return value in ``list``.

        Returns:
            property names

        rO   )__mro__rj   r>   set)r4   rd   propscr   r   r   r[     s    
c                 C  s   dd | j dd D S )a,   Collect the names of all properties on this class that also have
        references.

        This method *always* traverses the class hierarchy and includes
        properties defined on any parent classes.

        Returns:
            set[str] : names of properties that have references

        c                 S  s   i | ]\}}|j r||qS r   )Zhas_refre   r   r   r   rh     s       z1HasProps.properties_with_refs.<locals>.<dictcomp>Trc   )r[   rD   r:   r   r   r   properties_with_refs  s    zHasProps.properties_with_refszDict[str, DataSpec]c                   s*   ddl m   fdd| jdd D S )a   Collect the names of all ``DataSpec`` properties on this class.

        This method *always* traverses the class hierarchy and includes
        properties defined on any parent classes.

        Returns:
            set[str] : names of ``DataSpec`` properties

        r    r.   c                   s    i | ]\}}t | r||qS r   )rE   re   r.   r   r   rh     s     
  z&HasProps.dataspecs.<locals>.<dictcomp>Trc   )property.dataspecr/   r[   rD   r:   r   r.   r   	dataspecs  s    zHasProps.dataspecsinclude_defaultsinclude_undefined)r   r   r   c                C  s   | j dd ||dS )a#   Collect a dict mapping property names to their values.

        This method *always* traverses the class hierarchy and includes
        properties defined on any parent classes.

        Non-serializable properties are skipped and property values are in
        "serialized" format which may be slightly different from the values
        you would normally read from the properties; the intent of this method
        is to return the information needed to losslessly reconstitute the
        object instance.

        Args:
            include_defaults (bool, optional) :
                Whether to include properties that haven't been explicitly set
                since the object was created. (default: True)

        Returns:
           dict : mapping from property names to their values

        c                 S  s   | j S r   )Z
serialized)rI   r   r   r   <lambda>+  r   z1HasProps.properties_with_values.<locals>.<lambda>r   )query_properties_with_values)rz   r   r   r   r   r   r     s    
 zHasProps.properties_with_valuesc                 C  s*   i }t | jD ]}|t|di  q|S )z Returns a dictionary of defaults that have been overridden.

        .. note::
            This is an implementation detail of ``Property``.

        rP   )reversedr   rj   r>   )r4   defaultsr   r   r   r   rJ   .  s    zHasProps._overridden_defaultsz)Callable[[PropertyDescriptor[Any]], bool])queryr   r   r   c             	   C  s   t  }i }|r| jdd}n@t | j t | j B }|  }|dk	r\t | }||O }|D ]t}| |}	||	sxq`z|	| }
W n" tk
r   |rt	}
nY q`Y n$X |s||krt
|
tr|| jkrq`|
||< q`|S )a   Query the properties values of |HasProps| instances with a
        predicate.

        Args:
            query (callable) :
                A callable that accepts property descriptors and returns True
                or False

            include_defaults (bool, optional) :
                Whether to include properties that have not been explicitly
                set by a user (default: True)

        Returns:
            dict : mapping of property names and values for matching properties

        Trc   N)r   r[   rv   rl   rw   themed_valuesr   Zserializable_valuer#   r%   rE   r&   )rz   r   r   r   Zthemed_keysresultrl   r   keyr\   r{   r   r   r   r   ;  s0    


z%HasProps.query_properties_with_valueszDict[str, Unknown] | Nonec                 C  s   t | ddS )z Get any theme-provided overrides.

        Results are returned as a dict from property name to value, or
        ``None`` if no theme overrides any values for this instance.

        Returns:
            dict or None

        rQ   N)r>   rz   r   r   r   r   r  s    
zHasProps.themed_values)property_valuesr   c           	      C  s   |   }||krdS t }|dk	r4|t|  t| }i }||D ]}t| |||< qNt|dkr|t| d| nt| drt	| d |
 D ]\}}|| jkr| j|= q|
 D ](\}}| |}t|tr|| | qdS )a   Apply a set of theme values which will be used rather than
        defaults, but will not override application-set values.

        The passed-in dictionary may be kept around as-is and shared with
        other instances to save memory (so neither the caller nor the
        |HasProps| instance should modify it).

        Args:
            property_values (dict) : theme values to use in place of defaults

        Returns:
            None

        Nr   rQ   )r   r   rj   rl   unionr>   r   ry   hasattrdelattrrD   rx   r   rE   r"   Ztrigger_if_changed)	rz   r   Zold_dictremovedaddedZ
old_valuesrf   rg   r\   r   r   r   apply_theme~  s*    





zHasProps.apply_themec                 C  s   | j i d dS )z\ Remove any themed values and restore defaults.

        Returns:
            None

        )r   N)r   r   r   r   r   unapply_theme  s    zHasProps.unapply_themec                 C  s   | j f | jS )z_ Duplicate a HasProps object.

        Values that are containers are shallow-copied.

        )r^   rv   r   r   r   r   _clone  s    zHasProps._clone)!r7   rq   rr   r8   ru   rs   rp   r~   r   r   r   __repr__r   classmethodr   r   r   rj   r   r   r   r   r[   r   r   r   rJ   r   r   r   r   r   rt   r   r   r]   r   r1      sv   

( $  70	)	metaclassc                   @  s&   e Zd ZU ded< ded< ded< dS )r   rR   rH   zKindRef | Noner   zUnknown | NonerF   Nr7   rq   rr   rs   r   r   r   r   r     s   
r   c                   @  s   e Zd ZU ded< ded< dS )r   rR   rH   r)   rF   Nr   r   r   r   r   r     s   
r   c                   @  s   e Zd ZU ded< ded< dS )r   rR   rH   z
str | Noner   Nr   r   r   r   r   r     s   
r   c                   @  s&   e Zd ZU ded< ded< ded< dS )r   zModelRef | Noner   zList[PropertyDef] | Noner[   zList[OverrideDef] | Noner   Nr   r   r   r   r   r     s   
r   z
    .. note::
        This is an abstract base class used to help organize the hierarchy of Bokeh
        model types. **It is not useful to instantiate on its own.**

)Kr8   
__future__r   logging	getLoggerr7   r   r   typingr   r   r   r   r   r   r	   r
   r   r   r   r   r   r   warningsr   Ztyping_extensionsr   r   r   r   	functoolsZutil.stringr   r   Zproperty.descriptor_factoryr!   Zproperty.descriptorsr"   r#   Zproperty.overrider$   Zproperty.singletonsr%   Zproperty.wrappersr&   typesr'   r(   r)   Zclient.sessionr*   Zdocument.documentr+   Zserver.sessionr,   Zproperty.basesr-   r   r/   __all__ZSetterr3   r0   r?   rJ   rM   typer2   r1   ZKindRefr   r   r   r   r9   r   r   r   r   <module>   sX   
@		8    	