#-----------------------------------------------------------------------------# Copyright (c) Anaconda, Inc., and Bokeh Contributors.# All rights reserved.## The full license is in the file LICENSE.txt, distributed with this software.#-----------------------------------------------------------------------------''' Encapsulate implicit state that is useful for Bokeh plotting APIs... note:: While ``State`` objects can also be manipulated explicitly, they are automatically configured when the output functions like |output_file| from :ref:`bokeh.io` are used. Therefore, manipulating ``State`` objects is usually not necessary.Generating output for Bokeh plots requires coordinating several things:|Document| Groups together Bokeh models that may be shared between plots (e.g., range or data source objects) into one common structure.:class:`~bokeh.resources.Resources` Control how JavaScript and CSS for the client library BokehJS are included and used in the generated output.It is possible to handle the configuration of these things manually, and someexamples of doing this can be found in ``examples/models`` directory. Whendeveloping sophisticated applications, it may be necessary or desirable to workat this level. However, for general use this would quickly become burdensome.This module provides a ``State`` class that encapsulates these objects andensures their proper configuration in many common usage scenarios.'''#-----------------------------------------------------------------------------# Boilerplate#-----------------------------------------------------------------------------from__future__importannotationsimportlogging# isort:skiplog=logging.getLogger(__name__)#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------# Standard library importsimportosfromdataclassesimportdataclassfromtypingimportTYPE_CHECKING,cast# Bokeh importsfrom..core.typesimportPathLikefrom..documentimportDocumentfrom..resourcesimportResources,ResourcesModeifTYPE_CHECKING:from..core.typesimportIDfrom..server.serverimportServerfrom.notebookimportCommsHandle,NotebookType#-----------------------------------------------------------------------------# Globals and constants#-----------------------------------------------------------------------------__all__=('curstate','State',)#-----------------------------------------------------------------------------# General API#-----------------------------------------------------------------------------
[docs]classState:''' Manage state related to controlling Bokeh output. '''_file:FileConfig|None_notebook:bool_notebook_type:NotebookType|Nonelast_comms_handle:CommsHandle|Noneuuid_to_server:dict[ID,Server]def__init__(self)->None:self.last_comms_handle=Noneself.uuid_to_server={}# Mapping from uuid to server instanceself.reset()# Properties --------------------------------------------------------------@propertydefdocument(self)->Document:''' A default |Document| to use for all output operations. '''returnself._document@document.setterdefdocument(self,doc:Document)->None:self._document=doc@propertydeffile(self)->FileConfig|None:''' A structure with the default configuration for file output (READ ONLY) See :class:`~bokeh.io.state.FileConfig`. '''returnself._file@propertydefnotebook(self)->bool:''' Whether to generate notebook output on show operations. (READ ONLY) '''returnself._notebook@propertydefnotebook_type(self)->NotebookType|None:''' Notebook type '''returnself._notebook_type@notebook_type.setterdefnotebook_type(self,notebook_type:NotebookType)->None:''' Notebook type, acceptable values are 'jupyter' as well as any names defined by external notebook hooks that have been installed. '''ifnotebook_typeisNoneornotisinstance(notebook_type,str):raiseValueError("Notebook type must be a string")self._notebook_type=cast("NotebookType",notebook_type.lower())# Public methods ----------------------------------------------------------
[docs]defoutput_file(self,filename:PathLike,title:str="Bokeh Plot",mode:ResourcesMode|None=None,root_dir:PathLike|None=None)->None:''' Configure output to a standalone HTML file. Calling ``output_file`` does not clear the effects of any other calls to |output_notebook|, etc. It adds an additional output destination (publishing to HTML files). Any other active output modes continue to be active. Args: filename (PathLike, e.g. str, Path) : a filename for saving the HTML document title (str, optional) : a title for the HTML document mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources` for more details. root_dir (str, optional) : root dir to use for absolute resources (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. .. warning:: The specified output file will be overwritten on every save, e.g., every time ``show()`` or ``save()`` is called. '''self._file=FileConfig(filename=filename,resources=Resources(mode=mode,root_dir=root_dir),title=title,)ifos.path.isfile(filename):log.info(f"Session output file '{filename}' already exists, will be overwritten.")
[docs]defoutput_notebook(self,notebook_type:NotebookType="jupyter")->None:''' Generate output in notebook cells. Calling ``output_notebook`` does not clear the effects of any other calls to |output_file|, etc. It adds an additional output destination (publishing to notebook output cells). Any other active output modes continue to be active. Returns: None '''self._notebook=Trueself.notebook_type=notebook_type
[docs]defreset(self)->None:''' Deactivate all currently active output modes and set ``curdoc()`` to a fresh empty ``Document``. Subsequent calls to ``show()`` will not render until a new output mode is activated. Returns: None '''self._reset_with_doc(Document())
# Private methods ---------------------------------------------------------def_reset_keeping_doc(self)->None:''' Reset output modes but DO NOT replace the default Document '''self._file=Noneself._notebook=Falseself._notebook_type=Nonedef_reset_with_doc(self,doc:Document)->None:''' Reset output modes but DO replace the default Document '''self._document=docself._reset_keeping_doc()
[docs]defcurstate()->State:''' Return the current State object Returns: State : the current default State object '''global_STATEif_STATEisNone:_STATE=State()return_STATE
#-----------------------------------------------------------------------------# Dev API#-----------------------------------------------------------------------------@dataclass(frozen=True)classFileConfig:filename:PathLikeresources:Resourcestitle:str#-----------------------------------------------------------------------------# Private API#-----------------------------------------------------------------------------_STATE:State|None=None#-----------------------------------------------------------------------------# Code#-----------------------------------------------------------------------------