{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Embedding WebAgg\n\nThis example demonstrates how to embed Matplotlib WebAgg interactive plotting\nin your own web application and framework.  It is not necessary to do all this\nif you merely want to display a plot in a browser or use Matplotlib's built-in\nTornado-based server \"on the side\".\n\nThe framework being used must support web sockets.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import argparse\nimport io\nimport json\nimport mimetypes\nfrom pathlib import Path\nimport signal\nimport socket\n\ntry:\n    import tornado\nexcept ImportError as err:\n    raise RuntimeError(\"This example requires tornado.\") from err\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nimport tornado.websocket\n\nimport numpy as np\n\nimport matplotlib as mpl\nfrom matplotlib.backends.backend_webagg import (FigureManagerWebAgg,\n                                                new_figure_manager_given_figure)\nfrom matplotlib.figure import Figure\n\n\ndef create_figure():\n    \"\"\"\n    Creates a simple example figure.\n    \"\"\"\n    fig = Figure()\n    ax = fig.add_subplot()\n    t = np.arange(0.0, 3.0, 0.01)\n    s = np.sin(2 * np.pi * t)\n    ax.plot(t, s)\n    return fig\n\n\n# The following is the content of the web page.  You would normally\n# generate this using some sort of template facility in your web\n# framework, but here we just use Python string formatting.\nhtml_content = \"\"\"<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <!-- TODO: There should be a way to include all of the required javascript\n               and CSS so matplotlib can add to the set in the future if it\n               needs to. -->\n    <link rel=\"stylesheet\" href=\"_static/css/page.css\" type=\"text/css\">\n    <link rel=\"stylesheet\" href=\"_static/css/boilerplate.css\" type=\"text/css\">\n    <link rel=\"stylesheet\" href=\"_static/css/fbm.css\" type=\"text/css\">\n    <link rel=\"stylesheet\" href=\"_static/css/mpl.css\" type=\"text/css\">\n    <script src=\"mpl.js\"></script>\n\n    <script>\n      /* This is a callback that is called when the user saves\n         (downloads) a file.  Its purpose is really to map from a\n         figure and file format to a url in the application. */\n      function ondownload(figure, format) {\n        window.open('download.' + format, '_blank');\n      };\n\n      function ready(fn) {\n        if (document.readyState != \"loading\") {\n          fn();\n        } else {\n          document.addEventListener(\"DOMContentLoaded\", fn);\n        }\n      }\n\n      ready(\n        function() {\n          /* It is up to the application to provide a websocket that the figure\n             will use to communicate to the server.  This websocket object can\n             also be a \"fake\" websocket that underneath multiplexes messages\n             from multiple figures, if necessary. */\n          var websocket_type = mpl.get_websocket_type();\n          var websocket = new websocket_type(\"%(ws_uri)sws\");\n\n          // mpl.figure creates a new figure on the webpage.\n          var fig = new mpl.figure(\n              // A unique numeric identifier for the figure\n              %(fig_id)s,\n              // A websocket object (or something that behaves like one)\n              websocket,\n              // A function called when a file type is selected for download\n              ondownload,\n              // The HTML element in which to place the figure\n              document.getElementById(\"figure\"));\n        }\n      );\n    </script>\n\n    <title>matplotlib</title>\n  </head>\n\n  <body>\n    <div id=\"figure\">\n    </div>\n  </body>\n</html>\n\"\"\"\n\n\nclass MyApplication(tornado.web.Application):\n    class MainPage(tornado.web.RequestHandler):\n        \"\"\"\n        Serves the main HTML page.\n        \"\"\"\n\n        def get(self):\n            manager = self.application.manager\n            ws_uri = f\"ws://{self.request.host}/\"\n            content = html_content % {\n                \"ws_uri\": ws_uri, \"fig_id\": manager.num}\n            self.write(content)\n\n    class MplJs(tornado.web.RequestHandler):\n        \"\"\"\n        Serves the generated matplotlib javascript file.  The content\n        is dynamically generated based on which toolbar functions the\n        user has defined.  Call `FigureManagerWebAgg` to get its\n        content.\n        \"\"\"\n\n        def get(self):\n            self.set_header('Content-Type', 'application/javascript')\n            js_content = FigureManagerWebAgg.get_javascript()\n\n            self.write(js_content)\n\n    class Download(tornado.web.RequestHandler):\n        \"\"\"\n        Handles downloading of the figure in various file formats.\n        \"\"\"\n\n        def get(self, fmt):\n            manager = self.application.manager\n            self.set_header(\n                'Content-Type', mimetypes.types_map.get(fmt, 'binary'))\n            buff = io.BytesIO()\n            manager.canvas.figure.savefig(buff, format=fmt)\n            self.write(buff.getvalue())\n\n    class WebSocket(tornado.websocket.WebSocketHandler):\n        \"\"\"\n        A websocket for interactive communication between the plot in\n        the browser and the server.\n\n        In addition to the methods required by tornado, it is required to\n        have two callback methods:\n\n            - ``send_json(json_content)`` is called by matplotlib when\n              it needs to send json to the browser.  `json_content` is\n              a JSON tree (Python dictionary), and it is the responsibility\n              of this implementation to encode it as a string to send over\n              the socket.\n\n            - ``send_binary(blob)`` is called to send binary image data\n              to the browser.\n        \"\"\"\n        supports_binary = True\n\n        def open(self):\n            # Register the websocket with the FigureManager.\n            manager = self.application.manager\n            manager.add_web_socket(self)\n            if hasattr(self, 'set_nodelay'):\n                self.set_nodelay(True)\n\n        def on_close(self):\n            # When the socket is closed, deregister the websocket with\n            # the FigureManager.\n            manager = self.application.manager\n            manager.remove_web_socket(self)\n\n        def on_message(self, message):\n            # The 'supports_binary' message is relevant to the\n            # websocket itself.  The other messages get passed along\n            # to matplotlib as-is.\n\n            # Every message has a \"type\" and a \"figure_id\".\n            message = json.loads(message)\n            if message['type'] == 'supports_binary':\n                self.supports_binary = message['value']\n            else:\n                manager = self.application.manager\n                manager.handle_json(message)\n\n        def send_json(self, content):\n            self.write_message(json.dumps(content))\n\n        def send_binary(self, blob):\n            if self.supports_binary:\n                self.write_message(blob, binary=True)\n            else:\n                data_uri = (\"data:image/png;base64,\" +\n                            blob.encode('base64').replace('\\n', ''))\n                self.write_message(data_uri)\n\n    def __init__(self, figure):\n        self.figure = figure\n        self.manager = new_figure_manager_given_figure(id(figure), figure)\n\n        super().__init__([\n            # Static files for the CSS and JS\n            (r'/_static/(.*)',\n             tornado.web.StaticFileHandler,\n             {'path': FigureManagerWebAgg.get_static_file_path()}),\n\n            # Static images for the toolbar\n            (r'/_images/(.*)',\n             tornado.web.StaticFileHandler,\n             {'path': Path(mpl.get_data_path(), 'images')}),\n\n            # The page that contains all of the pieces\n            ('/', self.MainPage),\n\n            ('/mpl.js', self.MplJs),\n\n            # Sends images and events to the browser, and receives\n            # events from the browser\n            ('/ws', self.WebSocket),\n\n            # Handles the downloading (i.e., saving) of static images\n            (r'/download.([a-z0-9.]+)', self.Download),\n        ])\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-p', '--port', type=int, default=8080,\n                        help='Port to listen on (0 for a random port).')\n    args = parser.parse_args()\n\n    figure = create_figure()\n    application = MyApplication(figure)\n\n    http_server = tornado.httpserver.HTTPServer(application)\n    sockets = tornado.netutil.bind_sockets(args.port, '')\n    http_server.add_sockets(sockets)\n\n    for s in sockets:\n        addr, port = s.getsockname()[:2]\n        if s.family is socket.AF_INET6:\n            addr = f'[{addr}]'\n        print(f\"Listening on http://{addr}:{port}/\")\n    print(\"Press Ctrl+C to quit\")\n\n    ioloop = tornado.ioloop.IOLoop.instance()\n\n    def shutdown():\n        ioloop.stop()\n        print(\"Server stopped\")\n\n    old_handler = signal.signal(\n        signal.SIGINT,\n        lambda sig, frame: ioloop.add_callback_from_signal(shutdown))\n\n    try:\n        ioloop.start()\n    finally:\n        signal.signal(signal.SIGINT, old_handler)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}