from __future__ import annotations import hashlib import re from html import escape, unescape from html.parser import HTMLParser from pathlib import Path from urllib.parse import quote, unquote, urlsplit, urlunsplit from .file_versions import atomic_write IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg", ".tif", ".tiff"} def relocate_images(source: str, original: Path, target: Path) -> str: """Copy relative image resources and patch only parsed image destinations. Keep Markdown/code formatting intact. Reference images become inline images so shared reference definitions used by ordinary links need not be changed. """ from markdown_it.rules_inline import image, html_inline from .markdown_renderer import MarkdownRenderer if original.resolve().parent == target.resolve().parent: return source replacements: list[tuple[int, int, str]] = [] copied: dict[str, str] = {} def copy_url(url: str) -> str: if url in copied: return copied[url] parts = urlsplit(url) local = Path(unquote(parts.path)) if not parts.path or parts.scheme or parts.netloc or local.is_absolute(): return url resource = (original.parent / local).resolve() data = resource.read_bytes() # Abort the save on missing/unreadable resources. folder = target.parent / (target.stem + ".assets") destination = folder / (hashlib.sha256(data).hexdigest()[:24] + resource.suffix.lower()) if not destination.exists(): atomic_write(destination, data) relative = quote(destination.relative_to(target.parent).as_posix(), safe="/") copied[url] = urlunsplit(("", "", relative, parts.query, parts.fragment)) return copied[url] class HtmlImages(HTMLParser): def __init__(self, raw: str, offset: int): super().__init__(convert_charrefs=False) self.document_offset = offset self.lines = [0] for match in re.finditer("\n", raw): self.lines.append(match.end()) self.feed(raw) def handle_starttag(self, tag, attrs): if tag != "img": return raw = self.get_starttag_text() # Tokenize attributes rather than matching 'src' inside another value. pattern = r'''([^\s=<>/]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?''' for match in re.finditer(pattern, raw[4:]): if match[1].lower() != "src" or match[2] is None: continue value = match[2] quoted = value[:1] in {"'", '"'} url = unescape(value[1:-1] if quoted else value) moved = copy_url(url) if moved != url: line, column = self.getpos() start = self.document_offset + self.lines[line - 1] + column + 4 + match.start(2) replacements.append((start, start + len(value), '"' + escape(moved, quote=True) + '"')) parser = MarkdownRenderer(original.parent).markdown env = {} tokens = parser.parse(source, env) lines = source.splitlines(keepends=True) offsets = [0] for line in lines: offsets.append(offsets[-1] + len(line)) masked = list(source) excluded = [] for token in tokens: if token.map and token.type in {"fence", "code_block", "math_block", "html_block"}: start, end = (offsets[n] for n in token.map) if token.type == "html_block": HtmlImages(source[start:end], start) excluded.append((start, end)) for ref in env.get("references", {}).values(): excluded.append(tuple(offsets[n] for n in ref["map"])) for start, end in excluded: masked[start:end] = ["\n" if char == "\n" else " " for char in source[start:end]] inline_source = "".join(masked) def capture_image(state, silent): start = state.pos matched = image(state, silent) if matched and not silent and state.src is inline_source: token = state.tokens[-1] url = token.attrGet("src") or "" moved = copy_url(url) if moved != url: label_end = parser.helpers.parseLinkLabel(state, start + 1, False) pos = label_end + 1 if pos < len(source) and source[pos] == "(": pos += 1 while source[pos].isspace(): pos += 1 destination = parser.helpers.parseLinkDestination(source, pos, len(source)) replacements.append((pos, destination.pos, moved)) else: title = token.attrGet("title") suffix = ' "' + title.replace("\\", "\\\\").replace('"', '\\"') + '"' if title else "" replacements.append((start, state.pos, source[start:label_end + 1] + "(" + moved + suffix + ")")) return matched def capture_html(state, silent): start = state.pos matched = html_inline(state, silent) if matched and not silent and state.src is inline_source: HtmlImages(source[start:state.pos], start) return matched parser.inline.ruler.at("image", capture_image) parser.inline.ruler.at("html_inline", capture_html) parser.inline.parse(inline_source, parser, env, []) pieces = [] offset = 0 for start, end, replacement in sorted(replacements): pieces.extend((source[offset:start], replacement)) offset = end pieces.append(source[offset:]) return "".join(pieces) def store_image(document: Path, data: bytes, suffix: str = ".png", label: str = "图片") -> str: suffix = suffix.lower() if suffix not in IMAGE_SUFFIXES or not data: raise ValueError("不支持的图片或图片内容为空") folder = document.parent / (document.stem + ".assets") digest = hashlib.sha256(data).hexdigest()[:24] target = folder / (digest + suffix) if not target.exists(): atomic_write(target, data) relative = quote(target.relative_to(document.parent).as_posix(), safe="/") label = label.replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]").replace("\n", " ") return f"![{label}]({relative})" def image_files(mime: object) -> list[Path]: if not mime.hasUrls(): return [] urls = mime.urls() paths = [Path(url.toLocalFile()) for url in urls if url.isLocalFile()] return paths if len(paths) == len(urls) and all(p.suffix.lower() in IMAGE_SUFFIXES and p.is_file() for p in paths) else [] def image_markdown(mime: object, document: Path) -> str | None: files = image_files(mime) if files: return "\n".join(store_image(document, p.read_bytes(), p.suffix, p.stem) for p in files) if mime.hasImage(): from PySide6.QtCore import QBuffer, QByteArray, QIODevice from PySide6.QtGui import QImage, QPixmap data = mime.imageData() picture = data.toImage() if isinstance(data, QPixmap) else QImage(data) buffer = QBuffer() buffer.open(QIODevice.OpenModeFlag.WriteOnly) if picture.isNull() or not picture.save(buffer, "PNG"): raise ValueError("无法读取剪贴板图片") return store_image(document, bytes(buffer.data()), label="截图") return None