diff --git a/README.md b/README.md index abfb6a9..6badf7f 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,13 @@ python -m pip install -r requirements.txt ## Web configurator -Emoji in paragraph text, section headings, the table of contents, and document -titles render as inline color images using bundled Twemoji artwork. No emoji font -or network connection is required. Artwork credits and licensing are in +Emoji retain their original Unicode characters in the PDF text stream while +rendering as author-selected fixed-color artwork. Each color emoji has an inline +Type 3 text glyph with a ToUnicode mapping for the exact original sequence +(including skin tones, variation selectors, and joined emoji). Copying or +extracting the surrounding paragraph can therefore recover its Unicode emoji. +Twemoji is bundled by default; other styles require a PNG ZIP pack. Viewer +support for complex Unicode copy/paste varies. Twemoji credits are in [the emoji asset notes](assets/twemoji/README.md). Run the web app: @@ -363,3 +367,21 @@ Enable **Customize positions on the first page** in Letterhead to arrange the ex The editor uses the current page margins and reserves room above the body for visible fields. A positioned addressee appears once. Disabling the editor restores the fixed letterhead layout, while configuration export preserves your custom arrangement for later reuse. This integrates the editor from: https://github.com/PDF-magic/compiler/pull/37 + + +### Author-selected emoji appearance + +Choose --emoji-style from twemoji, fluent, noto, openmoji, blobmoji, emojitwo, +or mutant-standard. Twemoji is the built-in default. For other styles, supply +--emoji-pack /path/to/artwork.zip, upload the ZIP in the web form, or install +the pack at assets/emoji-styles/STYLE/72x72.zip. Individual PNG files are +named by lowercase Unicode codepoints, joined with hyphens for sequences, +such as 1f600.png, 1f44d-1f3fd.png or +1f468-200d-1f469-200d-1f467-200d-1f466.png. Nested ZIP folders are allowed. + +Missing supported emoji fail compilation rather than changing the style. +The author must source artwork and comply with the selected project's license. +Mutant Standard uses a noncommercial license and is not bundled. These images +fix the visual appearance; accompanying Type 3 ToUnicode glyphs preserve the +original emoji as inline selectable text. PDF/A output still needs independent +conformance validation. diff --git a/app.py b/app.py index 9efeb15..289ddc5 100644 --- a/app.py +++ b/app.py @@ -27,6 +27,7 @@ LetterSettings, ) from first_page_layout import FirstPagePdfRenderer, parse_letterhead_layout +from emoji_renderer import EMOJI_STYLES, emoji_preview, validate_emoji_style from pdf_compiler import ADMONITION_DEFAULT_COLORS, ADMONITION_TYPES, LINK_COLOR from pdfa4_export import render_pdf as render_with_format from legal_style_validator import validate_legal_style @@ -162,6 +163,7 @@ def index(): else getattr(TypographySettings.for_style(style), name)) for name in PROFESSIONAL_TYPOGRAPHY } for style in RENDER_STYLES}, + emoji_styles=EMOJI_STYLES, date_formats=DATE_FORMATS, image_treatments=IMAGE_TREATMENTS, page_number_styles=PAGE_NUMBER_STYLES, @@ -177,11 +179,28 @@ def index(): ' \n' ' \n' ' \n' - ' \n', + ' \n' + ' \n', 1, ) +@app.post("/emoji-preview") +def preview_emoji_style(): + selected = request.form.get("emoji_style", "twemoji") + uploaded = request.files.get("emoji_pack") + try: + with TemporaryDirectory(prefix="pdf-emoji-preview-") as temp: + pack = None + if selected != "twemoji" and uploaded and uploaded.filename: + pack = Path(temp) / "style.zip" + uploaded.save(pack) + content = emoji_preview(selected, pack) + return send_file(BytesIO(content), mimetype="image/png") + except ValueError as exc: + return jsonify({"error": str(exc)}), 400 + + @app.post("/validate") def validate_markdown(): markdown, error, source_relative = submitted_markdown() @@ -376,6 +395,17 @@ def metadata_value(name: str) -> str | None: except ValueError as exc: return jsonify({"error": str(exc)}), 400 + emoji_style = request.form.get("emoji_style", "twemoji") + uploaded_emoji = request.files.get("emoji_pack") + emoji_pack = None + if emoji_style != "twemoji" and uploaded_emoji and uploaded_emoji.filename: + emoji_pack = root / "emoji-style.zip" + uploaded_emoji.save(emoji_pack) + try: + validate_emoji_style(emoji_style, emoji_pack) + except ValueError as exc: + return jsonify({"error": str(exc)}), 400 + output = root / "output.pdf" try: renderer = FirstPagePdfRenderer( @@ -394,6 +424,8 @@ def metadata_value(name: str) -> str | None: keywords=metadata_value("keywords"), smart_quotes=truthy("smart_quotes"), quote_inline_number_footnotes=truthy("quote_inline_number_footnotes"), + emoji_style=emoji_style, + emoji_pack=emoji_pack, underline_links=truthy("underline_links"), hide_url_scheme=truthy("hide_url_scheme"), link_color=link_color, diff --git a/configured_renderer.py b/configured_renderer.py index d2c2805..5e293a5 100644 --- a/configured_renderer.py +++ b/configured_renderer.py @@ -28,7 +28,7 @@ ) from pdf_compiler import PdfRenderer, RefParagraph, TrackingDoc, advance_code_fence, alpha, compiler_creator, roman -from emoji_renderer import EmojiParagraph as Paragraph +from emoji_renderer import EmojiParagraph as Paragraph, render_with_emoji_style from document_assets import resolve_document_image @@ -996,6 +996,7 @@ def document(self, path: Path) -> SectionTrackingDoc: author=self.author, ) + @render_with_emoji_style def build(self) -> tuple[int, int, int]: """Render twice so a visible TOC can use the final section page locations.""" self.output.parent.mkdir(parents=True, exist_ok=True) diff --git a/docs/emoji-text-plan.md b/docs/emoji-text-plan.md new file mode 100644 index 0000000..017925c --- /dev/null +++ b/docs/emoji-text-plan.md @@ -0,0 +1,33 @@ +# Author-selected color emoji with Unicode text + +The author chooses a fixed PNG artwork style, while the PDF retains the +original Unicode emoji in the paragraph's searchable and copyable text stream. +The selected art draws in full color; a companion blank Type 3 glyph has a +ToUnicode CMap that maps one character code to the original Unicode sequence. +The glyph sits in the same ReportLab paragraph text run at the image position, +not in a separate end-of-page text layer. This also preserves presentation +selectors, skin-tone modifiers, flags, and zero-width joiners in the mapping. + +Supported styles: +- Twemoji (bundled and default) +- Fluent Emoji +- Noto Emoji +- OpenMoji +- Blobmoji +- Emojitwo +- Mutant Standard + +Alternative artwork is not bundled because of size, availability and licensing. +Supply a codepoint-named PNG ZIP through the web form or CLI, or install it at +assets/emoji-styles/STYLE/72x72.zip. The author must obtain the selected art +and comply with its license (Mutant Standard is noncommercial). + +Both PDF rendering passes use a request-local style. The completed PDF is +postprocessed atomically to install Type 3 font objects and /ToUnicode mappings. +Other author-supplied images are unaffected. Missing recognized emoji in an +alternate pack fail instead of switching to a different style. + +Limitations: Unicode emoji newer than both emoji catalogs may be unrecognized. +Uploaded packs are not stored in exported configuration files. Extraction and +copy/paste vary among PDF readers; PyMuPDF round-trip checks cover the original +sequences. PDF/A-4 and PDF/UA compliance still require independent validation. diff --git a/emoji_renderer.py b/emoji_renderer.py index 9241d4c..e00d2e8 100644 --- a/emoji_renderer.py +++ b/emoji_renderer.py @@ -1,32 +1,113 @@ -"""Render bundled Twemoji artwork inline without system fonts or network access.""" +"""Render author-selected, fixed emoji artwork; never use viewer-native emoji fonts.""" -from functools import lru_cache +from contextlib import contextmanager +from contextvars import ContextVar +from functools import lru_cache, wraps +from hashlib import sha256 from html import escape from pathlib import Path import re from tempfile import TemporaryDirectory from threading import Lock -from zipfile import ZipFile +from zipfile import BadZipFile, ZipFile from reportlab.platypus import Paragraph +from emoji_unicode import embed_unicode_emoji, emoji_from_image, emit_unicode_text ASSETS = Path(__file__).parent / "assets" / "twemoji" / "72x72.zip" +STYLE_PACK_ROOT = Path(__file__).parent / "assets" / "emoji-styles" +EMOJI_STYLES = { + "twemoji": "Twemoji (bundled)", + "fluent": "Fluent Emoji", + "noto": "Noto Emoji", + "openmoji": "OpenMoji", + "blobmoji": "Blobmoji", + "emojitwo": "Emojitwo", + "mutant-standard": "Mutant Standard", +} +_active_style = ContextVar("pdf_compiler_emoji_style", default=("twemoji", str(ASSETS))) _asset_lock = Lock() - - -@lru_cache(maxsize=1) -def _emoji_pattern(): - with ZipFile(ASSETS) as bundle: - sequences = { - "".join(chr(int(part, 16)) for part in name[:-4].split("-")).replace("\ufe0f", ""): name - for name in bundle.namelist() - } - # Longest first keeps flags, skin tones, and joined families as one image. - patterns = [] - for sequence in sorted(sequences, key=lambda value: (-len(value), value)): - patterns.append("".join(re.escape(char) + "\ufe0f?" for char in sequence)) - return re.compile("|".join(patterns)), sequences +_PNG = b"\x89PNG\r\n\x1a\n" +_NAME = re.compile(r"(?:emoji_u)?([0-9a-f]{2,6}(?:-[0-9a-f]{2,6})*)\.png\Z") + + +def _archive(style, pack=None): + if style not in EMOJI_STYLES: + raise ValueError(f"Unknown emoji style: {style}") + if style == "twemoji": + if pack is not None: + raise ValueError("Twemoji uses bundled artwork; omit the external pack.") + path = ASSETS + else: + path = Path(pack) if pack is not None else STYLE_PACK_ROOT / style / "72x72.zip" + if not path.is_file(): + raise ValueError(f"{EMOJI_STYLES[style]} is unavailable: supply its PNG ZIP pack.") + return str(path) + + +def _pack_index(archive): + try: + with ZipFile(archive) as bundle: + if len(bundle.infolist()) > 10000: + raise ValueError("Emoji ZIP contains too many entries.") + entries = {} + total = 0 + for info in bundle.infolist(): + name = Path(info.filename).name.lower() + matched = _NAME.fullmatch(name) + if not matched: + continue + total += info.file_size + if info.file_size > 1024 * 1024 or total > 128 * 1024 * 1024: + raise ValueError("Emoji ZIP exceeds image size limits.") + key = "".join(chr(int(part, 16)) for part in matched.group(1).split("-") + if int(part, 16) != 0xfe0f) + if key in entries: + raise ValueError(f"Duplicate emoji sequence: {name}") + entries[key] = info.filename + if not entries: + raise ValueError("Emoji ZIP must contain codepoint-named PNG files.") + return entries + except (BadZipFile, OSError) as exc: + raise ValueError("Emoji artwork must be a valid PNG ZIP file.") from exc + + +def validate_emoji_style(style, pack=None): + return _pack_index(_archive(style, pack)) + + +@contextmanager +def emoji_style_scope(style="twemoji", pack=None): + archive = _archive(style, pack) + _pack_index(archive) + token = _active_style.set((style, archive)) + try: + yield + finally: + _active_style.reset(token) + + +def render_with_emoji_style(method): + @wraps(method) + def wrapped(self, *args, **kwargs): + with emoji_style_scope(self.emoji_style, self.emoji_pack): + result = method(self, *args, **kwargs) + embed_unicode_emoji(self.output) + return result + return wrapped + + +@lru_cache(maxsize=32) +def _emoji_pattern(archive): + selected = _pack_index(archive) + reference = selected if archive == str(ASSETS) else _pack_index(str(ASSETS)) + sequences = selected.keys() | reference.keys() + parts = [ + "".join(re.escape(char) + "\ufe0f?" for char in sequence) + for sequence in sorted(sequences, key=lambda value: (-len(value), value)) + ] + return re.compile("|".join(parts)), selected @lru_cache(maxsize=1) @@ -34,18 +115,38 @@ def _asset_directory(): return TemporaryDirectory(prefix="pdf-compiler-emoji-") -@lru_cache(maxsize=None) -def _image_path(filename): +@lru_cache(maxsize=1024) +def _image_path(archive, filename, original): with _asset_lock: - path = Path(_asset_directory().name) / filename + prefix = sha256(archive.encode()).hexdigest()[:16] + directory = Path(_asset_directory().name) / prefix + directory.mkdir(exist_ok=True) + codepoints = "-".join(f"{ord(char):x}" for char in original) + path = directory / f"{codepoints}__{Path(filename).name}" if not path.exists(): - with ZipFile(ASSETS) as bundle: - path.write_bytes(bundle.read(filename)) + with ZipFile(archive) as bundle: + data = bundle.read(filename) + if not data.startswith(_PNG): + raise ValueError(f"Invalid PNG emoji artwork: {filename}") + path.write_bytes(data) return escape(str(path), quote=True) +def emoji_preview(style, pack=None): + archive = _archive(style, pack) + entries = _pack_index(archive) + sample = next((entries.get(item) for item in ("πŸ˜€", "🌐", "πŸ‘πŸ½", "❀️") + if entries.get(item)), None) + if sample is None: + raise ValueError("This emoji pack lacks a common preview glyph.") + with ZipFile(archive) as bundle: + data = bundle.read(sample) + if not data.startswith(_PNG): + raise ValueError("Emoji preview must be a PNG.") + return data + + def _dash_markup(text): - # Standard PDF Times lacks these Unicode hyphens and the figure dash. text = text.replace("\u2010", "-").replace("\u2012", "\u2013") return re.sub( r"\S*\u2011\S*", @@ -55,16 +156,23 @@ def _dash_markup(text): def emoji_markup(text, font_size): - pattern, sequences = _emoji_pattern() + style, archive = _active_style.get() + pattern, selected = _emoji_pattern(archive) def replace(match): - filename = sequences[match.group().replace("\ufe0f", "")] + normalized = match.group().replace("\ufe0f", "") + filename = selected.get(normalized) + if filename is None: + raise ValueError( + f"{EMOJI_STYLES[style]} does not include emoji {match.group()!r}. " + "Choose a compatible artwork pack." + ) return ( - f'' ) - # Never modify link destinations, anchors, or other markup attributes. + # Do not change markup attributes, link destinations, or anchors. return "".join( part if index % 2 else pattern.sub(replace, _dash_markup(part)) for index, part in enumerate(re.split(r"(<[^>]+>)", text)) @@ -76,3 +184,31 @@ def __init__(self, text, style=None, bulletText=None, frags=None, **kwargs): if text and frags is None: text = emoji_markup(text, style.fontSize if style is not None else 10) super().__init__(text, style, bulletText=bulletText, frags=frags, **kwargs) + + def beginText(self, *args, **kwargs): + tx = super().beginText(*args, **kwargs) + self._emoji_tx = tx + return tx + + def drawPara(self, *args, **kwargs): + # ReportLab draws inline images separately from its paragraph text. + # Insert the exact Unicode sequence into that same text run at the + # image's position, while retaining the full-color PNG for display. + canvas = self.canv + original_draw_image = canvas.drawImage + + def draw_image(image, x, y, *image_args, **image_kwargs): + result = original_draw_image(image, x, y, *image_args, **image_kwargs) + sequence = emoji_from_image(image, Path(_asset_directory().name)) + if sequence is not None: + emit_unicode_text( + canvas, self._emoji_tx, sequence, + self.style.fontSize, self.style.fontName, + ) + return result + + canvas.drawImage = draw_image + try: + return super().drawPara(*args, **kwargs) + finally: + canvas.drawImage = original_draw_image diff --git a/emoji_unicode.py b/emoji_unicode.py new file mode 100644 index 0000000..256b8f2 --- /dev/null +++ b/emoji_unicode.py @@ -0,0 +1,127 @@ +"""Embed copyable Unicode emoji alongside fixed-color ReportLab emoji artwork. + +ReportLab draws inline PNGs outside the text object. EmojiParagraph emits one +zero-paint Type 3 text glyph at each image position. This module installs a +ToUnicode CMap for the exact source sequence; ordinary text and the chosen +color PNG are left untouched. The glyph is inside the paragraph text run, so +text extraction retains the surrounding reading order. +""" + +import os +from pathlib import Path +import re +from tempfile import NamedTemporaryFile + +import fitz + + +_EMOJI_FONT = re.compile(rb"/EMJ_([0-9a-f]+(?:_[0-9a-f]+)*)\s+[0-9.]+\s+Tf") +_FONT_REF = re.compile(r"/Font\s+(\d+)\s+0\s+R") + + +def emoji_font_name(sequence: str) -> str: + """A PDF Name that losslessly identifies one Unicode emoji sequence.""" + return "EMJ_" + "_".join(f"{ord(char):x}" for char in sequence) + + +def emoji_from_image(image, root: Path) -> str | None: + """Recognize only artwork generated by emoji_markup, not author images.""" + file_name = getattr(image, "fileName", "") + path = Path(file_name) if isinstance(file_name, (str, Path)) else None + if path is None or root not in path.parents or "__" not in path.name: + return None + prefix = path.name.split("__", 1)[0] + if not re.fullmatch(r"[0-9a-f]+(?:-[0-9a-f]+)*", prefix): + return None + try: + return "".join(chr(int(code, 16)) for code in prefix.split("-")) + except ValueError: + return None + + +def emit_unicode_text(canvas, tx, sequence: str, font_size: float, fallback_font: str): + """Insert selectable text without changing PNG placement or text style.""" + active_font = tx._fontname or fallback_font + active_size = tx._fontsize or font_size + restore = canvas._doc.getInternalFontName(active_font) + font = emoji_font_name(sequence) + tx._code.append(f"/{font} {active_size:g} Tf <01> Tj {restore} {active_size:g} Tf") + + +def _make_font(doc, sequence: str, char_proc: int) -> int: + unicode_hex = sequence.encode("utf-16-be").hex().upper() + cmap = ( + "/CIDInit /ProcSet findresource begin\n" + "12 dict begin\n" + "begincmap\n" + "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n" + "/CMapName /EmojiUnicode def\n/CMapType 2 def\n" + "1 begincodespacerange\n<00> \nendcodespacerange\n" + f"1 beginbfchar\n<01> <{unicode_hex}>\nendbfchar\n" + "endcmap\nCMapName currentdict /CMap defineresource pop\nend end\n" + ).encode("ascii") + cmap_ref = doc.get_new_xref() + doc.update_object(cmap_ref, "<< >>") + doc.update_stream(cmap_ref, cmap) + font_ref = doc.get_new_xref() + doc.update_object(font_ref, ( + "<< /Type /Font /Subtype /Type3 " + "/FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] " + f"/CharProcs << /E1 {char_proc} 0 R >> " + "/Encoding << /Type /Encoding /Differences [1 /E1] >> " + "/FirstChar 1 /LastChar 1 /Widths [1000] " + f"/Resources << >> /ToUnicode {cmap_ref} 0 R >>" + )) + return font_ref + + +def _page_font_table(doc, page) -> int: + """Locate the indirect ReportLab font dictionary on this page.""" + kind, resources = doc.xref_get_key(page.xref, "Resources") + if kind == "xref": + resource_ref = int(resources.split()[0]) + kind, font_entry = doc.xref_get_key(resource_ref, "Font") + if kind == "xref": + return int(font_entry.split()[0]) + else: + match = _FONT_REF.search(resources) + if match: + return int(match.group(1)) + raise RuntimeError("Cannot install Unicode emoji fonts in PDF page resources") + + +def embed_unicode_emoji(path: Path) -> None: + """Attach ToUnicode Type 3 mappings atomically after ReportLab renders.""" + path = Path(path) + with fitz.open(path) as doc: + used = [] + for page in doc: + names = set() + for xref in page.get_contents(): + for match in _EMOJI_FONT.finditer(doc.xref_stream(xref)): + names.add(match.group(1).decode("ascii")) + used.append(names) + if not any(used): + return + char_proc = doc.get_new_xref() + doc.update_object(char_proc, "<< >>") + doc.update_stream(char_proc, b"1000 0 d0\n") + installed = {} + for page, names in zip(doc, used): + if not names: + continue + font_table = _page_font_table(doc, page) + for codepoints in sorted(names): + sequence = "".join(chr(int(code, 16)) for code in codepoints.split("_")) + name = emoji_font_name(sequence) + if name not in installed: + installed[name] = _make_font(doc, sequence, char_proc) + doc.xref_set_key(font_table, name, f"{installed[name]} 0 R") + with NamedTemporaryFile(prefix=".emoji-unicode-", suffix=".pdf", dir=path.parent, + delete=False) as handle: + temporary = Path(handle.name) + try: + doc.save(str(temporary), garbage=3, deflate=True) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) diff --git a/examples/emoji-text.md b/examples/emoji-text.md new file mode 100644 index 0000000..40e79da --- /dev/null +++ b/examples/emoji-text.md @@ -0,0 +1,34 @@ +# Emoji text rendering fixture 🌐 + +[[TOC]] + +## Individual characters πŸ€” ⏰ 🌐 + +πŸ€” Before the sentence. An inline clock ⏰ stays in the text. A final globe 🌐. + +## Emoji sequences + +Skin tone: πŸ‘πŸ½. Flag: πŸ‡ΊπŸ‡Έ. Family: πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦. Heart: ❀️. +Keycap: 1️⃣. Rainbow flag: πŸ³οΈβ€πŸŒˆ. Text presentation: β™₯︎. Emoji presentation: β™₯️. + +## Formatting and links + +**Bold emoji πŸ€”** and *italic emoji 🌐* remain selectable characters. + +[Emoji link ⏰](https://example.com/emoji) + +- List item with a globe 🌐. +- Nested sequences: + - Family πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ and skin tone πŸ‘πŸ½. + +## Wrapping and punctuation + +Repeat this paragraph when checking multi-page layout: Emoji πŸ€” should stay +inline with surrounding words, and joined sequences πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ should remain intact +when text wraps. Preserve punctuation around (🌐), [⏰], and β€œβ€οΈβ€. + +Keep existing dash handling: on‐chain, on‑chain, 1β€’2, en–dash, and emβ€”dash. + +*** + +The horizontal rule above should remain independent of emoji rendering. diff --git a/pdf_compiler.py b/pdf_compiler.py index 4cf2845..ee7359b 100644 --- a/pdf_compiler.py +++ b/pdf_compiler.py @@ -36,7 +36,7 @@ ) -from emoji_renderer import EmojiParagraph as Paragraph +from emoji_renderer import EmojiParagraph as Paragraph, EMOJI_STYLES, render_with_emoji_style, validate_emoji_style from page_breaks import PAGE_BREAK_SENTINEL, normalize_page_breaks from document_assets import resolve_document_image @@ -445,6 +445,8 @@ def __init__( start_heading: str | None = None, smart_quotes: bool = False, quote_inline_number_footnotes: bool = False, + emoji_style: str = "twemoji", + emoji_pack: Path | None = None, underline_links: bool = True, link_color: str = LINK_COLOR, ): @@ -457,6 +459,9 @@ def __init__( self.author = author or "" self.smart_quotes = smart_quotes self.quote_inline_number_footnotes = quote_inline_number_footnotes + validate_emoji_style(emoji_style, emoji_pack) + self.emoji_style = emoji_style + self.emoji_pack = emoji_pack self.underline_links = underline_links if not re.fullmatch(r"#[0-9a-fA-F]{6}", link_color): raise ValueError("Link color must be a six-digit hex color, such as #2E732E.") @@ -1460,6 +1465,7 @@ def document(self, path: Path) -> TrackingDoc: author=self.author, ) + @render_with_emoji_style def build(self) -> tuple[int, int, int]: self.output.parent.mkdir(parents=True, exist_ok=True) tmp = self.output.with_suffix(".tmp.pdf") @@ -1526,6 +1532,10 @@ def main() -> int: action="store_true", help="Convert straight quotes to typographic quotes in rendered text", ) + parser.add_argument("--emoji-style", choices=tuple(EMOJI_STYLES), default="twemoji", + help="Author-selected fixed emoji artwork style") + parser.add_argument("--emoji-pack", type=Path, + help="PNG ZIP asset pack for a non-Twemoji style") parser.add_argument( "--quote-inline-number-footnotes", action="store_true", @@ -1557,6 +1567,8 @@ def main() -> int: start_heading=args.start_heading, smart_quotes=args.smart_quotes, quote_inline_number_footnotes=args.quote_inline_number_footnotes, + emoji_style=args.emoji_style, + emoji_pack=args.emoji_pack, **presentation, ) from pdfa4_export import render_pdf diff --git a/static/emoji-styles.js b/static/emoji-styles.js new file mode 100644 index 0000000..6146ce8 --- /dev/null +++ b/static/emoji-styles.js @@ -0,0 +1,37 @@ +(() => { + const style = document.getElementById("emoji-style"); + const pack = document.getElementById("emoji-pack"); + const preview = document.getElementById("emoji-preview"); + const status = document.getElementById("emoji-preview-status"); + if (!style || !pack || !preview || !status) return; + let revision = 0, previous = null; + async function refresh() { + const current = ++revision; + const body = new FormData(); + body.set("emoji_style", style.value); + if (style.value !== "twemoji" && pack.files.length) body.set("emoji_pack", pack.files[0]); + status.textContent = "Checking selected emoji artwork…"; + try { + const response = await fetch("/emoji-preview", { method: "POST", body }); + if (current !== revision) return; + if (!response.ok) { + const result = await response.json(); + throw new Error(result.error || "Preview unavailable."); + } + const blob = await response.blob(); + if (previous) URL.revokeObjectURL(previous); + previous = URL.createObjectURL(blob); + preview.src = previous; + preview.style.display = "block"; + status.textContent = "Preview from the actual selected artwork."; + } catch (error) { + if (current !== revision) return; + preview.removeAttribute("src"); + preview.style.display = "none"; + status.textContent = error.message; + } + } + style.addEventListener("change", refresh); + pack.addEventListener("change", refresh); + refresh(); +})(); diff --git a/templates/index.html b/templates/index.html index ccabbc2..0780b3e 100644 --- a/templates/index.html +++ b/templates/index.html @@ -305,6 +305,22 @@

PDF Compiler

Choose a folder with one Markdown file and referenced raster images, including subfolders. + + +
+ Actual selected emoji artwork preview + +
diff --git a/tests/test_emoji_renderer.py b/tests/test_emoji_renderer.py index 7480df2..6a6ad64 100644 --- a/tests/test_emoji_renderer.py +++ b/tests/test_emoji_renderer.py @@ -61,7 +61,67 @@ def test_builds_pdf_with_emoji_in_headings_toc_and_wrapped_body(self): ) pages, _, _ = renderer.build() self.assertGreater(pages, 2) - self.assertIn(b"/Subtype /Image", output.read_bytes()) + import fitz + with fitz.open(output) as pdf: + self.assertTrue(any(page.get_images() for page in pdf)) + + def test_color_emoji_copy_as_original_inline_unicode(self): + import fitz + + with TemporaryDirectory() as temp: + root = Path(temp) + source = root / "emoji-copy.md" + source.write_text( + "## Greeting πŸ˜€\n\n" + "Hello πŸ˜€ world πŸ‘πŸ½ family πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ flag πŸ‡ΊπŸ‡Έ heart ❀️.\n\n" + "Next paragraph: πŸ¦„ then ✨.\n", + encoding="utf-8", + ) + output = root / "emoji-copy.pdf" + renderer = FirstPagePdfRenderer( + source, output, settings=LetterSettings(show_date=False), + ) + renderer.build() + with fitz.open(output) as pdf: + text = " ".join(" ".join(page.get_text(sort=True).split()) + for page in pdf) + self.assertIn( + "Hello πŸ˜€ world πŸ‘πŸ½ family πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ flag πŸ‡ΊπŸ‡Έ heart ❀️.", text + ) + self.assertIn("Next paragraph: πŸ¦„ then ✨.", text) + self.assertTrue(any(page.get_images() for page in pdf)) + self.assertTrue(pdf[0].search_for("πŸ˜€")) + + def test_selected_pack_does_not_fall_back(self): + from zipfile import ZipFile + from emoji_renderer import emoji_style_scope, validate_emoji_style + with TemporaryDirectory() as temp: + path = Path(temp) / "noto.zip" + bundled = Path(__file__).resolve().parents[1] / "assets" / "twemoji" / "72x72.zip" + with ZipFile(bundled) as source, ZipFile(path, "w") as target: + name = next(name for name in source.namelist() if name.endswith("1f600.png")) + target.writestr("1f600.png", source.read(name)) + validate_emoji_style("noto", path) + with emoji_style_scope("noto", path): + self.assertEqual(emoji_markup("πŸ˜€", 14).count("