diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..5e2b3f8 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +patreon: whitequark diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml new file mode 100644 index 0000000..0adf9ca --- /dev/null +++ b/.github/workflows/package.yml @@ -0,0 +1,58 @@ +on: [push, pull_request] +name: Test & publish +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Check out source code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up PDM + uses: pdm-project/setup-pdm@v4 + - name: Install dependencies + run: pdm install --dev + - name: Run tests + run: pdm test + - name: Build Python artifact + run: pdm build + - name: Upload Python artifact + uses: actions/upload-artifact@v4 + with: + name: dist-pypi + path: dist/ + - name: Publish test documentation + uses: JamesIves/github-pages-deploy-action@releases/v4 + with: + folder: test/_out/ + check: # group all `test (*)` workflows into one for the required status check + needs: test + if: ${{ always() && !contains(needs.*.result, 'cancelled') }} + runs-on: ubuntu-latest + steps: + - run: ${{ contains(needs.*.result, 'failure') && 'false' || 'true' }} + publish: + needs: check + if: ${{ github.event_name == 'push' && github.repository == 'YoWASP/sphinxcontrib-wavedrom' }} + runs-on: ubuntu-latest + environment: publish + permissions: + id-token: write + steps: + - name: Download Python artifacts + uses: actions/download-artifact@v4 + with: + name: dist-pypi + path: dist-tree/ + - name: Prepare artifacts for publishing + run: | + mkdir dist + find dist-tree -name '*.whl' -exec mv {} dist/ \; + - name: Publish package to Test PyPI + if: ${{ github.event.ref == 'refs/heads/main' }} + uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: https://test.pypi.org/legacy/ + - name: Publish package to PyPI + if: ${{ startsWith(github.event.ref, 'refs/tags/') }} + uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9b7dcc4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# Python +__pycache__/ +*.egg-info +/dist + +# pdm +/.pdm-plugins +/.pdm-python +/.venv +/pdm.lock + +# tests +/test/_out diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..df57d87 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Catherine + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..28b5864 --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +sphinxcontrib-yowasp-wavedrom +============================= + +This [Sphinx] extension allows embedding [WaveDrom] waveform, bitfield, and circuit diagrams into Sphinx documents. + +This extension uses the [YoWASP WaveDrom][yowasp-wavedrom] package to ensure that diagrams are rendered exactly the same as in the WaveDrom editor, without having to follow a decision tree for configuration, without requiring any additional tools to be installed on the system used to build documentation, without requiring any native dependencies to be installed on that system, without requiring JavaScript for browsing documentation, and without slowing down the Sphinx build process. It also reports syntax and semantic errors with accurate source locations. + +WaveJSON diagram descriptions are always converted into SVG files; only the HTML builder is supported at the moment. Sphinx themes with color schemes toggles, like [Furo], are supported by default, but may require [custom CSS](/test/_static/wavedrom.css) for integration. + +[Sphinx]: https://www.sphinx-doc.org/ +[WaveDrom]: https://wavedrom.com/ +[yowasp-wavedrom]: https://github.com/YoWASP/wavedrom +[Furo]: https://github.com/pradyunsg/furo + + +Usage +----- + +This extension provides only one directive, `wavedrom`. Its argument is the base name, without extension, of the generated image file (in `/_images/`; which must be unique in the entire document tree), and its contents is the raw WaveJSON file that can be copied to or from the editor. For example: + +```rst +.. wavedrom:: clk_and_data + + {"signal": [ + {"name": "clk", "wave": "n..."}, + {"name": "data", "wave": "01.0"} + ]} +``` + +Additional examples are available [in the test suite](/test/index.rst), as well as the corresponding [rendered output](https://yowasp.github.io/sphinxcontrib-wavedrom/). + + +License +------- + +This project is distributed under the terms of the [MIT license](LICENSE.txt). diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..660b87b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,33 @@ +[tool.pdm.version] +source = "scm" + +[project] +dynamic = ["version"] + +name = "sphinxcontrib-yowasp-wavedrom" +description = "A Sphinx extension for embedding WaveDrom diagrams" +readme = "README.md" +authors = [{name = "Catherine", email = "whitequark@whitequark.org"}] +license = {text = "MIT"} +classifiers = [ + "License :: OSI Approved :: MIT License" +] + +requires-python = "~=3.8" +dependencies = [ + "Sphinx~=7.1", + "yowasp_wavedrom>=3.5.0.4", +] + +[build-system] +requires = ["pdm-backend"] +build-backend = "pdm.backend" + +[tool.pdm.build] +includes = ["sphinxcontrib/"] # required for a namespace package + +[tool.pdm.dev-dependencies] +test = ["furo"] + +[tool.pdm.scripts] +test = "sphinx-build -aE -b html test test/_out" diff --git a/sphinxcontrib/yowasp_wavedrom.py b/sphinxcontrib/yowasp_wavedrom.py new file mode 100644 index 0000000..02ec805 --- /dev/null +++ b/sphinxcontrib/yowasp_wavedrom.py @@ -0,0 +1,86 @@ +import re +import json +from pathlib import Path +from docutils.parsers.rst import Directive +from docutils import nodes +import sphinx.application +import yowasp_wavedrom + + +class WaveDromDirective(Directive): + required_arguments = 1 + has_content = True + + def run(self): + self.assert_has_content() + + # Extract basename of the generated image file. + name, = self.arguments + + # This is a really weird way to extract the payload of a directive, but it keeps accurate + # line and more importantly column numbers within `JSONDecodeError`. + payload = re.sub(r"^..\s+wavedrom\s*::.+?\n", "\n", self.block_text) + + # Parse and validate WaveJSON source. + try: + wavedrom_src = json.loads(payload) + except json.decoder.JSONDecodeError as error: + return [self.reporter.error( + f"line {error.lineno + self.lineno - 1}, column {error.colno}: " + f"JSON: {error.msg}" + )] + + node = wavedrom_diagram(self.block_text, name=name, src=wavedrom_src, + loc=f'{self.state.document["source"]}:{self.lineno}') + self.add_name(node) + return [node] + + +class wavedrom_diagram(nodes.General, nodes.Inline, nodes.Element): + pass + + +def html_visit_wavedrom_diagram(self, node): + basename: str = node["name"] + wavedrom_loc: str = node["loc"] + wavedrom_src: dict = node["src"] + + # Adjust diagram configuration according to builder configuration. + wavedrom_src_config = wavedrom_src.setdefault("config", {}) + if "signal" in wavedrom_src: + wavedrom_src_config.setdefault("skin", self.builder.config.yowasp_wavedrom_skin) + + # Render WaveJSON to an SVG. + try: + wavedrom_svg = yowasp_wavedrom.render(wavedrom_src) + except Exception as error: + sphinx.application.logger.error( + f'Could not render WaveDrom diagram at {wavedrom_loc}: {error}') + self.body.append(f'' + f'
/!\ Could not render WaveDrom diagram: {self.encode(error)}
' + f'
') + raise nodes.SkipNode + + # Write the SVG to output directory. This is necessary because inlining it into the HTML has + # significantly different behavior: duplicate IDs result in broken rendering, text can be + # selected, media queries can't be overridden with a `color-scheme` CSS attribute for themes + # that have a dark/light toggle via JS, etc. + pathname = Path(self.builder.outdir) / self.builder.imagedir / f'{basename}.svg' + pathname.parent.mkdir(parents=True, exist_ok=True) + pathname.write_text(wavedrom_svg) + + # Reference the SVG in the HTML document. + self.body.append(f'') + raise nodes.SkipNode + + +def setup(app: sphinx.application.Sphinx): + app.add_config_value("yowasp_wavedrom_skin", "default", "html", str) + app.add_directive("wavedrom", WaveDromDirective) + app.add_node(wavedrom_diagram, + html=(html_visit_wavedrom_diagram, None)) + return { + "parallel_read_safe": True, + "parallel_write_safe": True + } diff --git a/test/_static/wavedrom.css b/test/_static/wavedrom.css new file mode 100644 index 0000000..51576a2 --- /dev/null +++ b/test/_static/wavedrom.css @@ -0,0 +1,2 @@ +body[data-theme="light"] { img { color-scheme: light; } } +body[data-theme="dark"] { img { color-scheme: dark; } } diff --git a/test/conf.py b/test/conf.py new file mode 100644 index 0000000..4e376d5 --- /dev/null +++ b/test/conf.py @@ -0,0 +1,8 @@ +project = "WaveDrom extension for Sphinx" +extensions = ["sphinxcontrib.yowasp_wavedrom"] +master_doc = "index" +html_theme = "furo" # with dark theme support +html_static_path = ['_static'] +html_css_files = ["wavedrom.css"] + +# yowasp_wavedrom_skin = "default" diff --git a/test/index.rst b/test/index.rst new file mode 100644 index 0000000..97e7acb --- /dev/null +++ b/test/index.rst @@ -0,0 +1,86 @@ +sphinxcontrib-yowasp-wavedrom test page +======================================= + + +Waveform diagrams +----------------- + +default: + +.. wavedrom:: skin_default + + {"signal": [ + {"name": "clk", "wave": "n..."}, + {"name": "data", "wave": "01.0"} + ]} + +light: + +.. wavedrom:: skin_light + + { + "signal": [ + {"name": "clk", "wave": "p..."}, + {"name": "data", "wave": "01.0"} + ], + "config": {"skin": "light"} + } + +dark: + +.. wavedrom:: skin_dark + + { + "signal": [ + {"name": "clk", "wave": "p..."}, + {"name": "data", "wave": "01.0"} + ], + "config": {"skin": "dark"} + } + +narrow: + +.. + test nested base names + +.. wavedrom:: extra/skin_narrow + + { + "signal": [ + {"name": "clk", "wave": "n..."}, + {"name": "data", "wave": "01.0"} + ], + "config": {"skin": "narrow"} + } + + +Bit field diagrams +------------------ + +.. wavedrom:: uart_rx_status + + { + "reg": [ + { "name": "ready", "bits": 1, "attr": "R" }, + { "name": "overflow", "bits": 1, "attr": "RW1C" }, + { "name": "error", "bits": 1, "attr": "RW1C" }, + { "bits": 5, "attr": "ResR0W0" } + ] + } + + +Circuit diagrams +---------------- + +.. wavedrom:: circuit + + { + "assign": [ + ["out", + ["|", + ["&", ["~", "a"], "b"], + ["&", ["~", "b"], "a"] + ] + ] + ] + }