visual fix

This commit is contained in:
Agel committed 2026-10-25 22:12:32 +01:00
1 parent 00c88a940c
commit 905c61da52
20 files changed
+669 -32

No files matched your search

+11 -4
View File
@@ -110,14 +110,14 @@ Backend (C++) handles all file I/O, format parsing, text layout calculation, and
| Object | Responsibility |
|---|---|
| `book` (`Book`) | Open/close book, async loading, error state, metadata (title, author, coverImageUrl). Owns `FormatReader`. |
| `readingModel` (`ReadingModel`) | `QAbstractListModel` exposing chunks (`ContentRole`, `LayoutRole`, `PixelHeightRole`), layout updates, reading mode (`isTextMode`, `isMangaMode`), and manga page pairs. |
| `readingModel` (`ReadingModel`) | `QAbstractListModel` exposing chunks (`ContentRole`, `LayoutRole`, `PixelHeightRole`), layout updates, reading mode (`isTextMode`, `isMangaMode`), manga page pairs, and per-book toggles (`pageShift`, `mangaRTL`, `useBookColours`). |
| `readingPreferences` (`ReadingPreferences`) | Font size, line spacing, horizontal margin, vertical margin (`QSettings`). |
| `uiState` (`UiState`) | Current theme, last page, sidebar open state, last file path, custom theme colors, window geometry. |
| `historyModel` (`HistoryModel`) | `QAbstractListModel` of recent books with async metadata extraction and reading progress. |
| `isDebugBuild` | Boolean constant indicating debug build. |
### Additional Registered Types & Providers
- **`KnuthPlassItem`** (`Asteria` module): Custom `QQuickPaintedItem` that draws `ChunkLayout` via `QPainter`.
- **`KnuthPlassItem`** (`Asteria` module): Custom `QQuickPaintedItem` that draws `ChunkLayout` via `QPainter`. Supports `useBookColours`, `surfaceColor`, theme colour overrides, and WCAG contrast safety fallback for publisher colours.
- **`ChunkLayout`**: Declared metatype storing positioned text lines, word runs, inline/block images, rules, and block decorations.
- **Image Providers**:
- `image://fileicon/...`: `FileIconProvider`
@@ -161,11 +161,17 @@ public:
- `ReadingModel` manages a list of HTML chunks.
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
- `HtmlBlockParser` extracts structured blocks (`Paragraph`, `ImageBlock`, `Rule`, `Container`).
- `CssParser` evaluates stylesheets and styles inline tags.
- Block-level `background` sets `BoxStyle::background` (emitted as `PositionedDecoration`), while inline spans apply to `TextStyle::background` (individual word runs).
- Cleans up trailing `<br/>` and trailing/leading whitespace in blocks.
- `CssParser` evaluates stylesheets and styles inline tags. Parses full `border` shorthand, individual borders (`border-top/right/bottom/left`), widths (1-4 values), keywords, styles, and colours.
- `KnuthPlass` computes optimal justified/aligned line breaks.
- `BookImageResolver` resolves embedded image dimensions and URLs.
- Off-thread calculation stores `ChunkLayout` and pixel heights.
- Rendered in a virtualized `ListView` (`cacheBuffer: 600`, high flick velocity) using `KnuthPlassItem`.
- **Publisher Colours vs Theme**: Controlled by per-book `useBookColours` setting (default `false`).
- When off: paints with theme palette (`readingText`, `dimText`, `buttonAccent`), omitting publisher backgrounds and border boxes (semantic blockquote bars with only `borderLeft` and no explicit border colour are drawn in `dimText`).
- When on: paints publisher backgrounds and border colours, using WCAG contrast calculation (`contrastRatio < 3.0`) to automatically select high-contrast black or white text when publisher or theme text colours would be unreadable on the effective background.
- Toggling `useBookColours` operates entirely at paint time in `KnuthPlassItem`—zero off-thread relayout, zero position shift, and instant response.
- Scrolling tracks top visible chunk and `intraOffset`.
### 2. Manga / Comic Mode (`MangaPageView.qml`)
@@ -176,7 +182,7 @@ public:
---
## Position Restoration & State Persistence
- **Position Persistence**: `BookPositionStore` persists `BookPosition` (`chunkIndex`, `intraOffset`, `progress`, `pageShift`, `mangaRTL`) indexed by file content MD5 (`contentHash()`), ensuring state survives file renames or moves.
- **Position Persistence**: `BookPositionStore` persists `BookPosition` (`chunkIndex`, `intraOffset`, `progress`, `pageShift`, `mangaRTL`, `useBookColours`) indexed by file content MD5 (`contentHash()`), ensuring state survives file renames or moves.
- **Restoration Flow**:
- Text mode: `ReadingModel` computes layout for the saved anchor chunk first, then emits `restoreReady(chunkIndex, intraOffset)`. `ScrollPageView` positions the `ListView` at `chunkIndex` and applies `intraOffset`.
- Comic mode: `restoreReady(chunkIndex)` triggers `MangaPageView.showPair(pairIndexForChunk(chunkIndex))`.
@@ -258,6 +264,7 @@ src/
Footer.qml
Header.qml
LabeledSlider.qml
LabeledSwitch.qml
MangaPageView.qml
ScrollPageView.qml
SettingsPopup.qml
+3
View File
@@ -169,6 +169,7 @@ set_source_files_properties(src/qml/components/ErrorPopup.qml PROPERTIES QT_RESO
set_source_files_properties(src/qml/components/SideBarButton.qml PROPERTIES QT_RESOURCE_ALIAS components/SideBarButton.qml)
set_source_files_properties(src/qml/components/FlatIconButton.qml PROPERTIES QT_RESOURCE_ALIAS components/FlatIconButton.qml)
set_source_files_properties(src/qml/components/LabeledSlider.qml PROPERTIES QT_RESOURCE_ALIAS components/LabeledSlider.qml)
set_source_files_properties(src/qml/components/LabeledSwitch.qml PROPERTIES QT_RESOURCE_ALIAS components/LabeledSwitch.qml)
set_source_files_properties(src/qml/pages/StarterPage.qml PROPERTIES QT_RESOURCE_ALIAS pages/StarterPage.qml)
set_source_files_properties(src/qml/pages/ReaderPage.qml PROPERTIES QT_RESOURCE_ALIAS pages/ReaderPage.qml)
set_source_files_properties(src/qml/components/SettingsPopup.qml PROPERTIES QT_RESOURCE_ALIAS components/SettingsPopup.qml)
@@ -195,6 +196,7 @@ qt_add_qml_module(asteria-qt
src/qml/components/SideBarButton.qml
src/qml/components/FlatIconButton.qml
src/qml/components/LabeledSlider.qml
src/qml/components/LabeledSwitch.qml
src/qml/components/SettingsPopup.qml
src/qml/pages/StarterPage.qml
src/qml/pages/ReaderPage.qml
@@ -279,6 +281,7 @@ target_link_libraries(CssParserTest PRIVATE Qt6::Gui Qt6::Xml)
add_asteria_test(ChunkLayoutEngineTest tests/reading/ChunkLayoutEngineTest.cpp
src/backend/reading/BookImageResolver.cpp
src/backend/reading/KnuthPlassItem.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/WebImageProvider.cpp
src/backend/formats/HtmlEntities.cpp
+16
View File
@@ -60,6 +60,7 @@ bool ReadingModel::measuring() const { return m_measuring; }
int ReadingModel::totalPagePairs() const { return m_pagination.count(); }
bool ReadingModel::pageShift() const { return m_pageShift; }
bool ReadingModel::mangaRTL() const { return m_mangaRTL; }
bool ReadingModel::useBookColours() const { return m_useBookColours; }
double ReadingModel::progress() const
{
@@ -203,6 +204,7 @@ void ReadingModel::saveCurrentPosition(int chunkIndex, qreal intraOffset)
pos.progress = m_progress;
pos.pageShift = m_pageShift;
pos.mangaRTL = m_mangaRTL;
pos.useBookColours = m_useBookColours;
m_positions.save(m_reader->contentHash(), pos);
emit positionSaved();
}
@@ -359,6 +361,16 @@ void ReadingModel::setMangaRTL(bool rtl)
emit mangaRTLChanged();
}
void ReadingModel::setUseBookColours(bool enabled)
{
if (m_useBookColours == enabled) return;
m_useBookColours = enabled;
if (m_reader) {
m_positions.setUseBookColours(m_reader->contentHash(), enabled);
}
emit useBookColoursChanged();
}
void ReadingModel::loadPages()
{
m_pages.clear();
@@ -398,13 +410,17 @@ void ReadingModel::setReader(FormatReader *reader)
m_progress = pos.progress;
m_pageShift = pos.pageShift;
m_mangaRTL = pos.mangaRTL;
m_useBookColours = pos.useBookColours;
emit progressChanged();
emit useBookColoursChanged();
} else {
m_progress = 0.0;
m_intraOffset = 0.0;
m_pageShift = true;
m_mangaRTL = true;
m_useBookColours = false;
emit progressChanged();
emit useBookColoursChanged();
}
if (m_isTextMode && m_reader) {
+7
View File
@@ -25,6 +25,7 @@ class ReadingModel : public QAbstractListModel {
Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged)
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged)
Q_PROPERTY(bool useBookColours READ useBookColours NOTIFY useBookColoursChanged)
public:
enum ReadingRoles {
@@ -50,6 +51,7 @@ public:
int totalPagePairs() const;
bool pageShift() const;
bool mangaRTL() const;
bool useBookColours() const;
void setReader(FormatReader *reader);
void setImageResolver(IBookImageResolver *resolver);
@@ -73,6 +75,9 @@ public:
Q_INVOKABLE void setPageShift(bool shift, int currentPairIndex = 0);
Q_INVOKABLE void setMangaRTL(bool rtl);
// Per-book publisher colour toggle
Q_INVOKABLE void setUseBookColours(bool enabled);
signals:
void modeChanged();
void measuringChanged();
@@ -82,6 +87,7 @@ signals:
void totalPagePairsChanged();
void pageShiftChanged();
void mangaRTLChanged();
void useBookColoursChanged();
void pagePairsRebuilt(int newPairIndex);
void restoreReady(int chunkIndex, qreal intraOffset = 0.0);
void positionSaved();
@@ -113,6 +119,7 @@ private:
bool m_mangaLandscape = false;
bool m_pageShift = true;
bool m_mangaRTL = true;
bool m_useBookColours = false;
QVector<PageInfo> m_pages;
MangaPagination m_pagination;
+85 -15
View File
@@ -58,6 +58,24 @@ void KnuthPlassItem::setDimColor(const QColor &c)
}
}
void KnuthPlassItem::setSurfaceColor(const QColor &c)
{
if (m_surfaceColor != c) {
m_surfaceColor = c;
emit colorsChanged();
update();
}
}
void KnuthPlassItem::setUseBookColours(bool v)
{
if (m_useBookColours != v) {
m_useBookColours = v;
emit useBookColoursChanged();
update();
}
}
void KnuthPlassItem::setHorizontalMargin(qreal m)
{
if (!qFuzzyCompare(m_horizontalMargin, m)) {
@@ -67,6 +85,26 @@ void KnuthPlassItem::setHorizontalMargin(qreal m)
}
}
qreal KnuthPlassItem::relativeLuminance(const QColor &c)
{
auto channel = [](qreal val) {
return (val <= 0.03928) ? (val / 12.92) : std::pow((val + 0.055) / 1.055, 2.4);
};
const qreal r = channel(c.redF());
const qreal g = channel(c.greenF());
const qreal b = channel(c.blueF());
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
qreal KnuthPlassItem::contrastRatio(const QColor &c1, const QColor &c2)
{
const qreal l1 = relativeLuminance(c1);
const qreal l2 = relativeLuminance(c2);
const qreal lighter = std::max(l1, l2);
const qreal darker = std::min(l1, l2);
return (lighter + 0.05) / (darker + 0.05);
}
void KnuthPlassItem::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
{
QQuickPaintedItem::geometryChange(newGeometry, oldGeometry);
@@ -91,19 +129,30 @@ void KnuthPlassItem::paint(QPainter *painter)
QRectF r = dec.rect;
r.translate(offX, 0);
if (dec.background.isValid()) {
painter->fillRect(r, dec.background);
}
if (m_useBookColours) {
if (dec.background.isValid() && dec.background.alpha() > 0) {
painter->fillRect(r, dec.background);
}
QColor borderColor = dec.borderColor.isValid() ? dec.borderColor : m_dimColor;
if (dec.borderLeft > 0) {
painter->fillRect(QRectF(r.left(), r.top(), dec.borderLeft, r.height()), borderColor);
}
if (dec.borderTop > 0) {
painter->fillRect(QRectF(r.left(), r.top(), r.width(), dec.borderTop), borderColor);
}
if (dec.borderBottom > 0) {
painter->fillRect(QRectF(r.left(), r.bottom() - dec.borderBottom, r.width(), dec.borderBottom), borderColor);
QColor borderColor = dec.borderColor.isValid() ? dec.borderColor : m_dimColor;
if (dec.borderLeft > 0) {
painter->fillRect(QRectF(r.left(), r.top(), dec.borderLeft, r.height()), borderColor);
}
if (dec.borderTop > 0) {
painter->fillRect(QRectF(r.left(), r.top(), r.width(), dec.borderTop), borderColor);
}
if (dec.borderBottom > 0) {
painter->fillRect(QRectF(r.left(), r.bottom() - dec.borderBottom, r.width(), dec.borderBottom), borderColor);
}
if (dec.borderRight > 0) {
painter->fillRect(QRectF(r.right() - dec.borderRight, r.top(), dec.borderRight, r.height()), borderColor);
}
} else {
// When useBookColours is false, omit publisher boxes/borders.
// Only draw semantic quotation bars (e.g. <blockquote> with only borderLeft).
if (dec.borderLeft > 0 && dec.borderTop == 0 && dec.borderBottom == 0 && dec.borderRight == 0 && !dec.borderColor.isValid()) {
painter->fillRect(QRectF(r.left(), r.top(), dec.borderLeft, r.height()), m_dimColor);
}
}
}
@@ -111,7 +160,8 @@ void KnuthPlassItem::paint(QPainter *painter)
for (const auto &rule : m_layout.rules) {
QRectF r = rule.rect;
r.translate(offX, 0);
painter->fillRect(r, rule.color.isValid() ? rule.color : m_dimColor);
QColor rc = (m_useBookColours && rule.color.isValid()) ? rule.color : m_dimColor;
painter->fillRect(r, rc);
}
// 3. Draw text runs
@@ -120,18 +170,38 @@ void KnuthPlassItem::paint(QPainter *painter)
bool hasFont = false;
bool hasPen = false;
const QColor baseSurface = m_surfaceColor.isValid() ? m_surfaceColor : QColor(25, 29, 53);
for (const auto &line : m_layout.lines) {
for (const auto &run : line.runs) {
QRectF r = run.rect;
r.translate(offX, 0);
// Highlight background
if (run.background.isValid()) {
if (m_useBookColours && run.background.isValid() && run.background.alpha() > 0) {
painter->fillRect(r, run.background);
}
// Word text
QColor fg = run.color.isValid() ? run.color : (run.link ? m_linkColor : m_textColor);
QColor fg;
if (!m_useBookColours) {
fg = run.link ? m_linkColor : m_textColor;
} else {
QColor effectiveBg = (run.background.isValid() && run.background.alpha() > 0)
? run.background
: ((run.surfaceBackground.isValid() && run.surfaceBackground.alpha() > 0)
? run.surfaceBackground
: baseSurface);
QColor desired = run.color.isValid() ? run.color : (run.link ? m_linkColor : m_textColor);
if (contrastRatio(desired, effectiveBg) < 3.0) {
qreal crBlack = contrastRatio(Qt::black, effectiveBg);
qreal crWhite = contrastRatio(Qt::white, effectiveBg);
fg = (crBlack >= crWhite) ? QColor(Qt::black) : QColor(Qt::white);
} else {
fg = desired;
}
}
if (!hasPen || currentPenColor != fg) {
painter->setPen(fg);
currentPenColor = fg;
+14
View File
@@ -15,6 +15,8 @@ class KnuthPlassItem : public QQuickPaintedItem {
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor NOTIFY colorsChanged)
Q_PROPERTY(QColor linkColor READ linkColor WRITE setLinkColor NOTIFY colorsChanged)
Q_PROPERTY(QColor dimColor READ dimColor WRITE setDimColor NOTIFY colorsChanged)
Q_PROPERTY(QColor surfaceColor READ surfaceColor WRITE setSurfaceColor NOTIFY colorsChanged)
Q_PROPERTY(bool useBookColours READ useBookColours WRITE setUseBookColours NOTIFY useBookColoursChanged)
Q_PROPERTY(qreal horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged)
public:
@@ -32,9 +34,18 @@ public:
QColor dimColor() const { return m_dimColor; }
void setDimColor(const QColor &c);
QColor surfaceColor() const { return m_surfaceColor; }
void setSurfaceColor(const QColor &c);
bool useBookColours() const { return m_useBookColours; }
void setUseBookColours(bool v);
qreal horizontalMargin() const { return m_horizontalMargin; }
void setHorizontalMargin(qreal m);
static qreal relativeLuminance(const QColor &c);
static qreal contrastRatio(const QColor &c1, const QColor &c2);
void paint(QPainter *painter) override;
static void setImageResolver(BookImageResolver *resolver);
@@ -45,6 +56,7 @@ protected:
signals:
void layoutChanged();
void colorsChanged();
void useBookColoursChanged();
void horizontalMarginChanged();
private:
@@ -54,6 +66,8 @@ private:
QColor m_textColor = QColor(196, 200, 216); // Theme.readingText default
QColor m_linkColor = QColor(87, 133, 193); // Theme.buttonAccent default
QColor m_dimColor = QColor(113, 115, 140); // Theme.dimText default
QColor m_surfaceColor = QColor(25, 29, 53); // Theme.surface default
bool m_useBookColours = false;
qreal m_horizontalMargin = 0;
static BookImageResolver *s_imageResolver;
@@ -159,8 +159,10 @@ private:
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) {
if (dec.background.isValid() || dec.borderLeft > 0 || dec.borderTop > 0
|| dec.borderBottom > 0 || dec.borderRight > 0) {
m_layout.decorations.append(dec);
}
@@ -247,6 +249,14 @@ private:
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);
@@ -379,6 +389,7 @@ private:
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;
@@ -19,6 +19,7 @@ struct PositionedWordRun {
QFont font;
QColor color;
QColor background;
QColor surfaceBackground;
bool link = false;
bool underline = false;
bool strikeOut = false;
@@ -48,6 +49,7 @@ struct PositionedDecoration {
qreal borderLeft = 0;
qreal borderTop = 0;
qreal borderBottom = 0;
qreal borderRight = 0;
};
struct ChunkLayout {
+42
View File
@@ -398,6 +398,48 @@ QColor parseColor(QStringView valueIn)
return c.isValid() ? c : QColor();
}
BorderSide parseBorderSide(QStringView valueIn, const LengthContext &ctx)
{
BorderSide res;
const QStringList tokens = splitValue(valueIn);
bool hasStyle = false;
for (const QString &token : tokens) {
const QString lower = token.trimmed().toLower();
if (lower.isEmpty())
continue;
if (lower == QLatin1String("none") || lower == QLatin1String("hidden")) {
res.width = 0.0;
res.isNone = true;
} else if (lower == QLatin1String("thin")) {
res.width = 1.0 * ctx.absoluteScale;
} else if (lower == QLatin1String("medium")) {
res.width = 3.0 * ctx.absoluteScale;
} else if (lower == QLatin1String("thick")) {
res.width = 5.0 * ctx.absoluteScale;
} else if (lower == QLatin1String("solid") || lower == QLatin1String("dotted")
|| lower == QLatin1String("dashed") || lower == QLatin1String("double")
|| lower == QLatin1String("groove") || lower == QLatin1String("ridge")
|| lower == QLatin1String("inset") || lower == QLatin1String("outset")) {
hasStyle = true;
} else if (auto len = parseLength(token, ctx)) {
res.width = *len;
} else {
QColor c = parseColor(token);
if (c.isValid()) {
res.color = c;
}
}
}
if (hasStyle && !res.width.has_value() && !res.isNone) {
res.width = 3.0 * ctx.absoluteScale;
}
return res;
}
QStringList splitValue(QStringView value)
{
QStringList out;
+7
View File
@@ -72,8 +72,15 @@ struct LengthContext {
qreal absoluteScale = 1; // scale applied to absolute units (px, pt...) to follow the user's font size
};
struct BorderSide {
std::optional<qreal> width;
QColor color;
bool isNone = false;
};
std::optional<qreal> parseLength(QStringView value, const LengthContext &ctx);
QColor parseColor(QStringView value);
BorderSide parseBorderSide(QStringView value, const LengthContext &ctx);
// Splits a value on top-level whitespace (keeps "rgb(1, 2, 3)" together).
QStringList splitValue(QStringView value);
+124 -12
View File
@@ -51,7 +51,8 @@ bool isBlockTag(const QString &tag)
void applyCssDeclarations(const QVector<Css::Declaration> &decls,
StyleContext &ctx,
BoxStyle &box,
const ParseParams &params)
const ParseParams &params,
bool isBlock)
{
Css::LengthContext lenCtx;
lenCtx.em = ctx.text.fontSize;
@@ -111,7 +112,20 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls,
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;
if (c.isValid() && c.alpha() > 0) {
if (isBlock) {
box.background = c;
ctx.text.background = QColor();
} else {
ctx.text.background = c;
}
} else if (val.trimmed() == QLatin1String("none") || val.trimmed() == QLatin1String("transparent")) {
if (isBlock) {
box.background = QColor();
} else {
ctx.text.background = QColor();
}
}
} 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;
@@ -146,15 +160,72 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls,
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")) {
} else if (prop == QLatin1String("border")) {
auto b = Css::parseBorderSide(val, lenCtx);
if (b.width) {
box.borderTop = *b.width;
box.borderRight = *b.width;
box.borderBottom = *b.width;
box.borderLeft = *b.width;
}
if (b.color.isValid()) box.borderColor = b.color;
} else if (prop == QLatin1String("border-top")) {
auto b = Css::parseBorderSide(val, lenCtx);
if (b.width) box.borderTop = *b.width;
if (b.color.isValid()) box.borderColor = b.color;
} else if (prop == QLatin1String("border-right")) {
auto b = Css::parseBorderSide(val, lenCtx);
if (b.width) box.borderRight = *b.width;
if (b.color.isValid()) box.borderColor = b.color;
} else if (prop == QLatin1String("border-bottom")) {
auto b = Css::parseBorderSide(val, lenCtx);
if (b.width) box.borderBottom = *b.width;
if (b.color.isValid()) box.borderColor = b.color;
} else if (prop == QLatin1String("border-left")) {
auto b = Css::parseBorderSide(val, lenCtx);
if (b.width) box.borderLeft = *b.width;
if (b.color.isValid()) box.borderColor = b.color;
} else if (prop == QLatin1String("border-top-width")) {
auto w = Css::parseBorderSide(val, lenCtx).width; if (w) box.borderTop = *w;
} else if (prop == QLatin1String("border-right-width")) {
auto w = Css::parseBorderSide(val, lenCtx).width; if (w) box.borderRight = *w;
} else if (prop == QLatin1String("border-bottom-width")) {
auto w = Css::parseBorderSide(val, lenCtx).width; if (w) box.borderBottom = *w;
} else if (prop == QLatin1String("border-left-width")) {
auto w = Css::parseBorderSide(val, lenCtx).width; if (w) box.borderLeft = *w;
} else if (prop == QLatin1String("border-width")) {
const QStringList tokens = Css::splitValue(val);
QVector<qreal> widths;
for (const QString &tok : tokens) {
auto w = Css::parseBorderSide(tok, lenCtx).width;
if (w) widths.append(*w);
}
if (widths.size() == 1) {
box.borderTop = box.borderRight = box.borderBottom = box.borderLeft = widths[0];
} else if (widths.size() == 2) {
box.borderTop = box.borderBottom = widths[0];
box.borderRight = box.borderLeft = widths[1];
} else if (widths.size() == 3) {
box.borderTop = widths[0];
box.borderRight = box.borderLeft = widths[1];
box.borderBottom = widths[2];
} else if (widths.size() >= 4) {
box.borderTop = widths[0];
box.borderRight = widths[1];
box.borderBottom = widths[2];
box.borderLeft = widths[3];
}
} else if (prop == QLatin1String("border-color") || prop.endsWith(QLatin1String("-color"))) {
QColor c = Css::parseColor(val);
if (c.isValid()) box.borderColor = c;
} else if (prop == QLatin1String("border-style") || prop.endsWith(QLatin1String("-style"))) {
if (val.contains(QLatin1String("none")) || val.contains(QLatin1String("hidden"))) {
if (prop == QLatin1String("border-top-style")) box.borderTop = 0;
else if (prop == QLatin1String("border-right-style")) box.borderRight = 0;
else if (prop == QLatin1String("border-bottom-style")) box.borderBottom = 0;
else if (prop == QLatin1String("border-left-style")) box.borderLeft = 0;
else { box.borderTop = box.borderRight = box.borderBottom = box.borderLeft = 0; }
}
}
}
}
@@ -178,6 +249,45 @@ public:
private:
void finishCurrentParagraph()
{
if (m_currentInlines.isEmpty())
return;
if (!m_currentPreformatted) {
// Drop trailing line breaks and whitespace
while (!m_currentInlines.isEmpty()) {
const auto &last = m_currentInlines.last();
if (last.kind == InlineItem::Kind::LineBreak) {
m_currentInlines.removeLast();
} else if (last.kind == InlineItem::Kind::Text && last.text.trimmed().isEmpty()) {
m_currentInlines.removeLast();
} else {
break;
}
}
if (!m_currentInlines.isEmpty() && m_currentInlines.last().kind == InlineItem::Kind::Text) {
while (m_currentInlines.last().text.endsWith(QLatin1Char(' '))) {
m_currentInlines.last().text.chop(1);
}
}
// Drop leading whitespace
while (!m_currentInlines.isEmpty()) {
const auto &first = m_currentInlines.first();
if (first.kind == InlineItem::Kind::Text && first.text.trimmed().isEmpty()) {
m_currentInlines.removeFirst();
} else {
break;
}
}
if (!m_currentInlines.isEmpty() && m_currentInlines.first().kind == InlineItem::Kind::Text) {
while (m_currentInlines.first().text.startsWith(QLatin1Char(' '))) {
m_currentInlines.first().text.remove(0, 1);
}
}
}
if (m_currentInlines.isEmpty())
return;
@@ -348,16 +458,18 @@ private:
else if (a == QLatin1String("left")) ctx.align = TextAlign::Left;
}
const bool isBlock = isBlockTag(tag);
// 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);
applyCssDeclarations(decls, ctx, box, m_params, isBlock);
}
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);
|| box.borderLeft > 0 || box.borderTop > 0 || box.borderBottom > 0 || box.borderRight > 0
|| box.background.isValid());
if (isBlock) {
finishCurrentParagraph();
+11
View File
@@ -16,6 +16,7 @@ BookPosition BookPositionStore::load(const QByteArray &contentMd5)
pos.progress = d.value(QStringLiteral("progress"), 0.0).toReal();
pos.pageShift = d.value(QStringLiteral("pageShift"), true).toBool();
pos.mangaRTL = d.value(QStringLiteral("mangaRTL"), true).toBool();
pos.useBookColours = d.value(QStringLiteral("useBookColours"), false).toBool();
return pos;
}
@@ -29,9 +30,19 @@ void BookPositionStore::save(const QByteArray &contentMd5, const BookPosition &p
{QStringLiteral("progress"), pos.progress},
{QStringLiteral("pageShift"), pos.pageShift},
{QStringLiteral("mangaRTL"), pos.mangaRTL},
{QStringLiteral("useBookColours"), pos.useBookColours},
});
}
void BookPositionStore::setUseBookColours(const QByteArray &contentMd5, bool enabled)
{
if (contentMd5.isEmpty())
return;
BookPosition pos = load(contentMd5);
pos.useBookColours = enabled;
save(contentMd5, pos);
}
QString BookPositionStore::sectionKey(const QByteArray &contentMd5)
{
return QStringLiteral("saved-progress/") + QString::fromLatin1(contentMd5.toHex());
+4
View File
@@ -10,6 +10,7 @@ struct BookPosition {
qreal progress = 0.0; // Normalized [0..1] scroll/reading progress
bool pageShift = true; // Comic mode only
bool mangaRTL = true; // Comic mode only
bool useBookColours = false; // Text mode only
};
class BookPositionStore {
@@ -22,6 +23,9 @@ public:
// Save the current position for a book identified by MD5 of its contents.
void save(const QByteArray &contentMd5, const BookPosition &pos);
// Update only the useBookColours preference for a book without modifying its saved position.
void setUseBookColours(const QByteArray &contentMd5, bool enabled);
private:
AppState &m_state;
+68
View File
@@ -0,0 +1,68 @@
import QtQuick
import QtQuick.Controls
import Asteria
Row {
id: root
property string label: ""
property string description: ""
property alias checked: switchControl.checked
signal toggled(bool checked)
width: parent ? parent.width : implicitWidth
height: Math.max(textCol.implicitHeight, switchControl.implicitHeight)
spacing: 12
Column {
id: textCol
width: root.width - switchControl.width - root.spacing
anchors.verticalCenter: parent.verticalCenter
spacing: 2
Text {
width: parent.width
text: root.label
font.pixelSize: 13
color: ThemeManager.currentTheme.uiText
elide: Text.ElideRight
}
Text {
width: parent.width
text: root.description
font.pixelSize: 11
color: ThemeManager.currentTheme.dimText
visible: text.length > 0
wrapMode: Text.WordWrap
}
}
Switch {
id: switchControl
anchors.verticalCenter: parent.verticalCenter
indicator: Rectangle {
implicitWidth: 36
implicitHeight: 20
radius: 10
color: switchControl.checked ? ThemeManager.currentTheme.buttonAccent : ThemeManager.currentTheme.scrollbarThumb
Rectangle {
x: switchControl.checked ? parent.width - width - 2 : 2
anchors.verticalCenter: parent.verticalCenter
width: 16
height: 16
radius: 8
color: "#ffffff"
Behavior on x {
NumberAnimation { duration: 150 }
}
}
}
onToggled: root.toggled(checked)
}
}
+2
View File
@@ -123,6 +123,8 @@ Rectangle {
textColor: ThemeManager.currentTheme.readingText
linkColor: ThemeManager.currentTheme.buttonAccent
dimColor: ThemeManager.currentTheme.dimText
surfaceColor: ThemeManager.currentTheme.surface
useBookColours: readingModel.useBookColours
horizontalMargin: readingPreferences.horizontalMargin
}
}
+9
View File
@@ -141,6 +141,15 @@ Item {
valueText: value.toFixed(1) + "\u00d7"
onCommitted: function(v) { readingPreferences.lineSpacing = v }
}
LabeledSwitch {
width: parent.width
label: "Use book colours"
description: "Apply publisher text and background colours for this book"
visible: readingModel.isTextMode
checked: readingModel.useBookColours
onToggled: function(c) { readingModel.setUseBookColours(c) }
}
}
}
}
+36
View File
@@ -207,6 +207,42 @@ private slots:
QVERIFY(!model.isTextMode());
QCOMPARE(model.rowCount(), 0);
}
void useBookColoursToggleAndPersistence()
{
Ctx ctx;
ReadingModel model(*ctx.store);
FakeTextReader reader;
QCOMPARE(model.useBookColours(), false);
// Pre-save position with useBookColours = true for reader
BookPosition savedPos;
savedPos.chunkIndex = 1;
savedPos.useBookColours = true;
ctx.store->save(reader.contentHash(), savedPos);
QSignalSpy spy(&model, &ReadingModel::useBookColoursChanged);
model.setReader(&reader);
QCOMPARE(model.useBookColours(), true);
QVERIFY(spy.count() >= 1);
// Toggle to false
spy.clear();
model.setUseBookColours(false);
QCOMPARE(model.useBookColours(), false);
QCOMPARE(spy.count(), 1);
// Verify it was persisted to store
BookPosition loaded = ctx.store->load(reader.contentHash());
QCOMPARE(loaded.useBookColours, false);
// Setting reader to null resets useBookColours to false
model.setUseBookColours(true);
QCOMPARE(model.useBookColours(), true);
model.setReader(nullptr);
QCOMPARE(model.useBookColours(), false);
}
};
QTEST_MAIN(ReadingModelTest)
+146
View File
@@ -1,5 +1,6 @@
#include <QtTest>
#include "backend/reading/BookImageResolver.h"
#include "backend/reading/KnuthPlassItem.h"
#include "backend/reading/layout/ChunkLayoutEngine.h"
class MockImageResolver : public IBookImageResolver {
@@ -165,6 +166,151 @@ private slots:
QCOMPARE(l1.contentWidth, 300.0);
QCOMPARE(l2.contentWidth, 600.0);
}
void calibreHeaderLayout()
{
const QString html = QStringLiteral(
"<h1 style=\"background-color: #e7e7e7; border: 1px solid black; font-size: 1.375em; text-align: left;\">"
"<a id=\"TOC_1\"></a>СЛУГА КУПЦА <br class=\"calibre9\"/></h1>"
);
LayoutParams params;
params.contentWidth = 600;
params.fontSize = 16;
params.lineSpacing = 1.2;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
// Should have exactly 1 block decoration for the h1 box
QCOMPARE(layout.decorations.size(), 1);
const auto &dec = layout.decorations[0];
QCOMPARE(dec.background, QColor(0xe7, 0xe7, 0xe7));
QCOMPARE(dec.borderColor, QColor(Qt::black));
QCOMPARE(dec.borderLeft, 1.0);
QCOMPARE(dec.borderRight, 1.0);
QCOMPARE(dec.borderTop, 1.0);
QCOMPARE(dec.borderBottom, 1.0);
// Trailing <br/> must be stripped and not produce a spurious empty second line
QCOMPARE(layout.lines.size(), 1);
QVERIFY(!layout.lines[0].runs.isEmpty());
// Words must NOT have individual highlight backgrounds
for (const auto &run : layout.lines[0].runs) {
QVERIFY(!run.background.isValid());
// But they should know the enclosing box background
QCOMPARE(run.surfaceBackground, QColor(0xe7, 0xe7, 0xe7));
}
}
void inlineBackgrounds()
{
const QString html = QStringLiteral("<p>Normal <span style=\"background-color: yellow;\">highlighted</span> text</p>");
LayoutParams params;
params.contentWidth = 600;
params.fontSize = 16;
params.lineSpacing = 1.2;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
// No container box decorations for an inline span
QCOMPARE(layout.decorations.size(), 0);
QVERIFY(!layout.lines.isEmpty());
bool foundYellow = false;
bool foundNormal = false;
for (const auto &run : layout.lines[0].runs) {
if (run.text.contains(QLatin1String("highlighted"))) {
QCOMPARE(run.background, QColor(Qt::yellow));
foundYellow = true;
} else if (run.text.contains(QLatin1String("Normal"))) {
QVERIFY(!run.background.isValid());
foundNormal = true;
}
}
QVERIFY(foundYellow);
QVERIFY(foundNormal);
}
void nestedBackgroundContainer()
{
const QString html = QStringLiteral("<div style=\"background-color: #ff0000;\"><p>Inner text</p></div>");
LayoutParams params;
params.contentWidth = 600;
params.fontSize = 16;
params.lineSpacing = 1.2;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QCOMPARE(layout.decorations.size(), 1);
QCOMPARE(layout.decorations[0].background, QColor(0xff, 0, 0));
QVERIFY(!layout.lines.isEmpty());
QVERIFY(!layout.lines[0].runs.isEmpty());
// Enclosing background is inherited as surfaceBackground
QCOMPARE(layout.lines[0].runs[0].surfaceBackground, QColor(0xff, 0, 0));
// But not as run.background
QVERIFY(!layout.lines[0].runs[0].background.isValid());
}
void contrastRatioHelper()
{
QColor lightBg(0xe7, 0xe7, 0xe7);
QColor darkBg(0x19, 0x1d, 0x35);
qreal crLightBlack = KnuthPlassItem::contrastRatio(Qt::black, lightBg);
qreal crLightWhite = KnuthPlassItem::contrastRatio(Qt::white, lightBg);
QVERIFY(crLightBlack > 10.0);
QVERIFY(crLightWhite < 2.0);
qreal crDarkBlack = KnuthPlassItem::contrastRatio(Qt::black, darkBg);
qreal crDarkWhite = KnuthPlassItem::contrastRatio(Qt::white, darkBg);
QVERIFY(crDarkWhite > 10.0);
QVERIFY(crDarkBlack < 2.0);
}
void knuthPlassItemPaintBoxSuppression()
{
const QString html = QStringLiteral(
"<h1 style=\"background-color: #e7e7e7; border: 2px solid black;\">Header Title</h1>"
);
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QCOMPARE(layout.decorations.size(), 1);
KnuthPlassItem item;
item.setSize(QSizeF(400, 200));
item.setLayout(QVariant::fromValue(layout));
// When useBookColours is false:
item.setUseBookColours(false);
QImage imgFalse(400, 200, QImage::Format_ARGB32_Premultiplied);
imgFalse.fill(Qt::transparent);
{
QPainter p(&imgFalse);
item.paint(&p);
}
// When useBookColours is true:
item.setUseBookColours(true);
QImage imgTrue(400, 200, QImage::Format_ARGB32_Premultiplied);
imgTrue.fill(Qt::transparent);
{
QPainter p(&imgTrue);
item.paint(&p);
}
const auto &dec = layout.decorations[0];
int testX = int(dec.rect.left());
int testY = int(dec.rect.top());
// With useBookColours = false, (testX, testY) should be transparent (no background, no border box)
QCOMPARE(imgFalse.pixelColor(testX, testY).alpha(), 0);
// With useBookColours = true, (testX, testY) is drawn with border or background
QVERIFY(imgTrue.pixelColor(testX, testY).alpha() > 0);
}
};
QTEST_MAIN(ChunkLayoutEngineTest)
+38
View File
@@ -53,6 +53,44 @@ private slots:
QCOMPARE(c5, QColor(Qt::red));
}
void parseBorders()
{
Css::LengthContext ctx;
ctx.em = 16.0;
ctx.rem = 16.0;
ctx.percentBase = 500.0;
ctx.absoluteScale = 1.0;
auto b1 = Css::parseBorderSide(QStringLiteral("1px solid Black"), ctx);
QVERIFY(b1.width.has_value());
QCOMPARE(*b1.width, 1.0);
QCOMPARE(b1.color, QColor(Qt::black));
QVERIFY(!b1.isNone);
auto b2 = Css::parseBorderSide(QStringLiteral("none"), ctx);
QVERIFY(b2.width.has_value());
QCOMPARE(*b2.width, 0.0);
QVERIFY(b2.isNone);
auto b3 = Css::parseBorderSide(QStringLiteral("thin dotted #cccccc"), ctx);
QVERIFY(b3.width.has_value());
QCOMPARE(*b3.width, 1.0);
QCOMPARE(b3.color, QColor(0xcc, 0xcc, 0xcc));
auto b4 = Css::parseBorderSide(QStringLiteral("2px"), ctx);
QVERIFY(b4.width.has_value());
QCOMPARE(*b4.width, 2.0);
auto b5 = Css::parseBorderSide(QStringLiteral("solid red"), ctx);
QVERIFY(b5.width.has_value());
QCOMPARE(*b5.width, 3.0); // Default medium width when style is present
QCOMPARE(b5.color, QColor(Qt::red));
auto b6 = Css::parseBorderSide(QStringLiteral("1px inset"), ctx);
QVERIFY(b6.width.has_value());
QCOMPARE(*b6.width, 1.0);
}
void stylesheetParsingAndCascade()
{
const QString css = QStringLiteral(
+32
View File
@@ -25,6 +25,7 @@ private slots:
QCOMPARE(pos.progress, 0.0);
QCOMPARE(pos.pageShift, true);
QCOMPARE(pos.mangaRTL, true);
QCOMPARE(pos.useBookColours, false);
}
void saveAndLoad()
@@ -119,6 +120,37 @@ private slots:
const BookPosition pos = store.load(QByteArray());
QCOMPARE(pos.chunkIndex, 0);
}
void setUseBookColoursPreservesPosition()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-ubc-XXXXXX.ini"));
(void)f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
BookPositionStore store(appState);
const QByteArray hash = QByteArray("ubc-test-hash");
BookPosition p;
p.chunkIndex = 12;
p.intraOffset = 45.5;
p.progress = 0.35;
p.pageShift = true;
p.mangaRTL = false;
p.useBookColours = false;
store.save(hash, p);
// Update only useBookColours
store.setUseBookColours(hash, true);
const BookPosition updated = store.load(hash);
QCOMPARE(updated.useBookColours, true);
QCOMPARE(updated.chunkIndex, 12);
QCOMPARE(updated.intraOffset, 45.5);
QCOMPARE(updated.progress, 0.35);
QCOMPARE(updated.pageShift, true);
QCOMPARE(updated.mangaRTL, false);
}
};
QTEST_MAIN(BookPositionStoreTest)