[
  {
    "path": ".gitignore",
    "content": ".pyc\n__pycache__\ndist/\n*.egg-info/\n"
  },
  {
    "path": "LICENSE",
    "content": "Creative Commons Legal Code\n\nCC0 1.0 Universal\n\n    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE\n    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN\n    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS\n    INFORMATION ON AN \"AS-IS\" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES\n    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS\n    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM\n    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED\n    HEREUNDER.\n\nStatement of Purpose\n\nThe laws of most jurisdictions throughout the world automatically confer\nexclusive Copyright and Related Rights (defined below) upon the creator\nand subsequent owner(s) (each and all, an \"owner\") of an original work of\nauthorship and/or a database (each, a \"Work\").\n\nCertain owners wish to permanently relinquish those rights to a Work for\nthe purpose of contributing to a commons of creative, cultural and\nscientific works (\"Commons\") that the public can reliably and without fear\nof later claims of infringement build upon, modify, incorporate in other\nworks, reuse and redistribute as freely as possible in any form whatsoever\nand for any purposes, including without limitation commercial purposes.\nThese owners may contribute to the Commons to promote the ideal of a free\nculture and the further production of creative, cultural and scientific\nworks, or to gain reputation or greater distribution for their Work in\npart through the use and efforts of others.\n\nFor these and/or other purposes and motivations, and without any\nexpectation of additional consideration or compensation, the person\nassociating CC0 with a Work (the \"Affirmer\"), to the extent that he or she\nis an owner of Copyright and Related Rights in the Work, voluntarily\nelects to apply CC0 to the Work and publicly distribute the Work under its\nterms, with knowledge of his or her Copyright and Related Rights in the\nWork and the meaning and intended legal effect of CC0 on those rights.\n\n1. Copyright and Related Rights. A Work made available under CC0 may be\nprotected by copyright and related or neighboring rights (\"Copyright and\nRelated Rights\"). Copyright and Related Rights include, but are not\nlimited to, the following:\n\n  i. the right to reproduce, adapt, distribute, perform, display,\n     communicate, and translate a Work;\n ii. moral rights retained by the original author(s) and/or performer(s);\niii. publicity and privacy rights pertaining to a person's image or\n     likeness depicted in a Work;\n iv. rights protecting against unfair competition in regards to a Work,\n     subject to the limitations in paragraph 4(a), below;\n  v. rights protecting the extraction, dissemination, use and reuse of data\n     in a Work;\n vi. database rights (such as those arising under Directive 96/9/EC of the\n     European Parliament and of the Council of 11 March 1996 on the legal\n     protection of databases, and under any national implementation\n     thereof, including any amended or successor version of such\n     directive); and\nvii. other similar, equivalent or corresponding rights throughout the\n     world based on applicable law or treaty, and any national\n     implementations thereof.\n\n2. Waiver. To the greatest extent permitted by, but not in contravention\nof, applicable law, Affirmer hereby overtly, fully, permanently,\nirrevocably and unconditionally waives, abandons, and surrenders all of\nAffirmer's Copyright and Related Rights and associated claims and causes\nof action, whether now known or unknown (including existing as well as\nfuture claims and causes of action), in the Work (i) in all territories\nworldwide, (ii) for the maximum duration provided by applicable law or\ntreaty (including future time extensions), (iii) in any current or future\nmedium and for any number of copies, and (iv) for any purpose whatsoever,\nincluding without limitation commercial, advertising or promotional\npurposes (the \"Waiver\"). Affirmer makes the Waiver for th benefit of each\nmember of the public at large and to the detriment of Affirmer's heirs and\nsuccessors, fully intending that such Waiver shall not be subject to\nrevocation, rescission, cancellation, termination, or any other legal or\nequitable action to disrupt the quiet enjoyment of the Work by the public\nas contemplated by Affirmer's express Statement of Purpose.\n\n3. Public License Fallback. Should any part of the Waiver for any reason\nbe judged legally invalid or ineffective under applicable law, then the\nWaiver shall be preserved to the maximum extent permitted taking into\naccount Affirmer's express Statement of Purpose. In addition, to the\nextent the Waiver is so judged Affirmer hereby grants to each affected\nperson a royalty-free, non transferable, non sublicensable, non exclusive,\nirrevocable and unconditional license to exercise Affirmer's Copyright and\nRelated Rights in the Work (i) in all territories worldwide, (ii) for the\nmaximum duration provided by applicable law or treaty (including future\ntime extensions), (iii) in any current or future medium and for any number\nof copies, and (iv) for any purpose whatsoever, including without\nlimitation commercial, advertising or promotional purposes (the\n\"License\"). The License shall be deemed effective as of the date CC0 was\napplied by Affirmer to the Work. Should any part of the License for any\nreason be judged legally invalid or ineffective under applicable law, such\npartial invalidity or ineffectiveness shall not invalidate the remainder\nof the License, and in such case Affirmer hereby affirms that he or she\nwill not (i) exercise any of his or her remaining Copyright and Related\nRights in the Work or (ii) assert any associated claims and causes of\naction with respect to the Work, in either case contrary to Affirmer's\nexpress Statement of Purpose.\n\n4. Limitations and Disclaimers.\n\n a. No trademark or patent rights held by Affirmer are waived, abandoned,\n    surrendered, licensed or otherwise affected by this document.\n b. Affirmer offers the Work as-is and makes no representations or\n    warranties of any kind concerning the Work, express, implied,\n    statutory or otherwise, including without limitation warranties of\n    title, merchantability, fitness for a particular purpose, non\n    infringement, or the absence of latent or other defects, accuracy, or\n    the present or absence of errors, whether or not discoverable, all to\n    the greatest extent permissible under applicable law.\n c. Affirmer disclaims responsibility for clearing rights of other persons\n    that may apply to the Work or any use thereof, including without\n    limitation any person's Copyright and Related Rights in the Work.\n    Further, Affirmer disclaims responsibility for obtaining any necessary\n    consents, permissions or other rights required for any use of the\n    Work.\n d. Affirmer understands and acknowledges that Creative Commons is not a\n    party to this document and has no duty or obligation with respect to\n    this CC0 or use of the Work.\n"
  },
  {
    "path": "README.md",
    "content": "# matplotlib-backend-kitty\n\nThis python module allows you to use your\n[kitty terminal](https://github.com/kovidgoyal/kitty)\nto show the plots generated by python's\n[matplotlib](https://github.com/matplotlib/matplotlib).\n\nFor other terminals, the similar [notcurses backend](https://github.com/jktr/matplotlib-backend-notcurses)\nmay also be of interest.\n\nTo install this one, do one of the following\n\n - `$ pip install --user matplotlib-backend-kitty`\n - clone this repo into your python's `site-packages` directory\n - clone this repo and add the parent directory to `sys.path` or `$PYTHONPATH`\n\nThen, configure matplotlib to use the module by either setting the\nenvironment variable `MPLBACKEND` to `module://matplotlib-backend-kitty`\nor by initializing matplotlib as follows.\n\n```python\nimport matplotlib\nmatplotlib.use('module://matplotlib-backend-kitty')\nimport matplotlib.pyplot as plt\n```\n\nIf you've installed this module correctly, you can now use\nthe following sample code to draw a plot in your terminal.\n\n```\n$ export MPLBACKEND='module://matplotlib-backend-kitty'\n$ python\n>>> n = 10000\n>>> df = pd.DataFrame({'x': np.random.randn(n),\n                       'y': np.random.randn(n)})\n>>> df.plot.hexbin(x='x', y='y', gridsize=20)\n<plot is shown>\n```\n\nIf you set your matplotlib to interactive mode via\n`matplotlib.pyplot.ion()` or by running an interactive python\nshell like `python` or `ipython`, non-empty figures are drawn on\nconstruction where possible. This allows you to use pandas'\n`plot()` calls directly, without calling `plt.show()`, and still\nenables you to manually construct and `plt.show()`.\n\nIf your matplotlib is in non-interactive mode,\nyou can construct your figures as usual, and then call\n`plt.show()` to render them to your terminal. This\nworks both from scripts and from a repl.\n\nFigures are resized to the size of your terminal by default.\nIf you'd rather control the sizing of figures manually,\nset the `MPLBACKEND_KITTY_SIZING` environment variable to `manual`.\n\nInternally, this backend is somewhat based on matplotlib's\nIPython support: it's a hybrid of image and GUI backend types.\nIt works by using matplotlib's `Agg` backend to render the\nplot, and then calls kitty's `icat` to place the rendered\nimage on your terminal. This means that plotting works as\nexpected, but the image drawn to your terminal isn't\ninteractive and animations aren't supported.\n"
  },
  {
    "path": "matplotlib-backend-kitty/__init__.py",
    "content": "# SPDX-License-Identifier: CC0-1.0\n\nimport os\nimport sys\n\nfrom io import BytesIO\nfrom subprocess import run\n\nfrom matplotlib import interactive, is_interactive\nfrom matplotlib._pylab_helpers import Gcf\nfrom matplotlib.backend_bases import (_Backend, FigureManagerBase)\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\n\n\n# XXX heuristic for interactive repl\nif hasattr(sys, 'ps1') or sys.flags.interactive:\n    interactive(True)\n\n\nclass FigureManagerICat(FigureManagerBase):\n\n    @classmethod\n    def _run(cls, *cmd):\n        def f(*args, output=True, **kwargs):\n            if output:\n                kwargs['capture_output'] = True\n                kwargs['text'] = True\n            r = run(cmd + args, **kwargs)\n            if output:\n                return r.stdout.rstrip()\n        return f\n\n    def show(self):\n\n        icat = __class__._run('kitty', '+kitten', 'icat')\n\n        if os.environ.get('MPLBACKEND_KITTY_SIZING', 'automatic') != 'manual':\n\n            tput = __class__._run('tput')\n\n            # gather terminal dimensions\n            rows = int(tput('lines'))\n            px = icat('--print-window-size')\n            px = list(map(int, px.split('x')))\n\n            # account for post-display prompt scrolling\n            # 3 line shift for [\\n, <matplotlib.axes…, >>>] after the figure\n            px[1] -= int(3*(px[1]/rows))\n\n            # resize figure to terminal size & aspect ratio\n            dpi = self.canvas.figure.dpi\n            self.canvas.figure.set_size_inches((px[0] / dpi, px[1] / dpi))\n\n        with BytesIO() as buf:\n            self.canvas.figure.savefig(buf, format='png')\n            icat('--align', 'left', output=False, input=buf.getbuffer())\n\n\nclass FigureCanvasICat(FigureCanvasAgg):\n    manager_class = FigureManagerICat\n\n\n@_Backend.export\nclass _BackendICatAgg(_Backend):\n\n    FigureCanvas = FigureCanvasICat\n    FigureManager = FigureManagerICat\n\n    # Noop function instead of None signals that\n    # this is an \"interactive\" backend\n    mainloop = lambda: None\n\n    # XXX: `draw_if_interactive` isn't really intended for\n    # on-shot rendering. We run the risk of being called\n    # on a figure that isn't completely rendered yet, so\n    # we skip draw calls for figures that we detect as\n    # not being fully initialized yet. Our heuristic for\n    # that is the presence of axes on the figure.\n    @classmethod\n    def draw_if_interactive(cls):\n        manager = Gcf.get_active()\n        if is_interactive() and manager.canvas.figure.get_axes():\n            cls.show()\n\n    @classmethod\n    def show(cls, *args, **kwargs):\n        _Backend.show(*args, **kwargs)\n        Gcf.destroy_all()\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[project]\nname = \"matplotlib-backend-kitty\"\nversion = \"2.1.2\"\ndescription = \"show matplotlib plots directly in your kitty terminal\"\nreadme = \"README.md\"\nclassifiers = [\n    \"Programming Language :: Python :: 3\",\n    \"License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication\",\n    \"Framework :: Matplotlib\",\n    \"Topic :: Terminals\",\n]\ndependencies = [ \"matplotlib\" ]\n\n[project.urls]\n\"Homepage\" = \"https://github.com/jktr/matplotlib-backend-kitty\"\n\"Bug Tracker\" = \"https://github.com/jktr/matplotlib-backend-kitty/issues\"\n\n[build-system]\nrequires = [ \"setuptools>=61.0\" ]\nbuild-backend = \"setuptools.build_meta\"\n\n[tool.setuptools.packages.find]\nwhere = [ \".\" ]\n"
  }
]