#-----------------------------------------------------------------------------# Copyright (c) Anaconda, Inc., and Bokeh Contributors.# All rights reserved.## The full license is in the file LICENSE.txt, distributed with this software.#-----------------------------------------------------------------------------""" Provide properties for various visual attributes."""#-----------------------------------------------------------------------------# Boilerplate#-----------------------------------------------------------------------------from__future__importannotationsimportlogging# isort:skiplog=logging.getLogger(__name__)#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------# Standard library importsimportbase64importdatetime# lgtm [py/import-and-import-from]importreimporttempfilefromioimportBytesIOfrompathlibimportPathfromtypingimportAny,BinaryIO# Bokeh importsfrom...util.serializationimportconvert_datetime_typefrom..importenumsfrom.autoimportAutofrom.basesimportPropertyfrom.containerimportSeq,Tuplefrom.datetimeimportDatetime,TimeDeltafrom.eitherimportEitherfrom.enumimportEnumfrom.nullableimportNullablefrom.numericimportFloat,Intfrom.primitiveimportStringfrom.stringimportRegex#-----------------------------------------------------------------------------# Globals and constants#-----------------------------------------------------------------------------__all__=('DashPattern','FontSize','HatchPatternType','Image','MinMaxBounds','MarkerType',)#-----------------------------------------------------------------------------# General API#-----------------------------------------------------------------------------
[docs]classDashPattern(Either):""" Accept line dash specifications. Express patterns that describe line dashes. ``DashPattern`` values can be specified in a variety of ways: * An enum: "solid", "dashed", "dotted", "dotdash", "dashdot" * a tuple or list of integers in the `HTML5 Canvas dash specification style`_. Note that if the list of integers has an odd number of elements, then it is duplicated, and that duplicated list becomes the new dash list. To indicate that dashing is turned off (solid lines), specify the empty list []. .. _HTML5 Canvas dash specification style: http://www.w3.org/html/wg/drafts/2dcontext/html5_canvas/#dash-list """_dash_patterns={"solid":[],"dashed":[6],"dotted":[2,4],"dotdash":[2,4,6,4],"dashdot":[6,4,2,4],}def__init__(self,default=[],*,help:str|None=None)->None:types=Enum(enums.DashPattern),Regex(r"^(\d+(\s+\d+)*)?$"),Seq(Int)super().__init__(*types,default=default,help=help)def__str__(self)->str:returnself.__class__.__name__deftransform(self,value):value=super().transform(value)ifisinstance(value,str):try:returnself._dash_patterns[value]exceptKeyError:return[int(x)forxinvalue.split()]else:returnvalue
[docs]classFontSize(String):_font_size_re=re.compile(r"^[0-9]+(.[0-9]+)?(%|em|ex|ch|ic|rem|vw|vh|vi|vb|vmin|vmax|cm|mm|q|in|pc|pt|px)$",re.I)defvalidate(self,value:Any,detail:bool=True)->None:super().validate(value,detail)ifisinstance(value,str):iflen(value)==0:msg=""ifnotdetailelse"empty string is not a valid font size value"raiseValueError(msg)elifnotself._font_size_re.match(value):msg=""ifnotdetailelsef"{value!r} is not a valid font size value"raiseValueError(msg)
classHatchPatternType(Either):""" Accept built-in fill hatching specifications. Accepts either "long" names, e.g. "horizontal-wave" or the single letter abbreviations, e.g. "v" """def__init__(self,default=[],*,help:str|None=None)->None:types=Enum(enums.HatchPattern),Enum(enums.HatchPatternAbbreviation),Stringsuper().__init__(*types,default=default,help=help)def__str__(self)->str:returnself.__class__.__name__
[docs]classImage(Property):""" Accept image file types, e.g PNG, JPEG, TIFF, etc. This property can be configured with: * A ``pathlib.Path`` image file path * A data URL encoded image string * A string filename to be loaded with ``PIL.Image.open`` * An RGB(A) NumPy array, will be converted to PNG * A ``PIL.Image.Image`` object In all cases, the image data is serialized as a Base64 encoded string. """defvalidate(self,value:Any,detail:bool=True)->None:importnumpyasnpimportPIL.Imageifisinstance(value,str|Path|PIL.Image.Image):returnifisinstance(value,np.ndarray):ifvalue.dtype=="uint8"andlen(value.shape)==3andvalue.shape[2]in(3,4):returnmsg=""ifnotdetailelsef"invalid value: {value!r}; allowed values are string filenames, PIL.Image.Image instances, or RGB(A) NumPy arrays"raiseValueError(msg)deftransform(self,value):importnumpyasnpimportPIL.Imageifisinstance(value,np.ndarray):value=PIL.Image.fromarray(value)ifisinstance(value,str):returnvalue# tempfile doesn't implement IO interface (https://bugs.python.org/issue33762)ifisinstance(value,Path|BinaryIO|tempfile._TemporaryFileWrapper):value=PIL.Image.open(value)ifisinstance(value,PIL.Image.Image):out=BytesIO()fmt=value.formator"PNG"value.save(out,fmt)encoded=base64.b64encode(out.getvalue()).decode('ascii')returnf"data:image/{fmt.lower()};base64,{encoded}"raiseValueError(f"Could not transform {value!r}")
[docs]classMinMaxBounds(Either):""" Accept (min, max) bounds tuples for use with Ranges. Bounds are provided as a tuple of ``(min, max)`` so regardless of whether your range is increasing or decreasing, the first item should be the minimum value of the range and the second item should be the maximum. Setting min > max will result in a ``ValueError``. Setting bounds to None will allow your plot to pan/zoom as far as you want. If you only want to constrain one end of the plot, you can set min or max to ``None`` e.g. ``DataRange1d(bounds=(None, 12))`` """def__init__(self,default='auto',*,accept_datetime:bool=False,help:str|None=None)->None:types=(Auto,Tuple(Float,Float),Tuple(Nullable(Float),Float),Tuple(Float,Nullable(Float)),Tuple(TimeDelta,TimeDelta),Tuple(Nullable(TimeDelta),TimeDelta),Tuple(TimeDelta,Nullable(TimeDelta)),)ifaccept_datetime:types=(*types,Tuple(Datetime,Datetime),Tuple(Nullable(Datetime),Datetime),Tuple(Datetime,Nullable(Datetime)),)super().__init__(*types,default=default,help=help)defvalidate(self,value:Any,detail:bool=True)->None:super().validate(value,detail)ifvalue[0]isNoneorvalue[1]isNone:returnvalue=list(value)# make sure the values are timestamps for comparisonifisinstance(value[0],datetime.datetime):value[0]=convert_datetime_type(value[0])ifisinstance(value[1],datetime.datetime):value[1]=convert_datetime_type(value[1])ifvalue[0]<value[1]:returnmsg=""ifnotdetailelse"Invalid bounds: maximum smaller than minimum. Correct usage: bounds=(min, max)"raiseValueError(msg)