"""Approximate layout check for the deck (no browser on this machine). Reads project/deck.css and project/slides/.html, lays the slide out with real font metrics (PIL + raqm) and a small subset of CSS (block, flex row/column, grid, table, lists), and reports block heights, wrapped line counts and overflow. Usage: python -I layout_check.py [depth] """ import re import sys from html.parser import HTMLParser from PIL import ImageFont ROOT = sys.argv[1] SLIDE = sys.argv[2] DEPTH = int(sys.argv[3]) if len(sys.argv) > 3 else 3 FONTDIR = __file__.rsplit("/", 1)[0] + "/fonts/" W, H = 1920, 1080 TEXT_TAGS = {"p", "h1", "h2", "h3", "li", "td", "th"} INLINE = {"b", "i", "u", "span", "a", "br"} DEFAULT_SIZE = {"h1": 96, "h2": 64, "h3": 44} # ---------- css ---------- css = open(ROOT + "/project/deck.css").read() css = re.sub(r"/\*.*?\*/", "", css, flags=re.S) rules = [] for order, m in enumerate(re.finditer(r"([^{}]+)\{([^{}]*)\}", css)): decls = {} for d in m.group(2).split(";"): if ":" in d: k, v = d.split(":", 1) decls[k.strip()] = v.strip() for sel in m.group(1).split(","): parts = [] for simple in sel.split(): tag = re.match(r"^[a-z0-9]+", simple) parts.append((tag.group(0) if tag else None, set(re.findall(r"\.([\w-]+)", simple)))) spec = (sum(len(c) for _, c in parts), sum(1 for t, _ in parts if t), order) rules.append((spec, parts, decls)) rules.sort(key=lambda r: r[0]) class Node: def __init__(self, tag, attrs, parent): self.tag, self.parent, self.children = tag, parent, [] self.classes = set((attrs.get("class") or "").split()) self.style = {} self.text = None # for text runs class P(HTMLParser): def __init__(self): super().__init__() self.root = Node("root", {}, None) self.cur = self.root def handle_starttag(self, tag, attrs): n = Node(tag, dict(attrs), self.cur) self.cur.children.append(n) if tag != "br": self.cur = n def handle_endtag(self, tag): if tag != "br": self.cur = self.cur.parent def handle_data(self, data): if data.strip() or (data and self.cur.tag in TEXT_TAGS | INLINE): n = Node("#text", {}, self.cur) n.text = data self.cur.children.append(n) def matches(node, parts): def one(n, part): tag, classes = part return (tag is None or n.tag == tag) and classes <= n.classes if not one(node, parts[-1]): return False rest, anc = list(parts[:-1]), node.parent while rest and anc is not None: if one(anc, rest[-1]): rest.pop() anc = anc.parent return not rest def compute_styles(node): if node.tag != "#text": for _, parts, decls in rules: if matches(node, parts): node.style.update(decls) for c in node.children: compute_styles(c) def inherited(node, prop, default): n = node while n is not None: if prop in n.style: return n.style[prop] if prop in ("font-size", "font-weight") and n.tag in DEFAULT_SIZE: return {"font-size": f"{DEFAULT_SIZE[n.tag]}px", "font-weight": "600"}[prop] n = n.parent return default def px(v, base=0.0): v = v.strip() if v.endswith("px"): return float(v[:-2]) if v.endswith("%"): return base * float(v[:-1]) / 100 if v.endswith("em"): return base * float(v[:-2]) return float(v) if v not in ("auto", "none") else 0.0 def box4(node, prop, em=0.0): out = [0.0, 0.0, 0.0, 0.0] # top right bottom left if prop in node.style: vals = [px(x, em) for x in node.style[prop].split()] if len(vals) == 1: out = vals * 4 elif len(vals) == 2: out = [vals[0], vals[1], vals[0], vals[1]] elif len(vals) == 3: out = [vals[0], vals[1], vals[2], vals[1]] else: out = vals for i, side in enumerate(("top", "right", "bottom", "left")): if f"{prop}-{side}" in node.style: out[i] = px(node.style[f"{prop}-{side}"].split()[0], em) return out def border4(node): out = [0.0] * 4 if "border" in node.style: out = [px(node.style["border"].split()[0])] * 4 for i, side in enumerate(("top", "right", "bottom", "left")): if f"border-{side}" in node.style: v = node.style[f"border-{side}"].split()[0] out[i] = 0.0 if v == "none" else px(v) return out _fonts = {} def font(family, weight): fam = "NotoSansDevanagari" if "Devanagari" in family else "RobotoCondensed" w = 400 if weight < 500 else (600 if weight < 650 or fam == "NotoSansDevanagari" else 700) key = (fam, w) if key not in _fonts: _fonts[key] = ImageFont.truetype(f"{FONTDIR}{fam}-{w}.ttf", 200) return _fonts[key] def has_deva(s): return any("ऀ" <= ch <= "ॿ" for ch in s) def width_of(s, family, weight, size): if has_deva(s): f = font("Noto Sans Devanagari", weight) else: f = font(family.split(",")[0], weight) return f.getlength(s) * size / 200 def runs(node, bold=False): out = [] for c in node.children: if c.tag == "#text": out.append((re.sub(r"\s+", " ", c.text), bold)) elif c.tag == "br": out.append(("\n", bold)) else: out += runs(c, bold or c.tag == "b") return out problems = [] def text_lines(node, width): size = px(inherited(node, "font-size", "32px")) weight = int(inherited(node, "font-weight", "400").replace("bold", "700").replace("normal", "400")) if node.tag == "th": weight = max(weight, 700) family = inherited(node, "font-family", "Roboto Condensed") words = [] # list of word pieces [(text,bold)], separated by spaces cur = [] for text, bold in runs(node): w = weight if not bold else max(weight, 700) for piece in re.split(r"( )", text): if piece == " ": if cur: words.append(cur) cur = [] elif piece: cur.append((piece, w)) if cur: words.append(cur) space = width_of(" ", family, weight, size) lines, x, widest = 1, 0.0, 0.0 for word in words: ww = sum(width_of(t, family, w, size) for t, w in word) if ww > width + 0.5: problems.append(f"WORD WIDER THAN BOX: '{''.join(t for t, _ in word)}' {ww:.0f} > {width:.0f}") if x == 0: x = ww elif x + space + ww <= width: x += space + ww else: lines += 1 x = ww widest = max(widest, x) lh = inherited(node, "line-height", "1.2") lhpx = px(lh) if lh.endswith("px") else float(lh) * size return lines, lhpx, widest, size report = [] def label(node): return node.tag + ("." + ".".join(sorted(node.classes)) if node.classes else "") def layout(node, avail, depth): """avail = outer width offered. Returns outer height (incl. padding, border, margin-top).""" st = node.style size = px(inherited(node, "font-size", "32px")) pad = box4(node, "padding", size) if node.tag in ("td", "th") and "padding" not in st: pad = [0.35 * size, 0.6 * size, 0.35 * size, 0.6 * size] if node.tag == "ul" and "padding-left" not in st and "padding" not in st: pad[3] = 40.0 bor = border4(node) mt = px(st.get("margin-top", "0px")) if node.tag == "section": outer, content_w = W, W - pad[1] - pad[3] elif "width" in st and node.tag not in ("td", "th"): content_w = px(st["width"], avail) outer = content_w + pad[1] + pad[3] + bor[1] + bor[3] else: outer = avail content_w = avail - pad[1] - pad[3] - bor[1] - bor[3] node.outer_w = outer slot = len(report) report.append(None) disp = st.get("display", "block") kids = [c for c in node.children if c.tag not in ("#text", "aside")] info = "" if node.tag in TEXT_TAGS and node.tag not in ("td", "th") or node.tag in ("td", "th"): n, lhpx, widest, fs = text_lines(node, content_w) inner = n * lhpx info = f"{n} line(s) @{fs:.0f}px, widest {widest:.0f}/{content_w:.0f}" if node.tag in ("p", "li") and n >= 1: npb = len(problems) def minw(target): lo, hi = 40.0, 4000.0 while hi - lo > 1: mid = (lo + hi) / 2 if text_lines(node, mid)[0] <= target: hi = mid else: lo = mid return hi info += f" [keep {n}L >= {minw(n):.0f}px" + (f"; {n-1}L >= {minw(n-1):.0f}px]" if n > 1 else "]") del problems[npb:] elif node.tag == "table": rows = [c for c in kids if c.tag == "tr"] first = [c for c in rows[0].children if c.tag in ("td", "th")] ncol = len(first) widths = [None] * ncol for i, c in enumerate(first): compute = c.style.get("width") if compute: widths[i] = px(compute, content_w) free = content_w - sum(w for w in widths if w) nfree = sum(1 for w in widths if not w) widths = [w if w else free / nfree for w in widths] inner = 2.0 for r in rows: cells = [c for c in r.children if c.tag in ("td", "th")] rh = max(layout(c, widths[i], depth + 2) for i, c in enumerate(cells)) inner += rh + 2.0 info = f"{len(rows)} rows, cols {[round(w) for w in widths]}" elif disp == "flex" and st.get("flex-direction", "row") == "row": gap = px(st.get("gap", "0px").split()[-1]) fixed, grow = 0.0, 0.0 for c in kids: if "flex" in c.style: grow += float(c.style["flex"].split()[0]) elif "width" in c.style: cs = px(inherited(c, "font-size", "32px")) p, b = box4(c, "padding", cs), border4(c) fixed += px(c.style["width"], content_w) + p[1] + p[3] + b[1] + b[3] else: raise SystemExit(f"row child without width/flex: {label(c)}") free = content_w - fixed - gap * (len(kids) - 1) hs = [] for c in kids: if "flex" in c.style: hs.append(layout(c, free * float(c.style["flex"].split()[0]) / grow, depth + 1)) else: hs.append(layout(c, content_w, depth + 1)) inner = max(hs) if free < 0: problems.append(f"ROW OVERFLOW in {label(node)}: {-free:.0f}px") elif disp == "grid": tracks = st["grid-template-columns"].split() gaps = st.get("gap", "0px").split() rgap, cgap = px(gaps[0]), px(gaps[-1]) fixed = sum(px(t) for t in tracks if t.endswith("px")) fr = sum(float(t[:-2]) for t in tracks if t.endswith("fr")) free = content_w - fixed - cgap * (len(tracks) - 1) if free < -0.5: problems.append(f"GRID OVERFLOW in {label(node)}: {-free:.0f}px") ws = [px(t) if t.endswith("px") else free * float(t[:-2]) / fr for t in tracks] inner, nrows = 0.0, 0 for r in range(0, len(kids), len(tracks)): inner += max(layout(c, ws[i], depth + 2) for i, c in enumerate(kids[r:r + len(tracks)])) nrows += 1 inner += rgap * (nrows - 1) info = f"grid {nrows} rows, cols {[round(w) for w in ws]}" else: gap = px(st.get("gap", "0px").split()[0]) if disp == "flex" else 0.0 hs = [layout(c, content_w, depth + 1) for c in kids] inner = sum(hs) + gap * max(0, len(kids) - 1) outer_h = inner + pad[0] + pad[2] + bor[0] + bor[2] + mt if depth <= DEPTH or (node.tag in TEXT_TAGS and depth <= DEPTH + 2): report[slot] = f"{' ' * depth}{label(node):<28} w={outer:7.1f} h={outer_h:7.1f} {info}" return outer_h p = P() p.feed(open(f"{ROOT}/project/slides/{SLIDE}.html").read()) section = p.root.children[0] compute_styles(section) idx = len(report) total = layout(section, W, 0) # report was appended post-order; print in document order by re-walking is overkill: sort by insertion reversed per depth print("\n".join(r for r in report[idx:] if r)) print(f"\nSLIDE {SLIDE}: content height {total:.0f} of {H} -> {'OVERFLOW by %.0f' % (total - H) if total > H else 'spare %.0f' % (H - total)}") for pr in problems: print("PROBLEM:", pr)