doxtr-html-theme-core 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doxtr_html_theme_core/__init__.py +424 -0
- doxtr_html_theme_core/images.py +814 -0
- doxtr_html_theme_core/layout.html +75 -0
- doxtr_html_theme_core/page.html +4 -0
- doxtr_html_theme_core/partials/drawer.html +40 -0
- doxtr_html_theme_core/partials/footer.html +18 -0
- doxtr_html_theme_core/partials/head.html +33 -0
- doxtr_html_theme_core/partials/header.html +104 -0
- doxtr_html_theme_core/partials/pygments_sync.html +17 -0
- doxtr_html_theme_core/partials/sidebar_left.html +29 -0
- doxtr_html_theme_core/partials/sidebar_right.html +26 -0
- doxtr_html_theme_core/partials/theme_images_sync.html +24 -0
- doxtr_html_theme_core/static/doxtr-core.css +828 -0
- doxtr_html_theme_core/static/doxtr-core.js +469 -0
- doxtr_html_theme_core/static/doxtr-tokens.css +48 -0
- doxtr_html_theme_core/theme.conf +23 -0
- doxtr_html_theme_core-0.1.0.dist-info/METADATA +28 -0
- doxtr_html_theme_core-0.1.0.dist-info/RECORD +22 -0
- doxtr_html_theme_core-0.1.0.dist-info/WHEEL +5 -0
- doxtr_html_theme_core-0.1.0.dist-info/entry_points.txt +2 -0
- doxtr_html_theme_core-0.1.0.dist-info/licenses/LICENSE +21 -0
- doxtr_html_theme_core-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,814 @@
|
|
|
1
|
+
"""Light/dark image variant generation, user variant pairing, and HTML rewriting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fnmatch
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Optional
|
|
12
|
+
|
|
13
|
+
from docutils import nodes
|
|
14
|
+
from sphinx.util import logging
|
|
15
|
+
|
|
16
|
+
from doxtr_theme_core import to_bool
|
|
17
|
+
from doxtr_theme_core.colors import hex_dark_invert, hex_to_rgb
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
RASTER_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"})
|
|
22
|
+
SVG_EXTENSION = ".svg"
|
|
23
|
+
SUPPORTED_EXTENSIONS = RASTER_EXTENSIONS | {SVG_EXTENSION}
|
|
24
|
+
|
|
25
|
+
_OPT_OUT_CLASSES = frozenset({"no-auto-image-adapt", "only-light", "only-dark"})
|
|
26
|
+
_VARIANT_MANIFEST = ".doxtr-image-variants.json"
|
|
27
|
+
|
|
28
|
+
_SAMPLE_SIZE = 64
|
|
29
|
+
_SAT_THRESHOLD = 0.15
|
|
30
|
+
_CHROMATIC_MAX_FRACTION = 0.05
|
|
31
|
+
_NEAR_BLACK_CEILING = 20
|
|
32
|
+
_ALPHA_THRESHOLD = 128
|
|
33
|
+
|
|
34
|
+
_RE_VARIANT_STEM = re.compile(r"^(.*?)(?:([-_])(light|dark))$", re.IGNORECASE)
|
|
35
|
+
_RE_SVG_MASK = re.compile(r"<mask\b[^>]*>.*?</mask>", re.IGNORECASE | re.DOTALL)
|
|
36
|
+
_RE_SVG_DATA_URI = re.compile(r"data:[^\"'()\s<>]+", re.IGNORECASE)
|
|
37
|
+
_RE_XML_COLOR_ATTR = re.compile(
|
|
38
|
+
r"(?<![\w-])(fill|stroke|color|stop-color|flood-color|lighting-color)\s*=\s*([\"'])([^\"']+)\2",
|
|
39
|
+
re.IGNORECASE,
|
|
40
|
+
)
|
|
41
|
+
_RE_CSS_COLOR_PROP = re.compile(
|
|
42
|
+
r"(?<![\w-])(fill|stroke|color|background(?:-color)?|border(?:-(?:top|right|bottom|left))?-color|stop-color|--[a-zA-Z0-9_-]*color[a-zA-Z0-9_-]*)\s*:\s*([^;}\"']+)",
|
|
43
|
+
re.IGNORECASE,
|
|
44
|
+
)
|
|
45
|
+
_RE_COLOR_TOKEN = re.compile(
|
|
46
|
+
r"(#[0-9a-fA-F]{3,8}\b|rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)|\b(?:white|black)\b)",
|
|
47
|
+
re.IGNORECASE,
|
|
48
|
+
)
|
|
49
|
+
_RE_LIGHT_CODE = re.compile(r"(\.light-code\s*\{[^}]*?display\s*:\s*)block(\s*[;}])", re.IGNORECASE)
|
|
50
|
+
_RE_DARK_CODE = re.compile(r"(\.dark-code\s*\{[^}]*?display\s*:\s*)none(\s*[;}])", re.IGNORECASE)
|
|
51
|
+
_RE_COLOR_SCHEME_CSS = re.compile(r"(color-scheme\s*:\s*)light\s+dark", re.IGNORECASE)
|
|
52
|
+
|
|
53
|
+
_RE_HTML_IMG_TAG = re.compile(r"<img\b[^>]*>", re.IGNORECASE | re.DOTALL)
|
|
54
|
+
_RE_HTML_OBJ_TAG = re.compile(r"<object\b[^>]*>", re.IGNORECASE | re.DOTALL)
|
|
55
|
+
_RE_HTML_A_TAG = re.compile(r"<a\b[^>]*>", re.IGNORECASE | re.DOTALL)
|
|
56
|
+
_RE_ATTR_SRC = re.compile(r"(\bsrc\s*=\s*)([\"'])([^\"']+)\2", re.IGNORECASE)
|
|
57
|
+
_RE_ATTR_DATA = re.compile(r"(\bdata\s*=\s*)([\"'])([^\"']+)\2", re.IGNORECASE)
|
|
58
|
+
_RE_ATTR_HREF = re.compile(r"(\bhref\s*=\s*)([\"'])([^\"']+)\2", re.IGNORECASE)
|
|
59
|
+
_RE_ATTR_CLASS = re.compile(r"\bclass\s*=\s*([\"'])([^\"']*)\1", re.IGNORECASE)
|
|
60
|
+
_RE_HTML_REF_IMG = re.compile(r"(?:\b(?:src|data|href)\s*=\s*[\"'])[^\"']*?_images/([^\"'?#]+)", re.IGNORECASE)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _get_pil_image() -> Any:
|
|
64
|
+
try:
|
|
65
|
+
from PIL import Image
|
|
66
|
+
|
|
67
|
+
return Image
|
|
68
|
+
except ImportError:
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _split_variant_stem(stem: str) -> tuple[str, Optional[str]]:
|
|
73
|
+
"""Split ``name-light`` / ``name_dark`` into ``(base_stem, role)``."""
|
|
74
|
+
m = _RE_VARIANT_STEM.match(stem)
|
|
75
|
+
if not m:
|
|
76
|
+
return stem, None
|
|
77
|
+
base, _sep, role = m.groups()
|
|
78
|
+
if not base:
|
|
79
|
+
return stem, None
|
|
80
|
+
return base, role.lower()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _find_sibling_variant(
|
|
84
|
+
base_stem: str,
|
|
85
|
+
ext: str,
|
|
86
|
+
role: str,
|
|
87
|
+
search_dirs: list[Path],
|
|
88
|
+
generated_names: set[str],
|
|
89
|
+
images_dir: Optional[Path] = None,
|
|
90
|
+
) -> Optional[Path]:
|
|
91
|
+
"""Find a user-provided ``-dark``/``_dark`` or ``-light``/``_light`` sibling."""
|
|
92
|
+
candidates = [f"{base_stem}-{role}{ext}", f"{base_stem}_{role}{ext}"]
|
|
93
|
+
for directory in search_dirs:
|
|
94
|
+
if not directory or not directory.is_dir():
|
|
95
|
+
continue
|
|
96
|
+
in_out_dir = images_dir is not None and directory.resolve() == images_dir.resolve()
|
|
97
|
+
for cand_name in candidates:
|
|
98
|
+
if in_out_dir and cand_name in generated_names:
|
|
99
|
+
continue
|
|
100
|
+
cand = directory / cand_name
|
|
101
|
+
if cand.is_file():
|
|
102
|
+
return cand
|
|
103
|
+
return None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _sample_pixels(img: Any) -> list[tuple[int, int, int]]:
|
|
107
|
+
pil_img = _get_pil_image()
|
|
108
|
+
has_trans = img.mode in ("RGBA", "LA", "PA") or (
|
|
109
|
+
img.mode == "P" and "transparency" in getattr(img, "info", {})
|
|
110
|
+
)
|
|
111
|
+
work = img.convert("RGBA") if has_trans else img.convert("RGB")
|
|
112
|
+
small = work.resize((_SAMPLE_SIZE, _SAMPLE_SIZE), pil_img.LANCZOS)
|
|
113
|
+
if has_trans:
|
|
114
|
+
return [(r, g, b) for r, g, b, a in small.getdata() if a > _ALPHA_THRESHOLD]
|
|
115
|
+
return list(small.getdata())
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def is_grayscale_image(img: Any) -> bool:
|
|
119
|
+
"""Return True if at least 95% of opaque non-near-black pixels have low saturation."""
|
|
120
|
+
pixels = _sample_pixels(img)
|
|
121
|
+
total = 0
|
|
122
|
+
chromatic = 0
|
|
123
|
+
for r, g, b in pixels:
|
|
124
|
+
cmax = max(r, g, b)
|
|
125
|
+
if cmax < _NEAR_BLACK_CEILING:
|
|
126
|
+
continue
|
|
127
|
+
total += 1
|
|
128
|
+
if (cmax - min(r, g, b)) / cmax > _SAT_THRESHOLD:
|
|
129
|
+
chromatic += 1
|
|
130
|
+
if total == 0:
|
|
131
|
+
return True
|
|
132
|
+
return (chromatic / total) < _CHROMATIC_MAX_FRACTION
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def is_bright_image(img: Any, threshold: float = 0.65) -> bool:
|
|
136
|
+
"""Return True if mean perceived luminance of opaque pixels exceeds *threshold*."""
|
|
137
|
+
pixels = _sample_pixels(img)
|
|
138
|
+
if not pixels:
|
|
139
|
+
return False
|
|
140
|
+
total_lum = sum((0.2126 * r + 0.7152 * g + 0.0722 * b) / 255.0 for r, g, b in pixels)
|
|
141
|
+
return (total_lum / len(pixels)) > threshold
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _split_alpha(img: Any) -> tuple[Any, Any, bool, str]:
|
|
145
|
+
fmt = img.format or "PNG"
|
|
146
|
+
has_alpha = img.mode in ("RGBA", "LA", "PA") or (
|
|
147
|
+
img.mode == "P" and "transparency" in getattr(img, "info", {})
|
|
148
|
+
)
|
|
149
|
+
if has_alpha:
|
|
150
|
+
rgba = img.convert("RGBA")
|
|
151
|
+
alpha = rgba.getchannel("A")
|
|
152
|
+
return rgba.convert("RGB"), alpha, True, fmt
|
|
153
|
+
return img.convert("RGB"), None, False, fmt
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _save_with_alpha(result: Any, alpha: Any, has_alpha: bool, dst_path: Path, fmt: str) -> None:
|
|
157
|
+
if has_alpha and fmt.upper() in ("JPEG", "JPG", "BMP"):
|
|
158
|
+
fmt = "PNG"
|
|
159
|
+
if has_alpha:
|
|
160
|
+
result = result.convert("RGBA")
|
|
161
|
+
result.putalpha(alpha)
|
|
162
|
+
result.save(dst_path, format=fmt)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _recolour_grayscale_raster(
|
|
166
|
+
img: Any, dst_path: Path, text_rgb: tuple[int, int, int], page_rgb: tuple[int, int, int]
|
|
167
|
+
) -> None:
|
|
168
|
+
pil_img = _get_pil_image()
|
|
169
|
+
rgb_img, alpha, has_alpha, fmt = _split_alpha(img)
|
|
170
|
+
try:
|
|
171
|
+
import numpy as np
|
|
172
|
+
|
|
173
|
+
arr = np.array(rgb_img, dtype=np.float32)
|
|
174
|
+
lum = arr.mean(axis=2, keepdims=True) / 255.0
|
|
175
|
+
t = np.array(text_rgb, dtype=np.float32)
|
|
176
|
+
p = np.array(page_rgb, dtype=np.float32)
|
|
177
|
+
out = np.clip(np.round(t * (1.0 - lum) + p * lum), 0, 255).astype(np.uint8)
|
|
178
|
+
result = pil_img.fromarray(out, mode="RGB")
|
|
179
|
+
except ImportError:
|
|
180
|
+
new_pixels = []
|
|
181
|
+
for r_val, g_val, b_val in rgb_img.getdata():
|
|
182
|
+
lum = (r_val + g_val + b_val) / (3.0 * 255.0)
|
|
183
|
+
new_pixels.append((
|
|
184
|
+
max(0, min(255, round(text_rgb[0] * (1.0 - lum) + page_rgb[0] * lum))),
|
|
185
|
+
max(0, min(255, round(text_rgb[1] * (1.0 - lum) + page_rgb[1] * lum))),
|
|
186
|
+
max(0, min(255, round(text_rgb[2] * (1.0 - lum) + page_rgb[2] * lum))),
|
|
187
|
+
))
|
|
188
|
+
result = pil_img.new("RGB", rgb_img.size)
|
|
189
|
+
result.putdata(new_pixels)
|
|
190
|
+
_save_with_alpha(result, alpha, has_alpha, dst_path, fmt)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _invert_bright_color_raster(
|
|
194
|
+
img: Any, dst_path: Path, text_rgb: tuple[int, int, int], page_rgb: tuple[int, int, int]
|
|
195
|
+
) -> None:
|
|
196
|
+
pil_img = _get_pil_image()
|
|
197
|
+
rgb_img, alpha, has_alpha, fmt = _split_alpha(img)
|
|
198
|
+
l_text = (max(text_rgb) + min(text_rgb)) / (2.0 * 255.0)
|
|
199
|
+
l_page = (max(page_rgb) + min(page_rgb)) / (2.0 * 255.0)
|
|
200
|
+
invert_peak = l_text
|
|
201
|
+
invert_slope = l_text - l_page
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
import numpy as np
|
|
205
|
+
|
|
206
|
+
arr = np.array(rgb_img, dtype=np.float32) / 255.0
|
|
207
|
+
cmax = arr.max(axis=2)
|
|
208
|
+
cmin = arr.min(axis=2)
|
|
209
|
+
delta = cmax - cmin
|
|
210
|
+
lum = (cmax + cmin) / 2.0
|
|
211
|
+
sat = np.zeros_like(lum)
|
|
212
|
+
mask = delta > 0
|
|
213
|
+
low = lum <= 0.5
|
|
214
|
+
sat[mask & low] = delta[mask & low] / np.maximum(cmax[mask & low] + cmin[mask & low], 1e-6)
|
|
215
|
+
sat[mask & ~low] = delta[mask & ~low] / np.maximum(
|
|
216
|
+
2.0 - cmax[mask & ~low] - cmin[mask & ~low], 1e-6
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
hue = np.zeros_like(lum)
|
|
220
|
+
r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2]
|
|
221
|
+
rm = mask & (cmax == r)
|
|
222
|
+
hue[rm] = ((g[rm] - b[rm]) / delta[rm]) % 6.0
|
|
223
|
+
gm = mask & (cmax == g)
|
|
224
|
+
hue[gm] = ((b[gm] - r[gm]) / delta[gm]) + 2.0
|
|
225
|
+
bm = mask & (cmax == b)
|
|
226
|
+
hue[bm] = ((r[bm] - g[bm]) / delta[bm]) + 4.0
|
|
227
|
+
hue = hue / 6.0
|
|
228
|
+
|
|
229
|
+
l_new = np.clip(invert_peak - (lum * invert_slope), 0.0, 1.0)
|
|
230
|
+
chroma = (1.0 - np.abs(2.0 * l_new - 1.0)) * sat
|
|
231
|
+
x_val = chroma * (1.0 - np.abs((hue * 6.0) % 2.0 - 1.0))
|
|
232
|
+
m_val = l_new - chroma / 2.0
|
|
233
|
+
h6 = (hue * 6.0).astype(np.int32) % 6
|
|
234
|
+
out = np.zeros_like(arr)
|
|
235
|
+
sectors = [
|
|
236
|
+
(chroma, x_val, None),
|
|
237
|
+
(x_val, chroma, None),
|
|
238
|
+
(None, chroma, x_val),
|
|
239
|
+
(None, x_val, chroma),
|
|
240
|
+
(x_val, None, chroma),
|
|
241
|
+
(chroma, None, x_val),
|
|
242
|
+
]
|
|
243
|
+
for idx, (c1, c2, c3) in enumerate(sectors):
|
|
244
|
+
sec = h6 == idx
|
|
245
|
+
if c1 is not None:
|
|
246
|
+
out[:, :, 0][sec] = c1[sec]
|
|
247
|
+
if c2 is not None:
|
|
248
|
+
out[:, :, 1][sec] = c2[sec]
|
|
249
|
+
if c3 is not None:
|
|
250
|
+
out[:, :, 2][sec] = c3[sec]
|
|
251
|
+
out = np.clip((out + m_val[:, :, np.newaxis]) * 255.0, 0, 255).astype(np.uint8)
|
|
252
|
+
result = pil_img.fromarray(out, mode="RGB")
|
|
253
|
+
except ImportError:
|
|
254
|
+
import colorsys
|
|
255
|
+
|
|
256
|
+
new_pixels = []
|
|
257
|
+
for r_val, g_val, b_val in rgb_img.getdata():
|
|
258
|
+
h, lum, s = colorsys.rgb_to_hls(r_val / 255.0, g_val / 255.0, b_val / 255.0)
|
|
259
|
+
l_new = max(0.0, min(1.0, invert_peak - (lum * invert_slope)))
|
|
260
|
+
nr, ng, nb = colorsys.hls_to_rgb(h, l_new, s)
|
|
261
|
+
new_pixels.append((
|
|
262
|
+
max(0, min(255, round(nr * 255))),
|
|
263
|
+
max(0, min(255, round(ng * 255))),
|
|
264
|
+
max(0, min(255, round(nb * 255))),
|
|
265
|
+
))
|
|
266
|
+
result = pil_img.new("RGB", rgb_img.size)
|
|
267
|
+
result.putdata(new_pixels)
|
|
268
|
+
|
|
269
|
+
_save_with_alpha(result, alpha, has_alpha, dst_path, fmt)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def generate_dark_raster(
|
|
273
|
+
src_path: Path,
|
|
274
|
+
dst_path: Path,
|
|
275
|
+
text_hex: str,
|
|
276
|
+
page_hex: str,
|
|
277
|
+
brightness_threshold: float = 0.65,
|
|
278
|
+
) -> bool:
|
|
279
|
+
"""Create a dark-mode raster image when source is line-art or bright-background."""
|
|
280
|
+
pil_img = _get_pil_image()
|
|
281
|
+
if pil_img is None:
|
|
282
|
+
return False
|
|
283
|
+
text_rgb = hex_to_rgb(text_hex)
|
|
284
|
+
page_rgb = hex_to_rgb(page_hex)
|
|
285
|
+
try:
|
|
286
|
+
with pil_img.open(src_path) as img:
|
|
287
|
+
img.load()
|
|
288
|
+
if is_grayscale_image(img):
|
|
289
|
+
_recolour_grayscale_raster(img, dst_path, text_rgb, page_rgb)
|
|
290
|
+
return True
|
|
291
|
+
if is_bright_image(img, threshold=brightness_threshold):
|
|
292
|
+
_invert_bright_color_raster(img, dst_path, text_rgb, page_rgb)
|
|
293
|
+
return True
|
|
294
|
+
except Exception as exc:
|
|
295
|
+
logger.warning("[Doxtr HTML Images] Failed processing raster %s: %s", src_path.name, exc)
|
|
296
|
+
return False
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _resolve_light_dark_css(text: str, mode: str) -> str:
|
|
300
|
+
"""Resolve CSS ``light-dark(lightVal, darkVal)`` calls with balanced parentheses."""
|
|
301
|
+
out: list[str] = []
|
|
302
|
+
idx = 0
|
|
303
|
+
lower = text.lower()
|
|
304
|
+
needle = "light-dark("
|
|
305
|
+
while idx < len(text):
|
|
306
|
+
pos = lower.find(needle, idx)
|
|
307
|
+
if pos == -1:
|
|
308
|
+
out.append(text[idx:])
|
|
309
|
+
break
|
|
310
|
+
out.append(text[idx:pos])
|
|
311
|
+
cursor = pos + len(needle)
|
|
312
|
+
depth = 1
|
|
313
|
+
comma_pos = -1
|
|
314
|
+
while cursor < len(text) and depth > 0:
|
|
315
|
+
ch = text[cursor]
|
|
316
|
+
if ch == "(":
|
|
317
|
+
depth += 1
|
|
318
|
+
elif ch == ")":
|
|
319
|
+
depth -= 1
|
|
320
|
+
if depth == 0:
|
|
321
|
+
break
|
|
322
|
+
elif ch == "," and depth == 1 and comma_pos == -1:
|
|
323
|
+
comma_pos = cursor
|
|
324
|
+
cursor += 1
|
|
325
|
+
if depth != 0 or comma_pos == -1:
|
|
326
|
+
out.append(text[pos : pos + len(needle)])
|
|
327
|
+
idx = pos + len(needle)
|
|
328
|
+
continue
|
|
329
|
+
light_val = text[pos + len(needle) : comma_pos].strip()
|
|
330
|
+
dark_val = text[comma_pos + 1 : cursor].strip()
|
|
331
|
+
out.append(dark_val if mode == "dark" else light_val)
|
|
332
|
+
idx = cursor + 1
|
|
333
|
+
rendered = "".join(out)
|
|
334
|
+
return _RE_COLOR_SCHEME_CSS.sub(lambda m: f"{m.group(1)}{mode}", rendered)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _invert_single_color_token(token: str, text_hex: str, page_hex: str) -> str:
|
|
338
|
+
low = token.strip().lower()
|
|
339
|
+
if low in ("white", "#fff", "#ffffff", "rgb(255,255,255)") or re.fullmatch(
|
|
340
|
+
r"rgb\(\s*255\s*,\s*255\s*,\s*255\s*\)", low
|
|
341
|
+
):
|
|
342
|
+
return page_hex
|
|
343
|
+
if low in ("black", "#000", "#000000", "rgb(0,0,0)") or re.fullmatch(
|
|
344
|
+
r"rgb\(\s*0\s*,\s*0\s*,\s*0\s*\)", low
|
|
345
|
+
):
|
|
346
|
+
return text_hex
|
|
347
|
+
if low.startswith("rgb("):
|
|
348
|
+
nums = [int(n) for n in re.findall(r"\d+", low)]
|
|
349
|
+
if len(nums) == 3:
|
|
350
|
+
as_hex = f"#{nums[0]:02X}{nums[1]:02X}{nums[2]:02X}"
|
|
351
|
+
return hex_dark_invert(as_hex) or token
|
|
352
|
+
return token
|
|
353
|
+
if low.startswith("#"):
|
|
354
|
+
clean = low[1:]
|
|
355
|
+
if len(clean) == 3:
|
|
356
|
+
clean = "".join(c * 2 for c in clean)
|
|
357
|
+
if clean == "ffffff":
|
|
358
|
+
return page_hex
|
|
359
|
+
if clean == "000000":
|
|
360
|
+
return text_hex
|
|
361
|
+
if len(clean) in (6, 8):
|
|
362
|
+
return hex_dark_invert(f"#{clean}") or token
|
|
363
|
+
return token
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _transform_static_svg_dark(svg_text: str, text_hex: str, page_hex: str) -> str:
|
|
367
|
+
"""Invert colors inside a static SVG while preserving masks and ``data:`` URIs."""
|
|
368
|
+
saved: list[str] = []
|
|
369
|
+
|
|
370
|
+
def _stash(match: re.Match[str]) -> str:
|
|
371
|
+
key = f"__DOXTR_SVG_KEEP_{len(saved)}__"
|
|
372
|
+
saved.append(match.group(0))
|
|
373
|
+
return key
|
|
374
|
+
|
|
375
|
+
work = _RE_SVG_MASK.sub(_stash, svg_text)
|
|
376
|
+
work = _RE_SVG_DATA_URI.sub(_stash, work)
|
|
377
|
+
|
|
378
|
+
def _rewrite_value(val: str) -> str:
|
|
379
|
+
return _RE_COLOR_TOKEN.sub(
|
|
380
|
+
lambda m: _invert_single_color_token(m.group(0), text_hex, page_hex), val
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
work = _RE_XML_COLOR_ATTR.sub(
|
|
384
|
+
lambda m: f"{m.group(1)}={m.group(2)}{_rewrite_value(m.group(3))}{m.group(2)}", work
|
|
385
|
+
)
|
|
386
|
+
work = _RE_CSS_COLOR_PROP.sub(
|
|
387
|
+
lambda m: f"{m.group(1)}:{_rewrite_value(m.group(2))}", work
|
|
388
|
+
)
|
|
389
|
+
work = _RE_LIGHT_CODE.sub(r"\1none\2", work)
|
|
390
|
+
work = _RE_DARK_CODE.sub(r"\1block\2", work)
|
|
391
|
+
|
|
392
|
+
for idx, original in enumerate(saved):
|
|
393
|
+
work = work.replace(f"__DOXTR_SVG_KEEP_{idx}__", original)
|
|
394
|
+
return work
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def generate_svg_variants(
|
|
398
|
+
src_path: Path,
|
|
399
|
+
light_dst: Path,
|
|
400
|
+
dark_dst: Path,
|
|
401
|
+
text_hex: str,
|
|
402
|
+
page_hex: str,
|
|
403
|
+
) -> bool:
|
|
404
|
+
"""Emit explicit light/dark SVGs for ``light-dark()`` or static color SVGs."""
|
|
405
|
+
try:
|
|
406
|
+
orig_text = src_path.read_text(encoding="utf-8", errors="ignore")
|
|
407
|
+
except OSError:
|
|
408
|
+
return False
|
|
409
|
+
|
|
410
|
+
if "light-dark(" in orig_text.lower():
|
|
411
|
+
light_svg = _resolve_light_dark_css(orig_text, "light")
|
|
412
|
+
dark_svg = _resolve_light_dark_css(orig_text, "dark")
|
|
413
|
+
else:
|
|
414
|
+
light_svg = orig_text
|
|
415
|
+
dark_svg = _transform_static_svg_dark(orig_text, text_hex, page_hex)
|
|
416
|
+
|
|
417
|
+
if dark_svg == orig_text and light_svg == orig_text:
|
|
418
|
+
return False
|
|
419
|
+
|
|
420
|
+
light_dst.write_text(light_svg, encoding="utf-8")
|
|
421
|
+
dark_dst.write_text(dark_svg, encoding="utf-8")
|
|
422
|
+
return True
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _is_excluded(filename: str, patterns: list[str], skip_names: set[str]) -> bool:
|
|
426
|
+
if filename in skip_names:
|
|
427
|
+
return True
|
|
428
|
+
return any(fnmatch.fnmatch(filename, pat) for pat in patterns)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _load_generated_manifest(images_dir: Path) -> set[str]:
|
|
432
|
+
manifest = images_dir / _VARIANT_MANIFEST
|
|
433
|
+
if not manifest.is_file():
|
|
434
|
+
return set()
|
|
435
|
+
try:
|
|
436
|
+
data = json.loads(manifest.read_text(encoding="utf-8"))
|
|
437
|
+
return set(data.get("generated", []))
|
|
438
|
+
except Exception:
|
|
439
|
+
return set()
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _save_generated_manifest(images_dir: Path, generated: set[str]) -> None:
|
|
443
|
+
if not generated:
|
|
444
|
+
return
|
|
445
|
+
manifest = images_dir / _VARIANT_MANIFEST
|
|
446
|
+
manifest.write_text(json.dumps({"generated": sorted(generated)}), encoding="utf-8")
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _discover_html_referenced_images(outdir: Path) -> set[str]:
|
|
450
|
+
referenced: set[str] = set()
|
|
451
|
+
for html_file in outdir.rglob("*.html"):
|
|
452
|
+
if any(part in {"_static", "_sources", "_images"} for part in html_file.relative_to(outdir).parts):
|
|
453
|
+
continue
|
|
454
|
+
text = html_file.read_text(encoding="utf-8", errors="ignore")
|
|
455
|
+
for match in _RE_HTML_REF_IMG.findall(text):
|
|
456
|
+
referenced.add(match)
|
|
457
|
+
return referenced
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _build_pair_for_source(
|
|
461
|
+
src_file: Path,
|
|
462
|
+
out_filename: str,
|
|
463
|
+
images_dir: Path,
|
|
464
|
+
search_dirs: list[Path],
|
|
465
|
+
generated_names: set[str],
|
|
466
|
+
text_hex: str,
|
|
467
|
+
page_hex: str,
|
|
468
|
+
brightness_threshold: float,
|
|
469
|
+
new_generated: set[str],
|
|
470
|
+
) -> Optional[tuple[str, str]]:
|
|
471
|
+
"""Build or pair ``(light_name, dark_name)`` inside ``images_dir``."""
|
|
472
|
+
stem, ext = os.path.splitext(out_filename)
|
|
473
|
+
ext_lower = ext.lower()
|
|
474
|
+
if ext_lower not in SUPPORTED_EXTENSIONS:
|
|
475
|
+
return None
|
|
476
|
+
|
|
477
|
+
base_stem, role = _split_variant_stem(stem)
|
|
478
|
+
if out_filename in generated_names:
|
|
479
|
+
return None
|
|
480
|
+
|
|
481
|
+
if role == "dark":
|
|
482
|
+
light_sibling = _find_sibling_variant(
|
|
483
|
+
base_stem, ext, "light", search_dirs, generated_names, images_dir=images_dir
|
|
484
|
+
)
|
|
485
|
+
if light_sibling is None:
|
|
486
|
+
plain_candidates = [d / f"{base_stem}{ext}" for d in search_dirs if d and d.is_dir()]
|
|
487
|
+
light_sibling = next((c for c in plain_candidates if c.is_file()), None)
|
|
488
|
+
if light_sibling is None:
|
|
489
|
+
return None
|
|
490
|
+
light_name = f"{base_stem}-light{ext}"
|
|
491
|
+
dark_name = f"{base_stem}-dark{ext}"
|
|
492
|
+
light_dst = images_dir / light_name
|
|
493
|
+
dark_dst = images_dir / dark_name
|
|
494
|
+
if light_sibling.resolve() != light_dst.resolve():
|
|
495
|
+
shutil.copy2(light_sibling, light_dst)
|
|
496
|
+
new_generated.add(light_name)
|
|
497
|
+
if src_file.resolve() != dark_dst.resolve():
|
|
498
|
+
shutil.copy2(src_file, dark_dst)
|
|
499
|
+
new_generated.add(dark_name)
|
|
500
|
+
return light_name, dark_name
|
|
501
|
+
|
|
502
|
+
# Role is None (base image) or 'light'
|
|
503
|
+
user_dark = _find_sibling_variant(
|
|
504
|
+
base_stem, ext, "dark", search_dirs, generated_names, images_dir=images_dir
|
|
505
|
+
)
|
|
506
|
+
light_name = f"{base_stem}-light{ext}"
|
|
507
|
+
dark_name = f"{base_stem}-dark{ext}"
|
|
508
|
+
light_dst = images_dir / light_name
|
|
509
|
+
dark_dst = images_dir / dark_name
|
|
510
|
+
|
|
511
|
+
if user_dark is not None:
|
|
512
|
+
user_light = (
|
|
513
|
+
src_file
|
|
514
|
+
if role == "light"
|
|
515
|
+
else (
|
|
516
|
+
_find_sibling_variant(
|
|
517
|
+
base_stem, ext, "light", search_dirs, generated_names, images_dir=images_dir
|
|
518
|
+
)
|
|
519
|
+
or src_file
|
|
520
|
+
)
|
|
521
|
+
)
|
|
522
|
+
if user_light.resolve() != light_dst.resolve():
|
|
523
|
+
shutil.copy2(user_light, light_dst)
|
|
524
|
+
new_generated.add(light_name)
|
|
525
|
+
if user_dark.resolve() != dark_dst.resolve():
|
|
526
|
+
shutil.copy2(user_dark, dark_dst)
|
|
527
|
+
new_generated.add(dark_name)
|
|
528
|
+
return light_name, dark_name
|
|
529
|
+
|
|
530
|
+
# No user-provided dark sibling: auto-generate when possible
|
|
531
|
+
if ext_lower == SVG_EXTENSION:
|
|
532
|
+
created = generate_svg_variants(src_file, light_dst, dark_dst, text_hex, page_hex)
|
|
533
|
+
if not created:
|
|
534
|
+
return None
|
|
535
|
+
if src_file.resolve() != light_dst.resolve():
|
|
536
|
+
new_generated.add(light_name)
|
|
537
|
+
new_generated.add(dark_name)
|
|
538
|
+
return light_name, dark_name
|
|
539
|
+
|
|
540
|
+
if ext_lower in RASTER_EXTENSIONS:
|
|
541
|
+
if generate_dark_raster(
|
|
542
|
+
src_file,
|
|
543
|
+
dark_dst,
|
|
544
|
+
text_hex,
|
|
545
|
+
page_hex,
|
|
546
|
+
brightness_threshold=brightness_threshold,
|
|
547
|
+
):
|
|
548
|
+
if src_file.resolve() != light_dst.resolve():
|
|
549
|
+
shutil.copy2(src_file, light_dst)
|
|
550
|
+
new_generated.add(light_name)
|
|
551
|
+
new_generated.add(dark_name)
|
|
552
|
+
return light_name, dark_name
|
|
553
|
+
|
|
554
|
+
return None
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _tag_has_opt_out(tag_text: str) -> bool:
|
|
558
|
+
cls_m = _RE_ATTR_CLASS.search(tag_text)
|
|
559
|
+
if not cls_m:
|
|
560
|
+
return False
|
|
561
|
+
classes = set(cls_m.group(2).split())
|
|
562
|
+
return bool(classes & _OPT_OUT_CLASSES)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _rewrite_asset_tag(
|
|
566
|
+
tag_text: str,
|
|
567
|
+
attr_re: re.Pattern[str],
|
|
568
|
+
folder_name: str,
|
|
569
|
+
light_attr: str,
|
|
570
|
+
dark_attr: str,
|
|
571
|
+
variant_map: dict[str, tuple[str, str]],
|
|
572
|
+
) -> str:
|
|
573
|
+
if f"{dark_attr}=" in tag_text or _tag_has_opt_out(tag_text):
|
|
574
|
+
return tag_text
|
|
575
|
+
m = attr_re.search(tag_text)
|
|
576
|
+
if not m:
|
|
577
|
+
return tag_text
|
|
578
|
+
raw_val = m.group(3)
|
|
579
|
+
marker = f"{folder_name}/"
|
|
580
|
+
pos = raw_val.find(marker)
|
|
581
|
+
if pos == -1:
|
|
582
|
+
return tag_text
|
|
583
|
+
prefix = raw_val[: pos + len(marker)]
|
|
584
|
+
rel_tail = raw_val[pos + len(marker) :].split("?", 1)[0].split("#", 1)[0]
|
|
585
|
+
pair = variant_map.get(rel_tail)
|
|
586
|
+
if not pair:
|
|
587
|
+
# Also resolve previously rewritten -light variants cleanly
|
|
588
|
+
stem, ext = os.path.splitext(rel_tail)
|
|
589
|
+
base_stem, role = _split_variant_stem(stem)
|
|
590
|
+
if role == "light":
|
|
591
|
+
pair = variant_map.get(f"{base_stem}{ext}") or variant_map.get(rel_tail)
|
|
592
|
+
if not pair:
|
|
593
|
+
return tag_text
|
|
594
|
+
light_name, dark_name = pair
|
|
595
|
+
light_url = f"{prefix}{light_name}"
|
|
596
|
+
dark_url = f"{prefix}{dark_name}"
|
|
597
|
+
rewritten = (
|
|
598
|
+
tag_text[: m.start()]
|
|
599
|
+
+ f"{m.group(1)}{m.group(2)}{light_url}{m.group(2)}"
|
|
600
|
+
+ tag_text[m.end() :]
|
|
601
|
+
)
|
|
602
|
+
extra = f' {light_attr}="{light_url}" {dark_attr}="{dark_url}"'
|
|
603
|
+
if rewritten.endswith("/>"):
|
|
604
|
+
return rewritten[:-2].rstrip() + extra + " />"
|
|
605
|
+
return rewritten[:-1] + extra + ">"
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def rewrite_html_files(
|
|
609
|
+
outdir: Path,
|
|
610
|
+
image_variants: dict[str, tuple[str, str]],
|
|
611
|
+
static_variants: Optional[dict[str, tuple[str, str]]] = None,
|
|
612
|
+
) -> None:
|
|
613
|
+
"""Attach ``data-doxtr-light-*`` and ``data-doxtr-dark-*`` attributes in built HTML."""
|
|
614
|
+
static_variants = static_variants or {}
|
|
615
|
+
if not image_variants and not static_variants:
|
|
616
|
+
return
|
|
617
|
+
|
|
618
|
+
for html_file in outdir.rglob("*.html"):
|
|
619
|
+
if any(part in {"_static", "_sources", "_images"} for part in html_file.relative_to(outdir).parts):
|
|
620
|
+
continue
|
|
621
|
+
orig = html_file.read_text(encoding="utf-8", errors="ignore")
|
|
622
|
+
updated = orig
|
|
623
|
+
|
|
624
|
+
if image_variants:
|
|
625
|
+
updated = _RE_HTML_IMG_TAG.sub(
|
|
626
|
+
lambda m: _rewrite_asset_tag(
|
|
627
|
+
m.group(0),
|
|
628
|
+
_RE_ATTR_SRC,
|
|
629
|
+
"_images",
|
|
630
|
+
"data-doxtr-light-src",
|
|
631
|
+
"data-doxtr-dark-src",
|
|
632
|
+
image_variants,
|
|
633
|
+
),
|
|
634
|
+
updated,
|
|
635
|
+
)
|
|
636
|
+
updated = _RE_HTML_OBJ_TAG.sub(
|
|
637
|
+
lambda m: _rewrite_asset_tag(
|
|
638
|
+
m.group(0),
|
|
639
|
+
_RE_ATTR_DATA,
|
|
640
|
+
"_images",
|
|
641
|
+
"data-doxtr-light-src",
|
|
642
|
+
"data-doxtr-dark-src",
|
|
643
|
+
image_variants,
|
|
644
|
+
),
|
|
645
|
+
updated,
|
|
646
|
+
)
|
|
647
|
+
|
|
648
|
+
def _rewrite_link(match: re.Match[str]) -> str:
|
|
649
|
+
tag = match.group(0)
|
|
650
|
+
cls_m = _RE_ATTR_CLASS.search(tag)
|
|
651
|
+
if not cls_m or "image-reference" not in cls_m.group(2).split():
|
|
652
|
+
return tag
|
|
653
|
+
return _rewrite_asset_tag(
|
|
654
|
+
tag,
|
|
655
|
+
_RE_ATTR_HREF,
|
|
656
|
+
"_images",
|
|
657
|
+
"data-doxtr-light-href",
|
|
658
|
+
"data-doxtr-dark-href",
|
|
659
|
+
image_variants,
|
|
660
|
+
)
|
|
661
|
+
|
|
662
|
+
updated = _RE_HTML_A_TAG.sub(_rewrite_link, updated)
|
|
663
|
+
|
|
664
|
+
if static_variants:
|
|
665
|
+
updated = _RE_HTML_IMG_TAG.sub(
|
|
666
|
+
lambda m: _rewrite_asset_tag(
|
|
667
|
+
m.group(0),
|
|
668
|
+
_RE_ATTR_SRC,
|
|
669
|
+
"_static",
|
|
670
|
+
"data-doxtr-light-src",
|
|
671
|
+
"data-doxtr-dark-src",
|
|
672
|
+
static_variants,
|
|
673
|
+
),
|
|
674
|
+
updated,
|
|
675
|
+
)
|
|
676
|
+
|
|
677
|
+
if updated != orig:
|
|
678
|
+
html_file.write_text(updated, encoding="utf-8")
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def collect_html_image_opt_outs(app: Any, doctree: Any) -> None:
|
|
682
|
+
"""Record image URIs carrying ``no-auto-image-adapt``, ``only-light``, or ``only-dark``."""
|
|
683
|
+
skip: set[str] = set(getattr(app.env, "_doxtr_html_image_skip", set()) or set())
|
|
684
|
+
for node in doctree.findall(nodes.image):
|
|
685
|
+
uri = str(node.get("uri", "") or "")
|
|
686
|
+
if not uri or "://" in uri or uri.startswith("data:"):
|
|
687
|
+
continue
|
|
688
|
+
node_classes = set(node.get("classes", []) or [])
|
|
689
|
+
parent_classes = set(getattr(node.parent, "get", lambda *_: [])("classes", []) or [])
|
|
690
|
+
if (node_classes | parent_classes) & _OPT_OUT_CLASSES:
|
|
691
|
+
skip.add(os.path.basename(uri))
|
|
692
|
+
app.env._doxtr_html_image_skip = skip
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def process_html_theme_images(app: Any, dark_palette: dict[str, str]) -> dict[str, tuple[str, str]]:
|
|
696
|
+
"""Generate/pair ``-light``/``-dark`` images and rewrite built HTML attributes."""
|
|
697
|
+
if not to_bool(getattr(app.config, "doxtr_html_dark_images", True), default=True):
|
|
698
|
+
return {}
|
|
699
|
+
|
|
700
|
+
outdir = Path(app.outdir)
|
|
701
|
+
images_dir = outdir / "_images"
|
|
702
|
+
srcdir = Path(str(app.srcdir))
|
|
703
|
+
text_hex = str(dark_palette.get("text") or "#DBDBDB")
|
|
704
|
+
page_hex = str(dark_palette.get("page") or "#242424")
|
|
705
|
+
threshold = float(getattr(app.config, "doxtr_dark_image_brightness_threshold", 0.65) or 0.65)
|
|
706
|
+
|
|
707
|
+
exclude_patterns = list(
|
|
708
|
+
getattr(app.config, "doxtr_image_exclude_patterns", None)
|
|
709
|
+
or getattr(app.config, "doxtr_dark_image_exclude_patterns", None)
|
|
710
|
+
or []
|
|
711
|
+
)
|
|
712
|
+
skip_names: set[str] = set(getattr(app.env, "_doxtr_html_image_skip", set()) or set())
|
|
713
|
+
skip_names.update(
|
|
714
|
+
os.path.basename(u) for u in (getattr(app.env, "_doxtr_image_skip", set()) or set())
|
|
715
|
+
)
|
|
716
|
+
|
|
717
|
+
generated_before = _load_generated_manifest(images_dir) if images_dir.is_dir() else set()
|
|
718
|
+
new_generated: set[str] = set(generated_before)
|
|
719
|
+
image_variants: dict[str, tuple[str, str]] = {}
|
|
720
|
+
|
|
721
|
+
if images_dir.is_dir():
|
|
722
|
+
# Map output filename -> original source directories from Sphinx env.images
|
|
723
|
+
src_dir_by_out_name: dict[str, list[Path]] = {}
|
|
724
|
+
env_images = getattr(app.env, "images", {}) or {}
|
|
725
|
+
for rel_src_uri, (_docnames, dest_filename) in env_images.items():
|
|
726
|
+
src_candidate = srcdir / rel_src_uri
|
|
727
|
+
dirs = src_dir_by_out_name.setdefault(dest_filename, [])
|
|
728
|
+
if src_candidate.parent not in dirs:
|
|
729
|
+
dirs.append(src_candidate.parent)
|
|
730
|
+
if srcdir not in dirs:
|
|
731
|
+
dirs.append(srcdir)
|
|
732
|
+
|
|
733
|
+
referenced = _discover_html_referenced_images(outdir)
|
|
734
|
+
candidates: set[str] = set(env_images.values() and [v[1] for v in env_images.values()])
|
|
735
|
+
candidates.update(referenced)
|
|
736
|
+
for p in images_dir.iterdir():
|
|
737
|
+
if p.is_file() and p.name != _VARIANT_MANIFEST:
|
|
738
|
+
candidates.add(p.name)
|
|
739
|
+
|
|
740
|
+
ordered_candidates = sorted(
|
|
741
|
+
candidates,
|
|
742
|
+
key=lambda n: (1 if _split_variant_stem(os.path.splitext(n)[0])[1] else 0, n),
|
|
743
|
+
)
|
|
744
|
+
for out_name in ordered_candidates:
|
|
745
|
+
if out_name in generated_before:
|
|
746
|
+
continue
|
|
747
|
+
if _is_excluded(out_name, exclude_patterns, skip_names):
|
|
748
|
+
continue
|
|
749
|
+
out_file = images_dir / out_name
|
|
750
|
+
if not out_file.is_file():
|
|
751
|
+
continue
|
|
752
|
+
|
|
753
|
+
stem, ext = os.path.splitext(out_name)
|
|
754
|
+
base_stem, role = _split_variant_stem(stem)
|
|
755
|
+
if f"{base_stem}{ext}" in image_variants and role in ("light", "dark"):
|
|
756
|
+
continue
|
|
757
|
+
|
|
758
|
+
search_dirs = list(src_dir_by_out_name.get(out_name, [srcdir]))
|
|
759
|
+
search_dirs.append(images_dir)
|
|
760
|
+
pair = _build_pair_for_source(
|
|
761
|
+
out_file,
|
|
762
|
+
out_name,
|
|
763
|
+
images_dir,
|
|
764
|
+
search_dirs,
|
|
765
|
+
generated_before,
|
|
766
|
+
text_hex,
|
|
767
|
+
page_hex,
|
|
768
|
+
threshold,
|
|
769
|
+
new_generated,
|
|
770
|
+
)
|
|
771
|
+
if pair is not None:
|
|
772
|
+
image_variants[out_name] = pair
|
|
773
|
+
image_variants.setdefault(pair[0], pair)
|
|
774
|
+
if role == "light":
|
|
775
|
+
image_variants.setdefault(f"{base_stem}{ext}", pair)
|
|
776
|
+
|
|
777
|
+
_save_generated_manifest(images_dir, new_generated)
|
|
778
|
+
|
|
779
|
+
# Also support user-provided or auto-generated dark logos (default core icon or html_logo) in _static/
|
|
780
|
+
static_variants: dict[str, tuple[str, str]] = {}
|
|
781
|
+
static_dir = outdir / "_static"
|
|
782
|
+
static_logo_candidates: dict[str, Path] = {}
|
|
783
|
+
for dest_name, src_path in (getattr(app, "_doxtr_static_logo_auto_adapt", None) or {}).items():
|
|
784
|
+
if src_path:
|
|
785
|
+
static_logo_candidates[dest_name] = src_path
|
|
786
|
+
html_logo = getattr(app.config, "html_logo", None)
|
|
787
|
+
if html_logo and not str(html_logo).lower().startswith(("http://", "https://", "//", "data:")):
|
|
788
|
+
html_logo_src = Path(app.confdir) / str(html_logo)
|
|
789
|
+
static_logo_candidates.setdefault(os.path.basename(str(html_logo)), html_logo_src)
|
|
790
|
+
|
|
791
|
+
if static_logo_candidates and static_dir.is_dir():
|
|
792
|
+
logo_gen_before = _load_generated_manifest(static_dir)
|
|
793
|
+
logo_gen_after = set(logo_gen_before)
|
|
794
|
+
for logo_name, logo_src in static_logo_candidates.items():
|
|
795
|
+
logo_out = static_dir / logo_name
|
|
796
|
+
if not logo_out.is_file() or _is_excluded(logo_name, exclude_patterns, skip_names):
|
|
797
|
+
continue
|
|
798
|
+
pair = _build_pair_for_source(
|
|
799
|
+
logo_out,
|
|
800
|
+
logo_name,
|
|
801
|
+
static_dir,
|
|
802
|
+
[logo_src.parent, Path(app.confdir), static_dir],
|
|
803
|
+
logo_gen_before,
|
|
804
|
+
text_hex,
|
|
805
|
+
page_hex,
|
|
806
|
+
threshold,
|
|
807
|
+
logo_gen_after,
|
|
808
|
+
)
|
|
809
|
+
if pair is not None:
|
|
810
|
+
static_variants[logo_name] = pair
|
|
811
|
+
_save_generated_manifest(static_dir, logo_gen_after)
|
|
812
|
+
|
|
813
|
+
rewrite_html_files(outdir, image_variants, static_variants)
|
|
814
|
+
return image_variants
|