#include "ChunkLayoutEngine.h" #include #include #include #include #include #include "backend/reading/BookImageResolver.h" #include "KnuthPlass.h" namespace ChunkLayoutEngine { namespace { QFont resolveFont(const TextStyle &style, qreal baseFontSize, const QString &baseFontFamily) { QFont font; if (!style.fontFamilies.isEmpty()) { const QString &fam = style.fontFamilies.first(); if (fam.compare(QLatin1String("serif"), Qt::CaseInsensitive) == 0) { font.setStyleHint(QFont::Serif); font.setFamily(QStringLiteral("Times New Roman")); } else if (fam.compare(QLatin1String("sans-serif"), Qt::CaseInsensitive) == 0) { font.setStyleHint(QFont::SansSerif); font.setFamily(QStringLiteral("Helvetica")); } else if (fam.compare(QLatin1String("monospace"), Qt::CaseInsensitive) == 0) { font.setStyleHint(QFont::Monospace); font.setFamily(QStringLiteral("Courier")); } else { font.setFamily(fam); } } else if (!baseFontFamily.isEmpty()) { font.setFamily(baseFontFamily); } qreal targetSize = style.fontSize > 0 ? style.fontSize : baseFontSize; font.setPointSizeF(targetSize * 0.75); font.setPixelSize(static_cast(std::round(targetSize))); font.setWeight(static_cast(style.weight)); font.setItalic(style.italic); font.setCapitalization(style.smallCaps ? QFont::SmallCaps : QFont::MixedCase); if (style.letterSpacing != 0) { font.setLetterSpacing(QFont::AbsoluteSpacing, style.letterSpacing); } font.setUnderline(style.underline); font.setStrikeOut(style.strikeOut); font.setOverline(style.overline); return font; } QString transformText(const QString &text, TextTransform transform) { switch (transform) { case TextTransform::Uppercase: return text.toUpper(); case TextTransform::Lowercase: return text.toLower(); case TextTransform::Capitalize: { QString res = text; bool inWord = false; for (int i = 0; i < res.size(); ++i) { if (res[i].isLetter()) { if (!inWord) { res[i] = res[i].toUpper(); inWord = true; } } else { inWord = false; } } return res; } case TextTransform::None: default: return text; } } struct WordMetrics { qreal width = 0; qreal ascent = 0; qreal descent = 0; }; struct ActiveBox { BoxStyle box; qreal startY = 0; qreal left = 0; qreal right = 0; }; class LayoutWorker { public: explicit LayoutWorker(const LayoutParams ¶ms) : m_params(params) { } ChunkLayout run(const PreparedChunk &prepared) { m_curY = 0; m_prevMarginBottom = 0; m_layout.contentWidth = m_params.contentWidth; for (const auto &b : prepared.blocks) { switch (b.kind) { case PreparedBlock::Kind::ContainerStart: handleContainerStart(b.box); break; case PreparedBlock::Kind::ContainerEnd: handleContainerEnd(b.box); break; case PreparedBlock::Kind::Rule: handleRule(b.ruleColor); break; case PreparedBlock::Kind::ImageBlock: handleImageBlock(b.imageBlock); break; case PreparedBlock::Kind::Paragraph: handleParagraph(b.paragraph); break; } } m_layout.totalHeight = m_curY; return m_layout; } private: void handleContainerStart(const BoxStyle &box) { qreal collapsedMargin = std::max(m_prevMarginBottom, box.marginTop); m_curY += collapsedMargin; m_prevMarginBottom = 0; ActiveBox ab; ab.box = box; ab.startY = m_curY; ab.left = currentLeft() + box.marginLeft; ab.right = currentRight() + box.marginRight; m_curY += box.borderTop + box.paddingTop; m_boxStack.append(ab); } void handleContainerEnd(const BoxStyle &box) { if (m_boxStack.isEmpty()) return; ActiveBox ab = m_boxStack.takeLast(); m_curY += box.paddingBottom + box.borderBottom; PositionedDecoration dec; dec.rect = QRectF(ab.left, ab.startY, std::max(0.0, m_params.contentWidth - ab.left - ab.right), m_curY - ab.startY); dec.background = box.background; dec.borderColor = box.borderColor; dec.borderLeft = box.borderLeft; dec.borderTop = box.borderTop; dec.borderBottom = box.borderBottom; dec.borderRight = box.borderRight; if (dec.background.isValid() || dec.borderLeft > 0 || dec.borderTop > 0 || dec.borderBottom > 0 || dec.borderRight > 0) { m_layout.decorations.append(dec); } m_prevMarginBottom = box.marginBottom; } void handleRule(const QColor &color) { m_curY += std::max(m_prevMarginBottom, 8.0); PositionedRule r; qreal left = currentLeft(); qreal right = currentRight(); r.rect = QRectF(left, m_curY, std::max(10.0, m_params.contentWidth - left - right), 1.0); r.color = color; m_layout.rules.append(r); m_curY += 1.0; m_prevMarginBottom = 8.0; } qreal currentLeft() const { qreal l = 0; for (const auto &b : m_boxStack) { l += b.box.marginLeft + b.box.borderLeft + b.box.paddingLeft; } return l; } qreal currentRight() const { qreal r = 0; for (const auto &b : m_boxStack) { r += b.box.marginRight + b.box.borderRight + b.box.paddingRight; } return r; } void handleImageBlock(const PreparedImageBlock &item) { qreal left = currentLeft(); qreal right = currentRight(); qreal availWidth = std::max(50.0, m_params.contentWidth - left - right); qreal natW = item.naturalSize.width() > 0 ? item.naturalSize.width() : 100.0; qreal natH = item.naturalSize.height() > 0 ? item.naturalSize.height() : 100.0; qreal targetW = natW; qreal targetH = natH; if (item.cssWidth > 0) { targetW = item.cssWidth; targetH = (item.cssHeight > 0) ? item.cssHeight : (targetW * (natH / natW)); } else if (item.cssHeight > 0) { targetH = item.cssHeight; targetW = targetH * (natW / natH); } if (item.cssMaxWidth > 0 && targetW > item.cssMaxWidth) { qreal scale = item.cssMaxWidth / targetW; targetW *= scale; targetH *= scale; } if (targetW > availWidth) { qreal scale = availWidth / targetW; targetW *= scale; targetH *= scale; } qreal imgX = left + std::max(0.0, (availWidth - targetW) / 2.0); m_curY += 8.0; PositionedImage posImg; posImg.url = item.imageUrl; posImg.targetRect = QRectF(imgX, m_curY, targetW, targetH); m_layout.images.append(posImg); m_curY += targetH + 8.0; m_prevMarginBottom = 0; } void handleParagraph(const PreparedParagraph &p) { if (p.words.isEmpty() && p.kpItems.isEmpty()) return; QColor enclosingBg; for (int i = m_boxStack.size() - 1; i >= 0; --i) { if (m_boxStack[i].box.background.isValid() && m_boxStack[i].box.background.alpha() > 0) { enclosingBg = m_boxStack[i].box.background; break; } } qreal left = currentLeft(); qreal right = currentRight(); qreal availWidth = std::max(50.0, m_params.contentWidth - left - right); // Check if any word exceeds line width (emergency letter split fallback) QVector activeWords = p.words; QVector kpItems = p.kpItems; bool hasOversized = false; for (const auto &w : p.words) { if (w.width > availWidth && w.text.size() > 1) { hasOversized = true; break; } } if (hasOversized) { activeWords.clear(); kpItems.clear(); if (p.textIndent > 0) { kpItems.append(KnuthPlass::Item::box(p.textIndent, -1)); } for (const auto &it : p.kpItems) { if (it.type == KnuthPlass::ItemType::Box && it.tag >= 0 && it.tag < p.words.size()) { const auto &tok = p.words[it.tag]; if (tok.width > availWidth && tok.text.size() > 1) { QFontMetricsF fm(tok.font); for (int chIdx = 0; chIdx < tok.text.size(); ++chIdx) { PreparedWord chTok = tok; chTok.text = tok.text.mid(chIdx, 1); chTok.width = fm.horizontalAdvance(chTok.text); int subTokIdx = activeWords.size(); activeWords.append(chTok); kpItems.append(KnuthPlass::Item::box(chTok.width, subTokIdx)); if (chIdx < tok.text.size() - 1) { kpItems.append(KnuthPlass::Item::penaltyItem(0, 100.0, false, -1)); } } } else { int tokIdx = activeWords.size(); activeWords.append(tok); kpItems.append(KnuthPlass::Item::box(tok.width, tokIdx)); } } else { kpItems.append(it); } } } const auto lines = KnuthPlass::breakLines(kpItems, availWidth); if (lines.isEmpty()) return; qreal lineMultiplier = p.lineHeight > 0 ? p.lineHeight : m_params.lineSpacing; for (int lIdx = 0; lIdx < lines.size(); ++lIdx) { const auto &line = lines[lIdx]; const bool isLastLine = (lIdx == lines.size() - 1); qreal maxAscent = p.fontSize * 0.8; qreal maxDescent = p.fontSize * 0.2; for (int itIdx = line.start; itIdx < line.end && itIdx < kpItems.size(); ++itIdx) { const auto &it = kpItems[itIdx]; if (it.type == KnuthPlass::ItemType::Box && it.tag >= 0 && it.tag < activeWords.size()) { const auto &tok = activeWords[it.tag]; maxAscent = std::max(maxAscent, tok.ascent); maxDescent = std::max(maxDescent, tok.descent); } } qreal lineHeight = (maxAscent + maxDescent) * lineMultiplier; qreal baselineY = m_curY + maxAscent + (lineHeight - (maxAscent + maxDescent)) / 2.0; qreal contentW = 0; for (int itIdx = line.start; itIdx < line.end && itIdx < kpItems.size(); ++itIdx) { const auto &it = kpItems[itIdx]; if (it.type == KnuthPlass::ItemType::Box) { contentW += it.width; } else if (it.type == KnuthPlass::ItemType::Glue) { if (isLastLine || p.align != TextAlign::Justify) { contentW += it.width; } else { qreal adj = (line.ratio >= 0) ? (line.ratio * it.stretch) : (line.ratio * it.shrink); contentW += std::max(0.0, it.width + adj); } } } if (line.hyphenated) { contentW += 8.0; } qreal startX = left; if (p.align == TextAlign::Center) { startX += std::max(0.0, (availWidth - contentW) / 2.0); } else if (p.align == TextAlign::Right) { startX += std::max(0.0, availWidth - contentW); } qreal curX = startX; PositionedLine pLine; pLine.rect = QRectF(left, m_curY, availWidth, lineHeight); pLine.baselineY = baselineY; if (lIdx == 0 && !p.marker.isEmpty()) { PositionedWordRun mRun; mRun.text = p.marker; mRun.font = resolveFont(p.markerStyle, m_params.fontSize, m_params.baseFontFamily); QFontMetricsF mFm(mRun.font); qreal mW = mFm.horizontalAdvance(mRun.text); mRun.rect = QRectF(startX - mW - 4.0, m_curY, mW, lineHeight); mRun.baselineY = baselineY; mRun.color = p.markerStyle.color; pLine.runs.append(mRun); } for (int itIdx = line.start; itIdx < line.end && itIdx < kpItems.size(); ++itIdx) { const auto &it = kpItems[itIdx]; if (it.type == KnuthPlass::ItemType::Box) { if (it.tag >= 0 && it.tag < activeWords.size()) { const auto &tok = activeWords[it.tag]; if (!tok.imageUrl.isEmpty()) { PositionedImage img; img.url = tok.imageUrl; img.targetRect = QRectF(curX, baselineY - tok.ascent, tok.width, tok.ascent); m_layout.images.append(img); } else { PositionedWordRun run; run.text = tok.text; run.font = tok.font; run.color = tok.style.color; run.background = tok.style.background; run.surfaceBackground = enclosingBg; run.link = tok.style.link; run.underline = tok.style.underline; run.strikeOut = tok.style.strikeOut; run.overline = tok.style.overline; run.rect = QRectF(curX, m_curY, tok.width, lineHeight); run.baselineY = baselineY - tok.style.baselineShift; pLine.runs.append(run); } } curX += it.width; } else if (it.type == KnuthPlass::ItemType::Glue) { qreal spaceW = it.width; if (!isLastLine && p.align == TextAlign::Justify) { qreal adj = (line.ratio >= 0) ? (line.ratio * it.stretch) : (line.ratio * it.shrink); spaceW = std::max(0.0, it.width + adj); } curX += spaceW; } } if (line.hyphenated) { PositionedWordRun hyRun; hyRun.text = QStringLiteral("-"); if (!pLine.runs.isEmpty()) { hyRun.font = pLine.runs.last().font; hyRun.color = pLine.runs.last().color; } QFontMetricsF hFm(hyRun.font); qreal hW = hFm.horizontalAdvance(hyRun.text); hyRun.rect = QRectF(curX, m_curY, hW, lineHeight); hyRun.baselineY = baselineY; pLine.runs.append(hyRun); } m_layout.lines.append(pLine); m_curY += lineHeight; } m_prevMarginBottom = 0; } const LayoutParams &m_params; ChunkLayout m_layout; qreal m_curY = 0; qreal m_prevMarginBottom = 0; QVector m_boxStack; }; bool isPureImageBlock(const QVector &inlines, int &outImageIdx) { outImageIdx = -1; for (int i = 0; i < inlines.size(); ++i) { const auto &item = inlines[i]; if (item.kind == InlineItem::Kind::Image) { if (outImageIdx >= 0) return false; outImageIdx = i; } else if (item.kind == InlineItem::Kind::Text) { if (!item.text.trimmed().isEmpty()) return false; } else if (item.kind == InlineItem::Kind::LineBreak) { // ignore breaks } else { return false; } } return outImageIdx >= 0; } } // namespace PreparedChunk prepareBlocks(const QVector &blocks, qreal baseFontSize, IBookImageResolver *imageResolver) { PreparedChunk prepared; prepared.blocks.reserve(blocks.size()); // Word metrics cache across the chunk QHash metricsCache; for (const auto &b : blocks) { PreparedBlock pb; switch (b.kind) { case BlockItem::Kind::ContainerStart: pb.kind = PreparedBlock::Kind::ContainerStart; pb.box = b.box; prepared.blocks.append(pb); break; case BlockItem::Kind::ContainerEnd: pb.kind = PreparedBlock::Kind::ContainerEnd; pb.box = b.box; prepared.blocks.append(pb); break; case BlockItem::Kind::Rule: pb.kind = PreparedBlock::Kind::Rule; pb.ruleColor = b.ruleColor; prepared.blocks.append(pb); break; case BlockItem::Kind::Paragraph: { int pureImageIdx = -1; if (isPureImageBlock(b.inlines, pureImageIdx)) { const auto &imgInline = b.inlines[pureImageIdx]; pb.kind = PreparedBlock::Kind::ImageBlock; pb.imageBlock.imageUrl = imgInline.imageUrl; pb.imageBlock.cssWidth = imgInline.cssWidth; pb.imageBlock.cssHeight = imgInline.cssHeight; pb.imageBlock.cssMaxWidth = imgInline.cssMaxWidth; if (imageResolver) { QSizeF sz = imageResolver->imageSize(pb.imageBlock.imageUrl); if (sz.isValid() && sz.width() > 0 && sz.height() > 0) { pb.imageBlock.naturalSize = sz; } } prepared.blocks.append(pb); } else { pb.kind = PreparedBlock::Kind::Paragraph; pb.paragraph.align = b.align; pb.paragraph.textIndent = b.textIndent; pb.paragraph.lineHeight = b.lineHeight; pb.paragraph.fontSize = b.fontSize; pb.paragraph.marker = b.marker; pb.paragraph.markerStyle = b.markerStyle; if (b.textIndent > 0) { pb.paragraph.kpItems.append(KnuthPlass::Item::box(b.textIndent, -1)); } for (const auto &item : b.inlines) { if (item.kind == InlineItem::Kind::LineBreak) { pb.paragraph.kpItems.append(KnuthPlass::Item::penaltyItem(0, -KnuthPlass::kInfinity, false)); continue; } if (item.kind == InlineItem::Kind::Image) { qreal w = 24.0, h = 24.0; if (imageResolver) { QSizeF sz = imageResolver->imageSize(item.imageUrl); if (sz.isValid() && sz.width() > 0 && sz.height() > 0) { w = sz.width(); h = sz.height(); } } if (item.cssWidth > 0) { qreal aspect = w > 0 ? (h / w) : 1.0; w = item.cssWidth; h = item.cssHeight > 0 ? item.cssHeight : (w * aspect); } PreparedWord tok; tok.imageUrl = item.imageUrl; tok.style = item.style; tok.width = w; tok.ascent = h; tok.descent = 0; int tokIdx = pb.paragraph.words.size(); pb.paragraph.words.append(tok); pb.paragraph.kpItems.append(KnuthPlass::Item::box(w, tokIdx)); continue; } QFont font = resolveFont(item.style, baseFontSize, QString()); QFontMetricsF fm(font); qreal spaceW = fm.horizontalAdvance(QLatin1Char(' ')); qreal hyphenW = fm.horizontalAdvance(QLatin1Char('-')); QString rawText = transformText(item.text, item.style.transform); const QStringList words = rawText.split(QLatin1Char(' '), Qt::SkipEmptyParts); for (int wIdx = 0; wIdx < words.size(); ++wIdx) { const QString &wStr = words[wIdx]; if (wStr.contains(QChar(0x00AD))) { const QStringList parts = wStr.split(QChar(0x00AD), Qt::SkipEmptyParts); for (int pIdx = 0; pIdx < parts.size(); ++pIdx) { PreparedWord tok; tok.text = parts[pIdx]; tok.style = item.style; tok.font = font; QString cacheKey = font.key() + QLatin1Char('|') + tok.text; auto it = metricsCache.constFind(cacheKey); if (it != metricsCache.constEnd()) { tok.width = it->width; tok.ascent = it->ascent; tok.descent = it->descent; } else { tok.width = fm.horizontalAdvance(tok.text); tok.ascent = fm.ascent(); tok.descent = fm.descent(); metricsCache.insert(cacheKey, {tok.width, tok.ascent, tok.descent}); } int tokIdx = pb.paragraph.words.size(); pb.paragraph.words.append(tok); pb.paragraph.kpItems.append(KnuthPlass::Item::box(tok.width, tokIdx)); if (pIdx < parts.size() - 1) { pb.paragraph.kpItems.append(KnuthPlass::Item::penaltyItem(hyphenW, 50.0, true, -1)); } } } else { PreparedWord tok; tok.text = wStr; tok.style = item.style; tok.font = font; QString cacheKey = font.key() + QLatin1Char('|') + tok.text; auto it = metricsCache.constFind(cacheKey); if (it != metricsCache.constEnd()) { tok.width = it->width; tok.ascent = it->ascent; tok.descent = it->descent; } else { tok.width = fm.horizontalAdvance(tok.text); tok.ascent = fm.ascent(); tok.descent = fm.descent(); metricsCache.insert(cacheKey, {tok.width, tok.ascent, tok.descent}); } int tokIdx = pb.paragraph.words.size(); pb.paragraph.words.append(tok); pb.paragraph.kpItems.append(KnuthPlass::Item::box(tok.width, tokIdx)); } if (wIdx < words.size() - 1 || rawText.endsWith(QLatin1Char(' '))) { qreal stretch = spaceW * 0.5; qreal shrink = spaceW * 0.333; pb.paragraph.kpItems.append(KnuthPlass::Item::glue(spaceW, stretch, shrink, -1)); } } } KnuthPlass::finishParagraph(pb.paragraph.kpItems); prepared.blocks.append(pb); } break; } } } return prepared; } PreparedChunk prepareChunk(const QString &html, qreal baseFontSize, IBookImageResolver *imageResolver) { ParseParams pp; pp.baseFontSize = baseFontSize; pp.contentWidth = 600; const auto blocks = HtmlBlockParser::parse(html, pp); return prepareBlocks(blocks, baseFontSize, imageResolver); } ChunkLayout layoutPreparedChunk(const PreparedChunk &prepared, const LayoutParams ¶ms) { LayoutWorker worker(params); return worker.run(prepared); } ChunkLayout layoutBlocks(const QVector &blocks, const LayoutParams ¶ms, IBookImageResolver *imageResolver) { PreparedChunk prep = prepareBlocks(blocks, params.fontSize, imageResolver); return layoutPreparedChunk(prep, params); } ChunkLayout layoutChunk(const QString &html, const LayoutParams ¶ms, IBookImageResolver *imageResolver) { PreparedChunk prep = prepareChunk(html, params.fontSize, imageResolver); return layoutPreparedChunk(prep, params); } } // namespace ChunkLayoutEngine