diff --git a/CHANGELOG.md b/CHANGELOG.md index 3441132..a9dc780 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Bundled figure font: Liberation Sans** (SIL OFL 1.1, metric-compatible with Arial), + shipped as package data in `karyoplot/data/fonts/` with its LICENSE/AUTHORS. + `core.fonts.register_vendored_fonts()` registers it with matplotlib so figures render + in the same typeface on every host — no system-font install, no license-encumbered + brand fonts, fully reproducible. This is the intended default for publication figures. - `ComparisonConfig.volcano_labels` — an optional `{feature_label: {"side": ..., "gap": ...}}` map that pins individual volcano labels to a chosen side/distance. karyoplot stays DB-agnostic (it receives the resolved map, never a database). @@ -22,6 +27,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Figures now default to the bundled Liberation Sans** instead of the optional Barthel + brand font. `mpl.style.apply_default_style` sets `font.family = ["Liberation Sans", + "DejaVu Sans"]` (DejaVu kept as the secondary family for Greek/subscript glyphs), and + `core.fonts.pil_font` defaults to Liberation Sans for raster output. The commercial + Basic Sans/Bicyclette fonts remain an explicit opt-in via `register_fonts` (with a + `$BARTHEL_FONT_DIR` override) but are no longer the default, since they can't be + vendored/redistributed and previously fell back silently to DejaVu off the author's Mac. - **Volcano label placement rewritten** to sit each label immediately beside its own marker via a deterministic greedy side-search (no `adjustText`, no leader lines) — reproducible across figure sizes, and overridable per label via diff --git a/pyproject.toml b/pyproject.toml index f864a9e..864cfda 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -81,6 +81,9 @@ include = [ [tool.hatch.build.targets.wheel] packages = ["src/karyoplot"] +# Bundled figure font (Liberation Sans, OFL 1.1) + its license/authors. Force-included +# so the binaries ship even when the build can't consult VCS to enumerate files. +artifacts = ["src/karyoplot/data/fonts/*.ttf", "src/karyoplot/data/fonts/*.txt"] # --- ruff (linter + formatter) --- # Config mirrors the sibling KaryoScope-analysis repo so the ecosystem lints diff --git a/src/karyoplot/core/fonts.py b/src/karyoplot/core/fonts.py index d66bcef..4443cd6 100644 --- a/src/karyoplot/core/fonts.py +++ b/src/karyoplot/core/fonts.py @@ -1,14 +1,23 @@ """Font registration for KaryoScope plots. -The library defaults to the generic CSS ``sans-serif`` family so plots -work without any extra font files. The optional Barthel brand fonts -(Basic Sans, Bicyclette) can be registered with :func:`register_fonts` -when available — a silent no-op if the font directory is missing. +For publication figures the library ships its own freely-licensed font, +**Liberation Sans** (SIL OFL 1.1, metric-compatible with Arial), as package +data. :func:`register_vendored_fonts` registers it with matplotlib, so every +consumer renders identically on any host — no system font install, no +license-encumbered brand fonts, fully reproducible. This is the intended +default for the manuscript figures. + +The optional Barthel *presentation* fonts (Basic Sans, Bicyclette) remain an +explicit opt-in via :func:`register_fonts` when a caller genuinely wants the +slide typeface — a silent no-op if the font directory is missing. They are +commercial (Adobe Fonts) and must not be vendored/redistributed, which is why +they are not the figure default. Examples: >>> from karyoplot.core import fonts - >>> registered = fonts.register_fonts() # quiet, returns list - >>> fonts.is_available("Basic Sans") # check before using + >>> fonts.register_vendored_fonts() # ['Liberation Sans'] + >>> fonts.is_available("Liberation Sans") + True """ from __future__ import annotations @@ -18,11 +27,63 @@ DEFAULT_FONT_FAMILY = "sans-serif" -BARTHEL_FONT_DIR = Path.home() / "Documents" / "Barthel-Custom-Powerpoint-Theme" / "fonts" +#: Freely-licensed figure font shipped in ``karyoplot/data/fonts`` (OFL 1.1). +VENDORED_FONT_FAMILY = "Liberation Sans" + +#: Optional Barthel *presentation* fonts. The ``.otf`` files live in the Barthel +#: ``Powerpoint-Themes`` repo (``fonts/``); point ``$BARTHEL_FONT_DIR`` at that +#: directory to opt in. Commercial (Adobe Fonts) — never vendored here. +BARTHEL_FONT_DIR = Path( + os.environ.get( + "BARTHEL_FONT_DIR", Path.home() / "Documents" / "Barthel-Custom-Powerpoint-Theme" / "fonts" + ) +) BARTHEL_FONT_FAMILIES = ("Basic Sans", "Bicyclette") +def _vendored_font_dir() -> Path | None: + """Filesystem path of the bundled fonts, or ``None`` if it can't be resolved. + + Uses ``importlib.resources`` so it works for an editable checkout and a normal + (unpacked) wheel install alike. matplotlib stores the font path and re-opens it + at draw time, so a real, persistent path is required. + """ + try: + from importlib.resources import files + + path = Path(str(files("karyoplot").joinpath("data", "fonts"))) + except Exception: + return None + return path if path.is_dir() else None + + +def register_vendored_fonts() -> list[str]: + """Register the bundled Liberation Sans family with matplotlib. + + Returns: + The font family names registered (``["Liberation Sans"]``), or ``[]`` if + matplotlib is not importable or the bundled fonts can't be found. + """ + try: + import matplotlib.font_manager as fm + except ImportError: + return [] + + font_dir = _vendored_font_dir() + if font_dir is None: + return [] + + registered: set[str] = set() + for font_file in font_dir.glob("LiberationSans-*.ttf"): + try: + fm.fontManager.addfont(str(font_file)) + registered.add(fm.FontProperties(fname=str(font_file)).get_name()) + except Exception: + continue + return sorted(registered) + + def register_fonts(font_dir: str | os.PathLike | None = None) -> list[str]: """Register Barthel brand fonts with matplotlib if available. @@ -86,6 +147,12 @@ def resolve_family(preferred: str = "Basic Sans") -> str: return preferred if is_available(preferred) else DEFAULT_FONT_FAMILY +_VENDORED_PIL_FILES: dict[str, str] = { + "Liberation Sans": "LiberationSans-Regular.ttf", + "Liberation Sans Bold": "LiberationSans-Bold.ttf", + "Liberation Sans Italic": "LiberationSans-Italic.ttf", +} + _BARTHEL_PIL_FILES: dict[str, str] = { "Basic Sans": "BasicSans-Regular.otf", "Basic Sans Bold": "BasicSans-Bold.otf", @@ -95,21 +162,30 @@ def resolve_family(preferred: str = "Basic Sans") -> str: } -def pil_font(size: int, family: str = "Basic Sans", fallback: str = "Arial"): - """Load a PIL ``ImageFont`` with a Barthel-first / system fallback chain. +def pil_font(size: int, family: str = "Liberation Sans", fallback: str = "Arial"): + """Load a PIL ``ImageFont`` with a vendored-first / system fallback chain. Used by raster-output scripts (PNG / GIF / MP4 frames) such as - ``KaryoScope_plot_reads.py``. Tries: + ``KaryoScope_plot_reads.py``. Tries, in order: - 1. ``BARTHEL_FONT_DIR / `` for the requested ``family``. - 2. The system font named ``fallback`` (e.g. ``Arial``). - 3. matplotlib's bundled DejaVu Sans at the requested ``size``. - 4. Pillow's bundled default (always succeeds, but a fixed ~10 px bitmap). + 1. The bundled Liberation Sans file for the requested ``family`` (always present). + 2. ``BARTHEL_FONT_DIR / `` for a requested Barthel ``family``. + 3. The system font named ``fallback`` (e.g. ``Arial``). + 4. matplotlib's bundled DejaVu Sans at the requested ``size``. + 5. Pillow's bundled default (always succeeds, but a fixed ~10 px bitmap). Returns the loaded ``ImageFont`` instance. Never raises. """ from PIL import ImageFont # imported lazily so karyoplot.core.fonts has no PIL dep + vendored_file = _VENDORED_PIL_FILES.get(family) + vendored_dir = _vendored_font_dir() + if vendored_file is not None and vendored_dir is not None: + try: + return ImageFont.truetype(str(vendored_dir / vendored_file), size) + except OSError: + pass + font_file = _BARTHEL_PIL_FILES.get(family) if font_file is not None: path = BARTHEL_FONT_DIR / font_file diff --git a/src/karyoplot/data/fonts/LiberationSans-AUTHORS.txt b/src/karyoplot/data/fonts/LiberationSans-AUTHORS.txt new file mode 100644 index 0000000..23f7966 --- /dev/null +++ b/src/karyoplot/data/fonts/LiberationSans-AUTHORS.txt @@ -0,0 +1,16 @@ +AUTHORS + +Current Contributors (sorted alphabetically): + + - Vishal Vijayraghavan + Project Owner/ Maintainer (Current) + Red Hat, Inc. + +Previous Contributors + - Pravin Satpute + Project Owner/ Maintainer + Red Hat, Inc. + + - Steve Matteson + Original Designer + Ascender, Inc. diff --git a/src/karyoplot/data/fonts/LiberationSans-Bold.ttf b/src/karyoplot/data/fonts/LiberationSans-Bold.ttf new file mode 100644 index 0000000..dc5d57f Binary files /dev/null and b/src/karyoplot/data/fonts/LiberationSans-Bold.ttf differ diff --git a/src/karyoplot/data/fonts/LiberationSans-BoldItalic.ttf b/src/karyoplot/data/fonts/LiberationSans-BoldItalic.ttf new file mode 100644 index 0000000..158488a Binary files /dev/null and b/src/karyoplot/data/fonts/LiberationSans-BoldItalic.ttf differ diff --git a/src/karyoplot/data/fonts/LiberationSans-Italic.ttf b/src/karyoplot/data/fonts/LiberationSans-Italic.ttf new file mode 100644 index 0000000..25970d9 Binary files /dev/null and b/src/karyoplot/data/fonts/LiberationSans-Italic.ttf differ diff --git a/src/karyoplot/data/fonts/LiberationSans-LICENSE.txt b/src/karyoplot/data/fonts/LiberationSans-LICENSE.txt new file mode 100644 index 0000000..aba73e8 --- /dev/null +++ b/src/karyoplot/data/fonts/LiberationSans-LICENSE.txt @@ -0,0 +1,102 @@ +Digitized data copyright (c) 2010 Google Corporation + with Reserved Font Arimo, Tinos and Cousine. +Copyright (c) 2012 Red Hat, Inc. + with Reserved Font Name Liberation. + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + +PREAMBLE The goals of the Open Font License (OFL) are to stimulate +worldwide development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to provide +a free and open framework in which fonts may be shared and improved in +partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. +The fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + + + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. +This may include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components +as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting ? in part or in whole ? +any of the components of the Original Version, by changing formats or +by porting the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical writer +or other person who contributed to the Font Software. + + +PERMISSION & CONDITIONS + +Permission is hereby granted, free of charge, to any person obtaining a +copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components,in + Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, + redistributed and/or sold with any software, provided that each copy + contains the above copyright notice and this license. These can be + included either as stand-alone text files, human-readable headers or + in the appropriate machine-readable metadata fields within text or + binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font + Name(s) unless explicit written permission is granted by the + corresponding Copyright Holder. This restriction only applies to the + primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font + Software shall not be used to promote, endorse or advertise any + Modified Version, except to acknowledge the contribution(s) of the + Copyright Holder(s) and the Author(s) or with their explicit written + permission. + +5) The Font Software, modified or unmodified, in part or in whole, must + be distributed entirely under this license, and must not be distributed + under any other license. The requirement for fonts to remain under + this license does not apply to any document created using the Font + Software. + + + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + + + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER +DEALINGS IN THE FONT SOFTWARE. + diff --git a/src/karyoplot/data/fonts/LiberationSans-Regular.ttf b/src/karyoplot/data/fonts/LiberationSans-Regular.ttf new file mode 100644 index 0000000..e633985 Binary files /dev/null and b/src/karyoplot/data/fonts/LiberationSans-Regular.ttf differ diff --git a/src/karyoplot/mpl/style.py b/src/karyoplot/mpl/style.py index 8ad3431..9c6d84b 100644 --- a/src/karyoplot/mpl/style.py +++ b/src/karyoplot/mpl/style.py @@ -1,10 +1,11 @@ """matplotlib defaults: font registration + dark/light rcParams. -Wraps :mod:`karyoplot.core.fonts` so that the same Basic Sans / Bicyclette -opt-in path is used by both the SVG and matplotlib backends. When the -Barthel fonts aren't available the matplotlib font.family falls back to -``["sans-serif", "DejaVu Sans"]`` (DejaVu provides Greek glyphs needed -for β/gamma labels). +Wraps :mod:`karyoplot.core.fonts`. Figures render in the bundled, freely-licensed +**Liberation Sans** (registered from package data, so they reproduce identically on +any host), with **DejaVu Sans** kept as the secondary family for the Greek letters, +subscripts, and minus sign some labels use (beta/gamma, log2, -log10 axis titles). +If the bundled font can't be loaded, the family falls back to +``["sans-serif", "DejaVu Sans"]``. Examples: >>> from karyoplot.mpl import style @@ -13,7 +14,7 @@ from __future__ import annotations -from ..core.fonts import DEFAULT_FONT_FAMILY, register_fonts +from ..core.fonts import DEFAULT_FONT_FAMILY, VENDORED_FONT_FAMILY, register_vendored_fonts def apply_default_style(dark_mode: bool = False) -> None: @@ -27,9 +28,9 @@ def apply_default_style(dark_mode: bool = False) -> None: """ import matplotlib.pyplot as plt - registered = register_fonts() - if "Basic Sans" in registered: - plt.rcParams["font.family"] = ["Basic Sans", "DejaVu Sans"] + registered = register_vendored_fonts() + if VENDORED_FONT_FAMILY in registered: + plt.rcParams["font.family"] = [VENDORED_FONT_FAMILY, "DejaVu Sans"] else: plt.rcParams["font.family"] = [DEFAULT_FONT_FAMILY, "DejaVu Sans"] diff --git a/tests/test_core.py b/tests/test_core.py index 4cff429..b0d5fd7 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -158,6 +158,42 @@ def test_register_fonts_missing_dir(tmp_path: Path): assert register_fonts(tmp_path / "no_such_dir") == [] +def test_vendored_font_dir_ships_liberation_sans(): + """The bundled OFL font files are present in package data.""" + from karyoplot.core.fonts import _vendored_font_dir + + d = _vendored_font_dir() + assert d is not None and d.is_dir() + names = {p.name for p in d.glob("LiberationSans-*.ttf")} + assert "LiberationSans-Regular.ttf" in names + assert (d / "LiberationSans-LICENSE.txt").exists() + + +def test_register_vendored_fonts_registers_liberation_sans(): + pytest.importorskip("matplotlib") + from karyoplot.core.fonts import ( + VENDORED_FONT_FAMILY, + is_available, + register_vendored_fonts, + ) + + registered = register_vendored_fonts() + assert VENDORED_FONT_FAMILY in registered + assert is_available(VENDORED_FONT_FAMILY) + + +def test_pil_font_prefers_vendored_liberation_sans(): + """The default family loads the bundled scalable Liberation Sans, not a bitmap.""" + pytest.importorskip("matplotlib") + from PIL import ImageFont + + from karyoplot.core.fonts import pil_font + + f = pil_font(24) # default family == "Liberation Sans" + assert isinstance(f, ImageFont.FreeTypeFont) + assert f.getname()[0] == "Liberation Sans" + + def test_default_font_family_is_sans_serif(): from karyoplot.core.fonts import DEFAULT_FONT_FAMILY diff --git a/tests/test_mpl.py b/tests/test_mpl.py index 4204dde..f7c7562 100644 --- a/tests/test_mpl.py +++ b/tests/test_mpl.py @@ -92,6 +92,8 @@ def test_apply_default_style_runs(tmp_path: Path): style.apply_default_style(dark_mode=False) assert plt.rcParams["font.size"] == 10 assert plt.rcParams["axes.spines.top"] is False + # Figures default to the bundled Liberation Sans, with DejaVu kept for Greek/subscripts. + assert list(plt.rcParams["font.family"]) == ["Liberation Sans", "DejaVu Sans"] def test_fg_color():