reintroduced epub support

This commit is contained in:
Agel committed 2026-10-25 19:59:23 +01:00
1 parent 49a959a89d
commit d14170a68f
49 files changed
+5048 -205

No files matched your search

@@ -0,0 +1,659 @@
#include "ChunkLayoutEngine.h"
#include <QFontDatabase>
#include <QFontMetricsF>
#include <QHash>
#include <algorithm>
#include <cmath>
#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<int>(std::round(targetSize)));
font.setWeight(static_cast<QFont::Weight>(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 &params)
: 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;
if (dec.background.isValid() || dec.borderLeft > 0 || dec.borderTop > 0 || dec.borderBottom > 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;
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<PreparedWord> activeWords = p.words;
QVector<KnuthPlass::Item> 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.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<ActiveBox> m_boxStack;
};
bool isPureImageBlock(const QVector<InlineItem> &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<BlockItem> &blocks,
qreal baseFontSize,
IBookImageResolver *imageResolver)
{
PreparedChunk prepared;
prepared.blocks.reserve(blocks.size());
// Word metrics cache across the chunk
QHash<QString, WordMetrics> 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 &params)
{
LayoutWorker worker(params);
return worker.run(prepared);
}
ChunkLayout layoutBlocks(const QVector<BlockItem> &blocks,
const LayoutParams &params,
IBookImageResolver *imageResolver)
{
PreparedChunk prep = prepareBlocks(blocks, params.fontSize, imageResolver);
return layoutPreparedChunk(prep, params);
}
ChunkLayout layoutChunk(const QString &html,
const LayoutParams &params,
IBookImageResolver *imageResolver)
{
PreparedChunk prep = prepareChunk(html, params.fontSize, imageResolver);
return layoutPreparedChunk(prep, params);
}
} // namespace ChunkLayoutEngine
@@ -0,0 +1,135 @@
#pragma once
#include <QColor>
#include <QFont>
#include <QMetaType>
#include <QRectF>
#include <QString>
#include <QVector>
#include "HtmlBlockParser.h"
#include "KnuthPlass.h"
class IBookImageResolver;
struct PositionedWordRun {
QString text;
QRectF rect;
qreal baselineY = 0;
QFont font;
QColor color;
QColor background;
bool link = false;
bool underline = false;
bool strikeOut = false;
bool overline = false;
};
struct PositionedLine {
QRectF rect;
qreal baselineY = 0;
QVector<PositionedWordRun> runs;
};
struct PositionedImage {
QString url;
QRectF targetRect;
};
struct PositionedRule {
QRectF rect;
QColor color;
};
struct PositionedDecoration {
QRectF rect;
QColor background;
QColor borderColor;
qreal borderLeft = 0;
qreal borderTop = 0;
qreal borderBottom = 0;
};
struct ChunkLayout {
QVector<PositionedLine> lines;
QVector<PositionedImage> images;
QVector<PositionedRule> rules;
QVector<PositionedDecoration> decorations;
qreal totalHeight = 0;
qreal contentWidth = 0;
};
struct LayoutParams {
qreal contentWidth = 600;
qreal fontSize = 16;
qreal lineSpacing = 1.0;
QString baseFontFamily;
};
namespace ChunkLayoutEngine {
struct PreparedWord {
QString text;
QString imageUrl;
TextStyle style;
QFont font;
qreal width = 0;
qreal ascent = 0;
qreal descent = 0;
};
struct PreparedParagraph {
TextAlign align = TextAlign::Justify;
qreal textIndent = 0;
qreal lineHeight = 0;
qreal fontSize = 16;
QString marker;
TextStyle markerStyle;
QVector<PreparedWord> words;
QVector<KnuthPlass::Item> kpItems;
};
struct PreparedImageBlock {
QString imageUrl;
QSizeF naturalSize;
qreal cssWidth = -1;
qreal cssHeight = -1;
qreal cssMaxWidth = -1;
};
struct PreparedBlock {
enum class Kind { ContainerStart, ContainerEnd, Paragraph, ImageBlock, Rule };
Kind kind = Kind::Paragraph;
BoxStyle box;
PreparedParagraph paragraph;
PreparedImageBlock imageBlock;
QColor ruleColor;
};
struct PreparedChunk {
QVector<PreparedBlock> blocks;
};
PreparedChunk prepareChunk(const QString &html,
qreal baseFontSize,
IBookImageResolver *imageResolver = nullptr);
PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
qreal baseFontSize,
IBookImageResolver *imageResolver = nullptr);
ChunkLayout layoutPreparedChunk(const PreparedChunk &prepared,
const LayoutParams &params);
ChunkLayout layoutChunk(const QString &html,
const LayoutParams &params,
IBookImageResolver *imageResolver = nullptr);
ChunkLayout layoutBlocks(const QVector<BlockItem> &blocks,
const LayoutParams &params,
IBookImageResolver *imageResolver = nullptr);
} // namespace ChunkLayoutEngine
Q_DECLARE_METATYPE(ChunkLayout)
+431
View File
@@ -0,0 +1,431 @@
#include "CssParser.h"
#include <QDomElement>
#include <QRegularExpression>
#include <algorithm>
namespace Css {
namespace {
QString stripComments(const QString &css)
{
QString out;
out.reserve(css.size());
int i = 0;
const int n = css.size();
while (i < n) {
if (i + 1 < n && css[i] == QLatin1Char('/') && css[i + 1] == QLatin1Char('*')) {
const int end = css.indexOf(QLatin1String("*/"), i + 2);
if (end < 0)
break;
i = end + 2;
continue;
}
out += css[i++];
}
return out;
}
// Index of the '}' matching the '{' at `open`, or -1.
int matchingBrace(const QString &s, int open)
{
int depth = 0;
QChar quote;
for (int i = open; i < s.size(); ++i) {
const QChar c = s[i];
if (!quote.isNull()) {
if (c == quote) quote = QChar();
continue;
}
if (c == QLatin1Char('"') || c == QLatin1Char('\'')) quote = c;
else if (c == QLatin1Char('{')) ++depth;
else if (c == QLatin1Char('}') && --depth == 0) return i;
}
return -1;
}
QString unquote(QString s)
{
s = s.trimmed();
if (s.size() >= 2 && (s.front() == QLatin1Char('"') || s.front() == QLatin1Char('\'')) && s.back() == s.front())
s = s.mid(1, s.size() - 2);
return s;
}
QString localTagName(const QDomElement &e)
{
QString tag = e.tagName();
const int colon = tag.indexOf(QLatin1Char(':'));
if (colon >= 0)
tag = tag.mid(colon + 1);
return tag.toLower();
}
bool matchesCompound(const Compound &c, const QDomElement &e)
{
if (!c.tag.isEmpty() && c.tag != localTagName(e))
return false;
if (!c.id.isEmpty() && e.attribute(QStringLiteral("id")) != c.id)
return false;
if (!c.classes.isEmpty()) {
const QStringList cls = e.attribute(QStringLiteral("class")).split(QLatin1Char(' '), Qt::SkipEmptyParts);
for (const QString &want : c.classes)
if (!cls.contains(want))
return false;
}
return true;
}
bool matchesFrom(const Selector &s, int partIdx, const QDomElement &e)
{
if (!matchesCompound(s.parts[partIdx], e))
return false;
if (partIdx == 0)
return true;
const QChar comb = s.combinators[partIdx - 1];
QDomNode p = e.parentNode();
if (comb == QLatin1Char('>')) {
return p.isElement() && matchesFrom(s, partIdx - 1, p.toElement());
}
for (; p.isElement(); p = p.parentNode()) {
if (matchesFrom(s, partIdx - 1, p.toElement()))
return true;
}
return false;
}
std::optional<Compound> parseCompound(QStringView text)
{
Compound c;
int i = 0;
const int n = text.size();
auto isIdent = [](QChar ch) { return ch.isLetterOrNumber() || ch == QLatin1Char('-') || ch == QLatin1Char('_'); };
while (i < n && (isIdent(text[i]) || text[i] == QLatin1Char('*') || text[i] == QLatin1Char('|')))
++i;
QString tag = text.left(i).toString().toLower();
const int bar = tag.indexOf(QLatin1Char('|'));
if (bar >= 0)
tag = tag.mid(bar + 1);
c.tag = (tag == QLatin1String("*")) ? QString() : tag;
while (i < n) {
const QChar kind = text[i++];
const int start = i;
while (i < n && isIdent(text[i]))
++i;
const QString name = text.mid(start, i - start).toString();
if (name.isEmpty())
return std::nullopt;
if (kind == QLatin1Char('.')) c.classes << name;
else if (kind == QLatin1Char('#')) c.id = name;
else return std::nullopt;
}
return c;
}
} // namespace
QVector<Declaration> parseDeclarations(QStringView block)
{
QVector<Declaration> out;
int depth = 0;
QChar quote;
int start = 0;
auto flush = [&](int end) {
const QStringView decl = block.mid(start, end - start).trimmed();
start = end + 1;
const int colon = decl.indexOf(QLatin1Char(':'));
if (colon <= 0)
return;
Declaration d;
d.property = decl.left(colon).trimmed().toString().toLower();
QString value = decl.mid(colon + 1).trimmed().toString();
static const QRegularExpression kImportant(QStringLiteral("!\\s*important\\s*$"),
QRegularExpression::CaseInsensitiveOption);
const auto m = kImportant.match(value);
if (m.hasMatch()) {
d.important = true;
value = value.left(m.capturedStart()).trimmed();
}
d.value = value;
if (!d.property.isEmpty() && !d.value.isEmpty())
out.append(d);
};
for (int i = 0; i < block.size(); ++i) {
const QChar c = block[i];
if (!quote.isNull()) {
if (c == quote) quote = QChar();
continue;
}
if (c == QLatin1Char('"') || c == QLatin1Char('\'')) quote = c;
else if (c == QLatin1Char('(')) ++depth;
else if (c == QLatin1Char(')')) depth = std::max(0, depth - 1);
else if (c == QLatin1Char(';') && depth == 0) flush(i);
}
flush(block.size());
return out;
}
std::optional<Selector> parseSelector(QStringView text)
{
const QString s = text.trimmed().toString();
if (s.isEmpty())
return std::nullopt;
for (QChar bad : {QLatin1Char(':'), QLatin1Char('['), QLatin1Char('+'), QLatin1Char('~')})
if (s.contains(bad))
return std::nullopt;
// Normalise child combinators so tokens are whitespace separated.
QString normalized = s;
normalized.replace(QLatin1Char('>'), QStringLiteral(" > "));
const QStringList tokens = normalized.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts);
Selector sel;
QChar pending = QLatin1Char(' ');
for (const QString &tok : tokens) {
if (tok == QLatin1String(">")) {
if (sel.parts.isEmpty())
return std::nullopt;
pending = QLatin1Char('>');
continue;
}
auto compound = parseCompound(tok);
if (!compound)
return std::nullopt;
if (!sel.parts.isEmpty())
sel.combinators.append(pending);
pending = QLatin1Char(' ');
sel.specificity += (compound->id.isEmpty() ? 0 : 100)
+ 10 * compound->classes.size()
+ (compound->tag.isEmpty() ? 0 : 1);
sel.parts.append(*compound);
}
if (sel.parts.isEmpty() || sel.combinators.size() != sel.parts.size() - 1)
return std::nullopt;
return sel;
}
StyleSheet StyleSheet::parse(const QString &cssIn)
{
StyleSheet sheet;
const QString css = stripComments(cssIn);
int i = 0;
const int n = css.size();
while (i < n) {
while (i < n && css[i].isSpace())
++i;
if (i >= n)
break;
if (css[i] == QLatin1Char('@')) {
const int brace = css.indexOf(QLatin1Char('{'), i);
const int semi = css.indexOf(QLatin1Char(';'), i);
if (semi >= 0 && (brace < 0 || semi < brace)) { // @import, @charset, @namespace
i = semi + 1;
continue;
}
if (brace < 0)
break;
const int close = matchingBrace(css, brace);
if (close < 0)
break;
const QString keyword = css.mid(i + 1, brace - i - 1).trimmed().toLower();
if (keyword == QLatin1String("font-face")) {
FontFace face;
for (const Declaration &d : parseDeclarations(QStringView(css).mid(brace + 1, close - brace - 1))) {
if (d.property == QLatin1String("font-family")) {
face.family = unquote(d.value);
} else if (d.property == QLatin1String("src")) {
static const QRegularExpression kUrl(QStringLiteral("url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)"));
const auto m = kUrl.match(d.value);
if (m.hasMatch() && face.src.isEmpty())
face.src = m.captured(2).trimmed();
} else if (d.property == QLatin1String("font-weight")) {
face.weight = d.value;
} else if (d.property == QLatin1String("font-style")) {
face.style = d.value;
}
}
if (!face.family.isEmpty() && !face.src.isEmpty())
sheet.fontFaces.append(face);
}
// Other at-rules (@media, @page, @supports...) are skipped.
i = close + 1;
continue;
}
const int brace = css.indexOf(QLatin1Char('{'), i);
if (brace < 0)
break;
const int close = matchingBrace(css, brace);
if (close < 0)
break;
const QString selectorText = css.mid(i, brace - i);
const QVector<Declaration> decls = parseDeclarations(QStringView(css).mid(brace + 1, close - brace - 1));
if (!decls.isEmpty()) {
for (const QString &part : selectorText.split(QLatin1Char(','))) {
if (auto sel = parseSelector(part)) {
Rule rule;
rule.selector = *sel;
rule.declarations = decls;
rule.order = sheet.rules.size();
sheet.rules.append(rule);
}
}
}
i = close + 1;
}
return sheet;
}
void StyleSheet::append(const StyleSheet &other)
{
const int base = rules.size();
for (Rule r : other.rules) {
r.order += base;
rules.append(r);
}
fontFaces += other.fontFaces;
}
bool matches(const Selector &selector, const QDomElement &element)
{
if (selector.parts.isEmpty() || element.isNull())
return false;
return matchesFrom(selector, selector.parts.size() - 1, element);
}
QVector<Declaration> cascade(const StyleSheet &sheet, const QDomElement &element)
{
QVector<const Rule *> matched;
for (const Rule &r : sheet.rules)
if (matches(r.selector, element))
matched.append(&r);
std::stable_sort(matched.begin(), matched.end(), [](const Rule *a, const Rule *b) {
if (a->selector.specificity != b->selector.specificity)
return a->selector.specificity < b->selector.specificity;
return a->order < b->order;
});
const QVector<Declaration> inlineDecls = parseDeclarations(element.attribute(QStringLiteral("style")));
QVector<Declaration> out;
for (const Rule *r : std::as_const(matched))
for (const Declaration &d : r->declarations)
if (!d.important) out.append(d);
for (const Declaration &d : inlineDecls)
if (!d.important) out.append(d);
for (const Rule *r : std::as_const(matched))
for (const Declaration &d : r->declarations)
if (d.important) out.append(d);
for (const Declaration &d : inlineDecls)
if (d.important) out.append(d);
return out;
}
QString serialize(const QVector<Declaration> &declarations)
{
QString out;
for (const Declaration &d : declarations) {
if (!out.isEmpty())
out += QLatin1Char(';');
out += d.property + QLatin1Char(':') + d.value;
}
return out;
}
std::optional<qreal> parseLength(QStringView valueIn, const LengthContext &ctx)
{
const QString value = valueIn.trimmed().toString().toLower();
if (value.isEmpty())
return std::nullopt;
static const QRegularExpression kNum(QStringLiteral("^([+-]?(?:\\d+\\.?\\d*|\\.\\d+))([a-z%]*)$"));
const auto m = kNum.match(value);
if (!m.hasMatch())
return std::nullopt;
const qreal num = m.captured(1).toDouble();
const QString unit = m.captured(2);
if (unit.isEmpty())
return num * ctx.absoluteScale;
if (unit == QLatin1String("em")) return num * ctx.em;
if (unit == QLatin1String("rem")) return num * ctx.rem;
if (unit == QLatin1String("ex") || unit == QLatin1String("ch")) return num * ctx.em * 0.5;
if (unit == QLatin1String("%")) return num * ctx.percentBase / 100.0;
if (unit == QLatin1String("px")) return num * ctx.absoluteScale;
if (unit == QLatin1String("pt")) return num * 4.0 / 3.0 * ctx.absoluteScale;
if (unit == QLatin1String("pc")) return num * 16.0 * ctx.absoluteScale;
if (unit == QLatin1String("in")) return num * 96.0 * ctx.absoluteScale;
if (unit == QLatin1String("cm")) return num * 96.0 / 2.54 * ctx.absoluteScale;
if (unit == QLatin1String("mm")) return num * 96.0 / 25.4 * ctx.absoluteScale;
return std::nullopt;
}
QColor parseColor(QStringView valueIn)
{
const QString value = valueIn.trimmed().toString().toLower();
if (value.isEmpty() || value == QLatin1String("inherit") || value == QLatin1String("currentcolor")
|| value == QLatin1String("initial") || value == QLatin1String("unset"))
return {};
if (value == QLatin1String("transparent"))
return QColor(Qt::transparent);
static const QRegularExpression kFunc(QStringLiteral("^(rgba?|hsla?)\\(([^)]*)\\)$"));
const auto m = kFunc.match(value);
if (m.hasMatch()) {
QStringList parts = m.captured(2).split(QRegularExpression(QStringLiteral("[\\s,/]+")), Qt::SkipEmptyParts);
if (parts.size() < 3)
return {};
auto channel = [](const QString &p, qreal scale) {
return p.endsWith(QLatin1Char('%')) ? p.chopped(1).toDouble() / 100.0 * scale : p.toDouble();
};
qreal alpha = 1.0;
if (parts.size() >= 4)
alpha = parts[3].endsWith(QLatin1Char('%')) ? parts[3].chopped(1).toDouble() / 100.0 : parts[3].toDouble();
QColor c;
if (m.captured(1).startsWith(QLatin1String("rgb"))) {
c = QColor::fromRgbF(float(std::clamp(channel(parts[0], 255) / 255.0, 0.0, 1.0)),
float(std::clamp(channel(parts[1], 255) / 255.0, 0.0, 1.0)),
float(std::clamp(channel(parts[2], 255) / 255.0, 0.0, 1.0)));
} else {
const qreal h = std::fmod(parts[0].toDouble(), 360.0) / 360.0;
c = QColor::fromHslF(float(h < 0 ? h + 1 : h),
float(std::clamp(channel(parts[1], 1), 0.0, 1.0)),
float(std::clamp(channel(parts[2], 1), 0.0, 1.0)));
}
c.setAlphaF(float(std::clamp(alpha, 0.0, 1.0)));
return c;
}
const QColor c = QColor::fromString(value);
return c.isValid() ? c : QColor();
}
QStringList splitValue(QStringView value)
{
QStringList out;
QString cur;
int depth = 0;
for (QChar c : value) {
if (c == QLatin1Char('(')) ++depth;
if (c == QLatin1Char(')')) depth = std::max(0, depth - 1);
if (c.isSpace() && depth == 0) {
if (!cur.isEmpty()) out << cur;
cur.clear();
} else {
cur += c;
}
}
if (!cur.isEmpty()) out << cur;
return out;
}
QStringList splitCommaList(QStringView value)
{
QStringList out;
for (const QString &item : value.toString().split(QLatin1Char(','))) {
const QString u = unquote(item);
if (!u.isEmpty()) out << u;
}
return out;
}
} // namespace Css
+84
View File
@@ -0,0 +1,84 @@
#pragma once
#include <QColor>
#include <QString>
#include <QStringList>
#include <QVector>
#include <optional>
class QDomElement;
// Minimal CSS engine for EPUB styling: stylesheet parsing, selector matching
// (type, class, id, compound, descendant and child combinators), cascade, and
// value parsing. Unsupported selectors (pseudo-classes, attribute selectors,
// sibling combinators) are skipped rather than mis-applied.
namespace Css {
struct Declaration {
QString property; // lowercase
QString value; // trimmed, without !important
bool important = false;
};
struct Compound {
QString tag; // lowercase; empty = any
QString id;
QStringList classes;
};
struct Selector {
QVector<Compound> parts; // left to right
QVector<QChar> combinators; // combinators[i] joins parts[i] and parts[i+1]: ' ' or '>'
int specificity = 0;
};
struct Rule {
Selector selector;
QVector<Declaration> declarations;
int order = 0;
};
struct FontFace {
QString family;
QString src; // first url(...) value, unresolved
QString weight;
QString style;
};
struct StyleSheet {
QVector<Rule> rules;
QVector<FontFace> fontFaces;
static StyleSheet parse(const QString &css);
void append(const StyleSheet &other);
};
QVector<Declaration> parseDeclarations(QStringView block);
std::optional<Selector> parseSelector(QStringView text);
bool matches(const Selector &selector, const QDomElement &element);
// Cascade result for one element, in application order (later wins):
// stylesheet normal, inline normal, stylesheet !important, inline !important.
QVector<Declaration> cascade(const StyleSheet &sheet, const QDomElement &element);
QString serialize(const QVector<Declaration> &declarations);
// --- Values -----------------------------------------------------------------
struct LengthContext {
qreal em = 16; // current font size in px
qreal rem = 16; // root (user preference) font size in px
qreal percentBase = 0; // what 100% resolves to
qreal absoluteScale = 1; // scale applied to absolute units (px, pt...) to follow the user's font size
};
std::optional<qreal> parseLength(QStringView value, const LengthContext &ctx);
QColor parseColor(QStringView value);
// Splits a value on top-level whitespace (keeps "rgb(1, 2, 3)" together).
QStringList splitValue(QStringView value);
// Splits a comma-separated list on top-level commas, unquoting each item.
QStringList splitCommaList(QStringView value);
} // namespace Css
@@ -0,0 +1,502 @@
#include "HtmlBlockParser.h"
#include <QDomDocument>
#include <QRegularExpression>
#include <algorithm>
#include "CssParser.h"
#include "backend/formats/HtmlEntities.h"
namespace HtmlBlockParser {
namespace {
struct StyleContext {
TextStyle text;
TextAlign align = TextAlign::Justify;
qreal textIndent = 0;
qreal lineHeight = 0;
bool preformatted = false;
};
QString localName(const QDomElement &e)
{
QString name = e.tagName();
const int idx = name.indexOf(QLatin1Char(':'));
if (idx >= 0)
name = name.mid(idx + 1);
return name.toLower();
}
bool isBlockTag(const QString &tag)
{
static const QStringList kBlocks = {
QStringLiteral("p"), QStringLiteral("div"),
QStringLiteral("h1"), QStringLiteral("h2"),
QStringLiteral("h3"), QStringLiteral("h4"),
QStringLiteral("h5"), QStringLiteral("h6"),
QStringLiteral("blockquote"), QStringLiteral("pre"),
QStringLiteral("ul"), QStringLiteral("ol"),
QStringLiteral("li"), QStringLiteral("dl"),
QStringLiteral("dt"), QStringLiteral("dd"),
QStringLiteral("hr"), QStringLiteral("figure"),
QStringLiteral("svg"), QStringLiteral("figcaption"),
QStringLiteral("section"), QStringLiteral("article"),
QStringLiteral("header"), QStringLiteral("footer"), QStringLiteral("aside"),
QStringLiteral("body")
};
return kBlocks.contains(tag);
}
void applyCssDeclarations(const QVector<Css::Declaration> &decls,
StyleContext &ctx,
BoxStyle &box,
const ParseParams &params)
{
Css::LengthContext lenCtx;
lenCtx.em = ctx.text.fontSize;
lenCtx.rem = params.baseFontSize;
lenCtx.percentBase = params.contentWidth;
lenCtx.absoluteScale = params.baseFontSize / 16.0;
for (const auto &d : decls) {
const QString &prop = d.property;
const QString &val = d.value;
if (prop == QLatin1String("font-family")) {
ctx.text.fontFamilies = Css::splitCommaList(val);
} else if (prop == QLatin1String("font-size")) {
if (val == QLatin1String("xx-small")) ctx.text.fontSize = params.baseFontSize * 0.6;
else if (val == QLatin1String("x-small")) ctx.text.fontSize = params.baseFontSize * 0.75;
else if (val == QLatin1String("small")) ctx.text.fontSize = params.baseFontSize * 0.875;
else if (val == QLatin1String("medium")) ctx.text.fontSize = params.baseFontSize;
else if (val == QLatin1String("large")) ctx.text.fontSize = params.baseFontSize * 1.15;
else if (val == QLatin1String("x-large")) ctx.text.fontSize = params.baseFontSize * 1.5;
else if (val == QLatin1String("xx-large")) ctx.text.fontSize = params.baseFontSize * 2.0;
else if (val == QLatin1String("smaller")) ctx.text.fontSize *= 0.85;
else if (val == QLatin1String("larger")) ctx.text.fontSize *= 1.2;
else {
auto sz = Css::parseLength(val, lenCtx);
if (sz && *sz > 0)
ctx.text.fontSize = *sz;
}
lenCtx.em = ctx.text.fontSize;
} else if (prop == QLatin1String("font-weight")) {
if (val == QLatin1String("bold") || val == QLatin1String("bolder")) ctx.text.weight = 700;
else if (val == QLatin1String("normal") || val == QLatin1String("lighter")) ctx.text.weight = 400;
else {
bool ok;
int w = val.toInt(&ok);
if (ok && w >= 100 && w <= 900)
ctx.text.weight = w;
}
} else if (prop == QLatin1String("font-style")) {
ctx.text.italic = (val == QLatin1String("italic") || val == QLatin1String("oblique"));
} else if (prop == QLatin1String("font-variant")) {
ctx.text.smallCaps = (val == QLatin1String("small-caps"));
} else if (prop == QLatin1String("text-transform")) {
if (val == QLatin1String("uppercase")) ctx.text.transform = TextTransform::Uppercase;
else if (val == QLatin1String("lowercase")) ctx.text.transform = TextTransform::Lowercase;
else if (val == QLatin1String("capitalize")) ctx.text.transform = TextTransform::Capitalize;
else ctx.text.transform = TextTransform::None;
} else if (prop == QLatin1String("letter-spacing")) {
auto ls = Css::parseLength(val, lenCtx);
if (ls) ctx.text.letterSpacing = *ls;
} else if (prop == QLatin1String("text-decoration") || prop == QLatin1String("text-decoration-line")) {
ctx.text.underline = val.contains(QLatin1String("underline"));
ctx.text.strikeOut = val.contains(QLatin1String("line-through"));
ctx.text.overline = val.contains(QLatin1String("overline"));
} else if (prop == QLatin1String("color")) {
QColor c = Css::parseColor(val);
if (c.isValid()) ctx.text.color = c;
} else if (prop == QLatin1String("background-color") || prop == QLatin1String("background")) {
QColor c = Css::parseColor(val);
if (c.isValid()) ctx.text.background = c;
} else if (prop == QLatin1String("text-align")) {
if (val == QLatin1String("left") || val == QLatin1String("start")) ctx.align = TextAlign::Left;
else if (val == QLatin1String("center")) ctx.align = TextAlign::Center;
else if (val == QLatin1String("right") || val == QLatin1String("end")) ctx.align = TextAlign::Right;
else if (val == QLatin1String("justify")) ctx.align = TextAlign::Justify;
} else if (prop == QLatin1String("text-indent")) {
auto ind = Css::parseLength(val, lenCtx);
if (ind) ctx.textIndent = *ind;
} else if (prop == QLatin1String("line-height")) {
bool ok;
qreal lh = val.toDouble(&ok);
if (ok && lh > 0) {
ctx.lineHeight = lh;
} else {
auto len = Css::parseLength(val, lenCtx);
if (len && *len > 0 && ctx.text.fontSize > 0)
ctx.lineHeight = *len / ctx.text.fontSize;
}
} else if (prop == QLatin1String("margin-top")) {
auto m = Css::parseLength(val, lenCtx); if (m) box.marginTop = *m;
} else if (prop == QLatin1String("margin-bottom")) {
auto m = Css::parseLength(val, lenCtx); if (m) box.marginBottom = *m;
} else if (prop == QLatin1String("margin-left")) {
auto m = Css::parseLength(val, lenCtx); if (m) box.marginLeft = *m;
} else if (prop == QLatin1String("margin-right")) {
auto m = Css::parseLength(val, lenCtx); if (m) box.marginRight = *m;
} else if (prop == QLatin1String("padding-top")) {
auto p = Css::parseLength(val, lenCtx); if (p) box.paddingTop = *p;
} else if (prop == QLatin1String("padding-bottom")) {
auto p = Css::parseLength(val, lenCtx); if (p) box.paddingBottom = *p;
} else if (prop == QLatin1String("padding-left")) {
auto p = Css::parseLength(val, lenCtx); if (p) box.paddingLeft = *p;
} else if (prop == QLatin1String("padding-right")) {
auto p = Css::parseLength(val, lenCtx); if (p) box.paddingRight = *p;
} else if (prop == QLatin1String("border-left") || prop == QLatin1String("border-left-width")) {
auto w = Css::parseLength(val, lenCtx); if (w) box.borderLeft = *w;
} else if (prop == QLatin1String("border-top") || prop == QLatin1String("border-top-width")) {
auto w = Css::parseLength(val, lenCtx); if (w) box.borderTop = *w;
} else if (prop == QLatin1String("border-bottom") || prop == QLatin1String("border-bottom-width")) {
auto w = Css::parseLength(val, lenCtx); if (w) box.borderBottom = *w;
} else if (prop == QLatin1String("border-color") || prop == QLatin1String("border-left-color")) {
QColor c = Css::parseColor(val);
if (c.isValid()) box.borderColor = c;
}
}
}
class Builder {
public:
Builder(const ParseParams &params) : m_params(params)
{
StyleContext root;
root.text.fontSize = params.baseFontSize;
m_stack.append(root);
}
QVector<BlockItem> build(const QDomElement &root)
{
walk(root);
finishCurrentParagraph();
return m_blocks;
}
private:
void finishCurrentParagraph()
{
if (m_currentInlines.isEmpty())
return;
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
p.align = m_currentAlign;
p.textIndent = m_currentIndent;
p.lineHeight = m_currentLineHeight;
p.fontSize = m_currentBlockFontSize;
p.preformatted = m_currentPreformatted;
p.marker = m_currentMarker;
p.markerStyle = m_currentMarkerStyle;
p.inlines = std::move(m_currentInlines);
m_blocks.append(p);
m_currentInlines.clear();
m_currentMarker.clear();
m_currentIndent = 0;
}
void startParagraph(const StyleContext &ctx, const QString &marker = {}, const TextStyle &markerStyle = {})
{
finishCurrentParagraph();
m_currentAlign = ctx.align;
m_currentIndent = ctx.textIndent;
m_currentLineHeight = ctx.lineHeight;
m_currentBlockFontSize = ctx.text.fontSize;
m_currentPreformatted = ctx.preformatted;
m_currentMarker = marker;
m_currentMarkerStyle = markerStyle;
}
void appendText(const QString &text, const TextStyle &style, bool pre)
{
if (text.isEmpty())
return;
if (m_currentInlines.isEmpty()) {
startParagraph(m_stack.last());
}
QString processed = text;
if (!pre) {
// Collapse whitespaces
static const QRegularExpression kSpaces(QStringLiteral("\\s+"));
processed.replace(kSpaces, QStringLiteral(" "));
if (m_currentInlines.isEmpty() && processed == QLatin1String(" "))
return;
}
if (processed.isEmpty())
return;
InlineItem item;
item.kind = InlineItem::Kind::Text;
item.text = processed;
item.style = style;
m_currentInlines.append(item);
}
void walk(const QDomNode &node)
{
if (node.isText()) {
const StyleContext &ctx = m_stack.last();
appendText(node.nodeValue(), ctx.text, ctx.preformatted);
return;
}
if (!node.isElement())
return;
const QDomElement el = node.toElement();
const QString tag = localName(el);
if (tag == QLatin1String("head") || tag == QLatin1String("style") || tag == QLatin1String("script"))
return;
StyleContext ctx = m_stack.last();
BoxStyle box;
// Default HTML semantics
if (tag == QLatin1String("h1")) {
ctx.text.fontSize = m_params.baseFontSize * 1.8;
ctx.text.weight = 700;
ctx.textIndent = 0;
box.marginTop = m_params.baseFontSize * 1.0;
box.marginBottom = m_params.baseFontSize * 0.5;
} else if (tag == QLatin1String("h2")) {
ctx.text.fontSize = m_params.baseFontSize * 1.5;
ctx.text.weight = 700;
ctx.textIndent = 0;
box.marginTop = m_params.baseFontSize * 0.8;
box.marginBottom = m_params.baseFontSize * 0.4;
} else if (tag == QLatin1String("h3")) {
ctx.text.fontSize = m_params.baseFontSize * 1.3;
ctx.text.weight = 700;
ctx.textIndent = 0;
box.marginTop = m_params.baseFontSize * 0.6;
box.marginBottom = m_params.baseFontSize * 0.3;
} else if (tag == QLatin1String("h4") || tag == QLatin1String("h5") || tag == QLatin1String("h6")) {
ctx.text.fontSize = m_params.baseFontSize * 1.1;
ctx.text.weight = 700;
ctx.textIndent = 0;
box.marginTop = m_params.baseFontSize * 0.5;
box.marginBottom = m_params.baseFontSize * 0.25;
} else if (tag == QLatin1String("p")) {
box.marginTop = m_params.baseFontSize * 0.25;
box.marginBottom = m_params.baseFontSize * 0.5;
ctx.textIndent = m_params.baseFontSize * 1.25;
} else if (tag == QLatin1String("blockquote")) {
box.marginLeft = m_params.baseFontSize * 1.5;
box.marginRight = m_params.baseFontSize * 1.0;
box.marginTop = m_params.baseFontSize * 0.5;
box.marginBottom = m_params.baseFontSize * 0.5;
box.borderLeft = 3;
box.paddingLeft = m_params.baseFontSize * 0.75;
ctx.text.italic = true;
} else if (tag == QLatin1String("pre")) {
ctx.text.fontFamilies = {QStringLiteral("monospace")};
ctx.preformatted = true;
box.marginTop = m_params.baseFontSize * 0.5;
box.marginBottom = m_params.baseFontSize * 0.5;
} else if (tag == QLatin1String("b") || tag == QLatin1String("strong")) {
ctx.text.weight = 700;
} else if (tag == QLatin1String("i") || tag == QLatin1String("em") || tag == QLatin1String("cite")) {
ctx.text.italic = true;
} else if (tag == QLatin1String("u") || tag == QLatin1String("ins")) {
ctx.text.underline = true;
} else if (tag == QLatin1String("s") || tag == QLatin1String("strike") || tag == QLatin1String("del")) {
ctx.text.strikeOut = true;
} else if (tag == QLatin1String("sub")) {
ctx.text.fontSize *= 0.75;
ctx.text.baselineShift = -ctx.text.fontSize * 0.35;
} else if (tag == QLatin1String("sup")) {
ctx.text.fontSize *= 0.75;
ctx.text.baselineShift = ctx.text.fontSize * 0.45;
} else if (tag == QLatin1String("small")) {
ctx.text.fontSize *= 0.85;
} else if (tag == QLatin1String("code") || tag == QLatin1String("tt") || tag == QLatin1String("kbd")) {
ctx.text.fontFamilies = {QStringLiteral("monospace")};
ctx.text.background = QColor(255, 255, 255, 20);
} else if (tag == QLatin1String("a")) {
ctx.text.underline = true;
ctx.text.link = true;
} else if (tag == QLatin1String("hr")) {
finishCurrentParagraph();
BlockItem r;
r.kind = BlockItem::Kind::Rule;
m_blocks.append(r);
return;
} else if (tag == QLatin1String("br")) {
InlineItem br;
br.kind = InlineItem::Kind::LineBreak;
m_currentInlines.append(br);
return;
} else if (tag == QLatin1String("img") || tag == QLatin1String("image")) {
handleImage(el, ctx);
return;
}
// Apply HTML attribute alignments
if (el.hasAttribute(QStringLiteral("align"))) {
const QString a = el.attribute(QStringLiteral("align")).toLower();
if (a == QLatin1String("center")) ctx.align = TextAlign::Center;
else if (a == QLatin1String("right")) ctx.align = TextAlign::Right;
else if (a == QLatin1String("justify")) ctx.align = TextAlign::Justify;
else if (a == QLatin1String("left")) ctx.align = TextAlign::Left;
}
// Apply CSS declarations from cascaded style attribute
if (el.hasAttribute(QStringLiteral("style"))) {
const auto decls = Css::parseDeclarations(el.attribute(QStringLiteral("style")));
applyCssDeclarations(decls, ctx, box, m_params);
}
const bool isBlock = isBlockTag(tag);
const bool hasBox = (box.marginTop > 0 || box.marginBottom > 0 || box.marginLeft > 0 || box.marginRight > 0
|| box.paddingTop > 0 || box.paddingBottom > 0 || box.paddingLeft > 0 || box.paddingRight > 0
|| box.borderLeft > 0 || box.borderTop > 0 || box.borderBottom > 0);
if (isBlock) {
finishCurrentParagraph();
if (hasBox) {
BlockItem start;
start.kind = BlockItem::Kind::ContainerStart;
start.box = box;
m_blocks.append(start);
}
}
QString marker;
TextStyle markerStyle;
if (tag == QLatin1String("li")) {
marker = QStringLiteral("• ");
markerStyle = ctx.text;
} else if (tag == QLatin1String("dt")) {
ctx.text.weight = 700;
ctx.textIndent = 0;
} else if (tag == QLatin1String("dd")) {
box.marginLeft = m_params.baseFontSize * 1.5;
ctx.textIndent = 0;
}
if (isBlock) {
startParagraph(ctx, marker, markerStyle);
}
m_stack.append(ctx);
for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) {
walk(child);
}
m_stack.removeLast();
if (isBlock) {
finishCurrentParagraph();
if (hasBox) {
BlockItem end;
end.kind = BlockItem::Kind::ContainerEnd;
end.box = box;
m_blocks.append(end);
}
}
}
void handleImage(const QDomElement &el, const StyleContext &ctx)
{
QString src = el.attribute(QStringLiteral("src"));
if (src.isEmpty())
src = el.attribute(QStringLiteral("xlink:href"));
if (src.isEmpty())
src = el.attribute(QStringLiteral("href"));
if (src.isEmpty())
return;
InlineItem item;
item.kind = InlineItem::Kind::Image;
item.imageUrl = src;
Css::LengthContext lenCtx;
lenCtx.em = ctx.text.fontSize;
lenCtx.rem = m_params.baseFontSize;
lenCtx.percentBase = m_params.contentWidth;
lenCtx.absoluteScale = m_params.baseFontSize / 16.0;
if (el.hasAttribute(QStringLiteral("width"))) {
auto w = Css::parseLength(el.attribute(QStringLiteral("width")), lenCtx);
if (w) item.cssWidth = *w;
}
if (el.hasAttribute(QStringLiteral("height"))) {
auto h = Css::parseLength(el.attribute(QStringLiteral("height")), lenCtx);
if (h) item.cssHeight = *h;
}
if (el.hasAttribute(QStringLiteral("style"))) {
const auto decls = Css::parseDeclarations(el.attribute(QStringLiteral("style")));
for (const auto &d : decls) {
if (d.property == QLatin1String("width")) {
auto w = Css::parseLength(d.value, lenCtx); if (w) item.cssWidth = *w;
} else if (d.property == QLatin1String("height")) {
auto h = Css::parseLength(d.value, lenCtx); if (h) item.cssHeight = *h;
} else if (d.property == QLatin1String("max-width")) {
auto mw = Css::parseLength(d.value, lenCtx); if (mw) item.cssMaxWidth = *mw;
}
}
}
if (m_currentInlines.isEmpty()) {
startParagraph(ctx);
}
m_currentInlines.append(item);
}
const ParseParams &m_params;
QVector<StyleContext> m_stack;
QVector<BlockItem> m_blocks;
QVector<InlineItem> m_currentInlines;
TextAlign m_currentAlign = TextAlign::Justify;
qreal m_currentIndent = 0;
qreal m_currentLineHeight = 0;
qreal m_currentBlockFontSize = 16;
bool m_currentPreformatted = false;
QString m_currentMarker;
TextStyle m_currentMarkerStyle;
};
} // namespace
QVector<BlockItem> parse(const QString &html, const ParseParams &params)
{
if (html.trimmed().isEmpty())
return {};
QString wrapped = html.trimmed();
if (!wrapped.startsWith(QLatin1String("<")))
wrapped = QStringLiteral("<p>") + wrapped + QStringLiteral("</p>");
if (!wrapped.contains(QLatin1String("<body")))
wrapped = QStringLiteral("<body>") + wrapped + QStringLiteral("</body>");
const QString safeXml = HtmlEntities::toXmlSafe(wrapped);
QDomDocument doc;
QString errorMsg;
int errorLine = 0, errorColumn = 0;
if (!doc.setContent(safeXml, false, &errorMsg, &errorLine, &errorColumn)) {
// Fallback: return as a simple paragraph
BlockItem b;
b.kind = BlockItem::Kind::Paragraph;
InlineItem textItem;
textItem.kind = InlineItem::Kind::Text;
textItem.text = html;
b.inlines.append(textItem);
return {b};
}
Builder builder(params);
return builder.build(doc.documentElement());
}
} // namespace HtmlBlockParser
@@ -0,0 +1,107 @@
#pragma once
#include <QColor>
#include <QString>
#include <QStringList>
#include <QVector>
// Intermediate representation between HTML chunks and the Knuth-Plass layout.
// All lengths are resolved to pixels for the LayoutParams used at parse time.
enum class TextAlign { Justify, Left, Center, Right };
enum class TextTransform { None, Uppercase, Lowercase, Capitalize };
struct TextStyle {
QStringList fontFamilies; // preferred families in order (may contain generic names); empty = default
qreal fontSize = 16; // px
int weight = 400; // CSS weight 100..900
bool italic = false;
bool smallCaps = false;
TextTransform transform = TextTransform::None;
qreal letterSpacing = 0; // px
bool underline = false;
bool strikeOut = false;
bool overline = false;
bool link = false;
QColor color; // invalid = theme default
QColor background; // invalid = none
qreal baselineShift = 0; // px, positive = raised (superscript)
bool operator==(const TextStyle &o) const {
return fontFamilies == o.fontFamilies
&& qFuzzyCompare(fontSize, o.fontSize)
&& weight == o.weight
&& italic == o.italic
&& smallCaps == o.smallCaps
&& transform == o.transform
&& qFuzzyCompare(letterSpacing, o.letterSpacing)
&& underline == o.underline
&& strikeOut == o.strikeOut
&& overline == o.overline
&& link == o.link
&& color == o.color
&& background == o.background
&& qFuzzyCompare(baselineShift, o.baselineShift);
}
};
struct InlineItem {
enum class Kind { Text, Image, LineBreak };
Kind kind = Kind::Text;
QString text; // whitespace already collapsed unless preformatted
TextStyle style;
QString imageUrl;
qreal cssWidth = -1; // px, -1 = auto
qreal cssHeight = -1;
qreal cssMaxWidth = -1;
};
struct BoxStyle {
qreal marginTop = 0, marginBottom = 0, marginLeft = 0, marginRight = 0;
qreal paddingTop = 0, paddingBottom = 0, paddingLeft = 0, paddingRight = 0;
qreal borderTop = 0, borderBottom = 0, borderLeft = 0, borderRight = 0;
QColor borderColor; // invalid = theme dim colour
QColor background; // invalid = none
// Boxes with a visible top edge stop margins collapsing through them.
bool blocksTopCollapse() const
{
return paddingTop > 0 || borderTop > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
}
bool blocksBottomCollapse() const
{
return paddingBottom > 0 || borderBottom > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
}
};
struct BlockItem {
enum class Kind { ContainerStart, ContainerEnd, Paragraph, Rule };
Kind kind = Kind::Paragraph;
BoxStyle box; // ContainerStart / ContainerEnd (same values on both)
// Paragraph properties
TextAlign align = TextAlign::Justify;
qreal textIndent = 0; // px, first line only
qreal lineHeight = 0; // multiplier of fontSize; 0 = LayoutParams default
qreal fontSize = 16; // block font size (minimum line height basis)
bool preformatted = false;
QString marker; // list marker drawn left of the first line
TextStyle markerStyle;
QVector<InlineItem> inlines;
QColor ruleColor; // Rule only; invalid = theme dim colour
};
struct ParseParams {
qreal baseFontSize = 16; // user preference, px
qreal contentWidth = 600; // px, resolves percentage lengths
};
namespace HtmlBlockParser {
// Parses one standalone HTML chunk (an XHTML fragment whose elements carry
// their cascaded CSS in `style` attributes) into a flat block list.
QVector<BlockItem> parse(const QString &html, const ParseParams &params);
} // namespace HtmlBlockParser
+261
View File
@@ -0,0 +1,261 @@
#include "KnuthPlass.h"
#include <QtGlobal>
#include <cmath>
namespace KnuthPlass {
namespace {
struct Node {
int position = -1; // breakpoint item index (-1 = paragraph start)
int start = 0; // first item index of the line that follows this break
int line = 0;
int fitness = 1;
qreal totalDemerits = 0;
int previous = -1; // arena index of the previous node in the best chain
};
struct Candidate {
qreal demerits = std::numeric_limits<qreal>::infinity();
int from = -1;
};
inline bool isForced(const Item &it)
{
return it.type == ItemType::Penalty && it.penalty <= -kInfinity;
}
inline int fitnessClass(qreal r)
{
if (r < -0.5) return 0;
if (r <= 0.5) return 1;
if (r <= 1.0) return 2;
return 3;
}
class Solver {
public:
Solver(const QVector<Item> &items, qreal lineWidth, const Params &params)
: m_items(items), m_lineWidth(lineWidth), m_params(params)
{
const int n = items.size();
m_sumW.resize(n + 1);
m_sumY.resize(n + 1);
m_sumZ.resize(n + 1);
m_sumW[0] = m_sumY[0] = m_sumZ[0] = 0;
for (int i = 0; i < n; ++i) {
const Item &it = items[i];
const bool counts = it.type != ItemType::Penalty;
m_sumW[i + 1] = m_sumW[i] + (counts ? it.width : 0);
m_sumY[i + 1] = m_sumY[i] + (it.type == ItemType::Glue ? it.stretch : 0);
m_sumZ[i + 1] = m_sumZ[i] + (it.type == ItemType::Glue ? it.shrink : 0);
}
}
qreal ratio(int start, int breakIdx) const
{
const Item &b = m_items[breakIdx];
qreal w = m_sumW[breakIdx] - m_sumW[start];
if (b.type == ItemType::Penalty)
w += b.width;
if (w < m_lineWidth) {
const qreal y = m_sumY[breakIdx] - m_sumY[start];
if (y >= 100000.0)
return 0.0;
return y > 0 ? (m_lineWidth - w) / y : kInfinity;
}
if (w > m_lineWidth) {
const qreal z = m_sumZ[breakIdx] - m_sumZ[start];
return z > 0 ? (m_lineWidth - w) / z : -kInfinity;
}
return 0;
}
// First item of the line that starts after a break at `breakIdx`:
// glue and non-forced penalties following a break are discarded.
int startAfter(int breakIdx) const
{
int j = breakIdx + 1;
while (j < m_items.size()) {
const Item &it = m_items[j];
if (it.type == ItemType::Box || isForced(it))
break;
++j;
}
return j;
}
bool isLegalBreak(int i) const
{
const Item &it = m_items[i];
if (it.type == ItemType::Penalty)
return it.penalty < kInfinity;
if (it.type == ItemType::Glue)
return i > 0 && m_items[i - 1].type == ItemType::Box;
return false;
}
// Returns the arena index of the best final node, or -1 when this pass failed.
int run(qreal tolerance, bool rescue)
{
m_nodes.clear();
m_active.clear();
m_nodes.reserve(m_items.size() / 4 + 8);
m_nodes.append(Node{});
m_active.append(0);
const int n = m_items.size();
QVector<int> keep;
keep.reserve(64);
for (int b = 0; b < n; ++b) {
if (!isLegalBreak(b))
continue;
const Item &brk = m_items[b];
const bool forced = isForced(brk);
Candidate best[4];
int lastDeactivated = -1;
keep.clear();
for (int idx : std::as_const(m_active)) {
const Node &a = m_nodes[idx];
const qreal r = ratio(a.start, b);
if (r < -1 || forced)
lastDeactivated = idx;
else
keep.append(idx);
if (r < -1 || r > tolerance)
continue;
const qreal badness = std::min(100.0 * std::pow(std::abs(r), 3), kInfinity);
qreal d = m_params.linePenalty + badness;
d *= d;
if (brk.type == ItemType::Penalty) {
if (brk.penalty >= 0)
d += brk.penalty * brk.penalty;
else if (brk.penalty > -kInfinity)
d -= brk.penalty * brk.penalty;
}
if (brk.type == ItemType::Penalty && brk.flagged && a.position >= 0) {
const Item &prev = m_items[a.position];
if (prev.type == ItemType::Penalty && prev.flagged)
d += m_params.flaggedDemerits;
}
const int fit = fitnessClass(r);
if (a.position >= 0 && std::abs(fit - a.fitness) > 1)
d += m_params.fitnessDemerits;
const qreal total = a.totalDemerits + d;
if (total < best[fit].demerits) {
best[fit].demerits = total;
best[fit].from = idx;
}
}
m_active.swap(keep);
bool added = false;
const int start = startAfter(b);
for (int fit = 0; fit < 4; ++fit) {
if (best[fit].from < 0)
continue;
Node node;
node.position = b;
node.start = start;
node.line = m_nodes[best[fit].from].line + 1;
node.fitness = fit;
node.totalDemerits = best[fit].demerits;
node.previous = best[fit].from;
m_nodes.append(node);
m_active.append(m_nodes.size() - 1);
added = true;
}
if (m_active.isEmpty() && !added) {
if (!rescue || lastDeactivated < 0)
return -1;
// Last resort: accept an overfull line rather than failing.
Node node;
node.position = b;
node.start = start;
node.line = m_nodes[lastDeactivated].line + 1;
node.fitness = 0;
node.totalDemerits = m_nodes[lastDeactivated].totalDemerits + kInfinity * kInfinity;
node.previous = lastDeactivated;
m_nodes.append(node);
m_active.append(m_nodes.size() - 1);
}
}
int bestIdx = -1;
for (int idx : std::as_const(m_active)) {
if (m_nodes[idx].position != n - 1)
continue;
if (bestIdx < 0 || m_nodes[idx].totalDemerits < m_nodes[bestIdx].totalDemerits)
bestIdx = idx;
}
return bestIdx;
}
QVector<Line> lines(int finalNode) const
{
QVector<Line> out;
for (int idx = finalNode; idx > 0; idx = m_nodes[idx].previous) {
const Node &node = m_nodes[idx];
const Node &prev = m_nodes[node.previous];
const Item &brk = m_items[node.position];
Line line;
line.start = prev.start;
line.end = node.position;
line.ratio = ratio(prev.start, node.position);
line.hyphenated = brk.type == ItemType::Penalty && brk.flagged && brk.width > 0;
out.append(line);
}
std::reverse(out.begin(), out.end());
return out;
}
private:
const QVector<Item> &m_items;
qreal m_lineWidth;
Params m_params;
QVector<qreal> m_sumW, m_sumY, m_sumZ;
QVector<Node> m_nodes;
QVector<int> m_active;
};
} // namespace
void finishParagraph(QVector<Item> &items)
{
// A trailing glue would otherwise become a legal break before the end.
while (!items.isEmpty() && items.last().type == ItemType::Glue)
items.removeLast();
items.append(Item::penaltyItem(0, kInfinity, false));
items.append(Item::glue(0, kInfiniteStretch, 0));
items.append(Item::penaltyItem(0, -kInfinity, false));
}
QVector<Line> breakLines(const QVector<Item> &items, qreal lineWidth, const Params &params)
{
if (items.isEmpty())
return {};
Q_ASSERT(isForced(items.last()));
Solver solver(items, std::max<qreal>(1.0, lineWidth), params);
int finalNode = solver.run(params.tolerance, false);
if (finalNode < 0)
finalNode = solver.run(params.looseTolerance, false);
if (finalNode < 0)
finalNode = solver.run(std::numeric_limits<qreal>::infinity(), true);
if (finalNode < 0)
return {};
return solver.lines(finalNode);
}
} // namespace KnuthPlass
+65
View File
@@ -0,0 +1,65 @@
#pragma once
#include <QVector>
#include <limits>
// Knuth-Plass optimal paragraph line breaking (Knuth & Plass, "Breaking
// Paragraphs into Lines", 1981). Pure computation: no Qt GUI dependency.
//
// Optimisations over the textbook formulation:
// * Prefix sums of width/stretch/shrink give O(1) line measurements between
// any active node and a candidate breakpoint.
// * Break nodes live in one contiguous arena addressed by index, so the inner
// loop performs no heap allocation per node.
namespace KnuthPlass {
constexpr qreal kInfinity = 10000.0; // penalty >= kInfinity forbids a break, <= -kInfinity forces it
constexpr qreal kInfiniteStretch = 1e7; // "fil" stretch used by the paragraph-finishing glue
enum class ItemType { Box, Glue, Penalty };
struct Item {
ItemType type = ItemType::Box;
qreal width = 0;
qreal stretch = 0; // glue only
qreal shrink = 0; // glue only
qreal penalty = 0; // penalty only
bool flagged = false; // penalty only: a hyphenation break
int tag = -1; // opaque caller data (e.g. index of the token this item represents)
static Item box(qreal w, int tag = -1) { Item i; i.type = ItemType::Box; i.width = w; i.tag = tag; return i; }
static Item glue(qreal w, qreal stretch, qreal shrink, int tag = -1)
{
Item i; i.type = ItemType::Glue; i.width = w; i.stretch = stretch; i.shrink = shrink; i.tag = tag; return i;
}
static Item penaltyItem(qreal w, qreal p, bool flagged, int tag = -1)
{
Item i; i.type = ItemType::Penalty; i.width = w; i.penalty = p; i.flagged = flagged; i.tag = tag; return i;
}
};
struct Params {
qreal tolerance = 2.0; // maximum adjustment ratio accepted on the first pass
qreal looseTolerance = 10.0; // second pass when the first finds no feasible solution
qreal linePenalty = 10.0;
qreal flaggedDemerits = 100.0; // consecutive hyphenated lines
qreal fitnessDemerits = 100.0; // adjacent lines differ by more than one fitness class
};
struct Line {
int start = 0; // index of the first item rendered on this line
int end = 0; // index of the breakpoint item (exclusive for rendering, except a penalty's width)
qreal ratio = 0; // adjustment ratio applied to the glue of this line
bool hyphenated = false; // ended at a flagged penalty with width (draw a hyphen)
};
// Appends the standard paragraph ending: finishing glue + forced break.
void finishParagraph(QVector<Item> &items);
// Break the item list into lines of the given width. The list must end with a
// forced break (use finishParagraph). Always returns a solution: when no
// feasible set of breaks exists, overfull lines are produced as a last resort.
QVector<Line> breakLines(const QVector<Item> &items, qreal lineWidth, const Params &params = {});
} // namespace KnuthPlass