ZaStoGram_desktop/Telegram/SourceFiles/test/test_capture.cpp
John Preston cee5c94af7 [ai] Add a stress kit runner and a Release test harness
Task: 2026/10/30/run-the-widget-stress-kit-at-v0-4-0-on-a-release-build-without-lto
2026-11-05 17:12:56 +04:00

1183 lines
34 KiB
C++

/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#if defined _DEBUG || defined TDESKTOP_RELEASE_TEST_HARNESS
#include "test/test_capture.h"
#include "test/test_log.h"
#include "ui/layers/box_layer_widget.h"
#include "ui/ui_utility.h"
#include "ui/widgets/elastic_scroll.h"
#include "styles/palette.h"
#include <QtGui/QPainter>
#include <QtWidgets/QAbstractScrollArea>
namespace Test {
namespace {
constexpr auto kBlankSpreadThreshold = 6;
constexpr auto kContactSheetGap = 8;
constexpr auto kCoverageSamples = 32;
constexpr auto kUnpaintedMinPermille = 100;
constexpr auto kBackgroundOwnerHops = 6;
constexpr auto kWalkedChainHead = 3;
constexpr auto kStrictDepth = 32;
constexpr auto kChannelBits = 8;
constexpr auto kChannelMask = quint32(0xFF);
[[nodiscard]] QString WithPngExtension(const QString &name) {
return name.endsWith(u".png"_q, Qt::CaseInsensitive)
? name
: (name + u".png"_q);
}
[[nodiscard]] std::vector<QPoint> SamplePoints(const QSize &size) {
auto result = std::vector<QPoint>();
const auto columns = std::min(size.width(), kCoverageSamples);
const auto rows = std::min(size.height(), kCoverageSamples);
if (columns < 1 || rows < 1) {
return result;
}
result.reserve(columns * rows);
for (auto y = 0; y != rows; ++y) {
for (auto x = 0; x != columns; ++x) {
result.push_back(QPoint(
((2 * x + 1) * size.width()) / (2 * columns),
((2 * y + 1) * size.height()) / (2 * rows)));
}
}
return result;
}
[[nodiscard]] int SampledMatchPermille(
const QImage &image,
const QColor &color) {
const auto points = SamplePoints(image.size());
if (points.empty()) {
return 0;
}
const auto reference = color.rgb();
auto matched = 0;
for (const auto &point : points) {
if (image.pixelColor(point).rgb() == reference) {
++matched;
}
}
return (1000 * matched) / int(points.size());
}
[[nodiscard]] int UnpaintedPermille(
not_null<QWidget*> widget,
const QRect &logicalRect) {
if (widget->testAttribute(Qt::WA_OpaquePaintEvent)) {
return 0;
}
const auto rect = logicalRect.isEmpty()
? widget->rect()
: logicalRect.intersected(widget->rect());
if (rect.isEmpty()) {
return 0;
}
const auto firstSentinel = QColor(255, 0, 255);
const auto secondSentinel = QColor(0, 255, 0);
const auto first = Ui::GrabWidgetToImage(widget, rect, firstSentinel);
const auto second = Ui::GrabWidgetToImage(widget, rect, secondSentinel);
if (first.isNull() || first.size() != second.size()) {
return 0;
}
const auto points = SamplePoints(first.size());
if (points.empty()) {
return 0;
}
const auto firstRgb = firstSentinel.rgb();
const auto secondRgb = secondSentinel.rgb();
auto unpainted = 0;
for (const auto &point : points) {
if (first.pixelColor(point).rgb() == firstRgb
&& second.pixelColor(point).rgb() == secondRgb) {
++unpainted;
}
}
return (1000 * unpainted) / int(points.size());
}
[[nodiscard]] QString BackgroundOwnerDetails(
not_null<QWidget*> widget,
const QRect &logicalRect) {
const auto rect = logicalRect.isEmpty() ? widget->rect() : logicalRect;
const auto top = widget->window();
auto ancestor = (widget.get() == top) ? nullptr : widget->parentWidget();
for (auto hop = 0; ancestor && (hop != kBackgroundOwnerHops); ++hop) {
const auto mapped = Ui::MapFrom(ancestor, widget, rect)
.intersected(ancestor->rect());
if (!mapped.isEmpty()) {
const auto unpainted = UnpaintedPermille(ancestor, mapped);
if (unpainted < kUnpaintedMinPermille) {
return u"grab %1 instead (unpainted %2/1000)%3"_q
.arg(WidgetDescription(ancestor))
.arg(unpainted)
.arg(dynamic_cast<Ui::BoxLayerWidget*>(ancestor)
? u" - Test::PaintingLayerRoot() resolves it"_q
: QString());
}
}
ancestor = (ancestor == top) ? nullptr : ancestor->parentWidget();
}
return u"no ancestor within %1 parents paints a background"_q
.arg(kBackgroundOwnerHops);
}
[[nodiscard]] QString BlankRootDetails(
not_null<QWidget*> widget,
const QImage &image,
const QRect &logicalRect,
bool logCoverage = true) {
if (image.isNull()
|| widget->testAttribute(Qt::WA_OpaquePaintEvent)
|| widget->testAttribute(Qt::WA_NoSystemBackground)) {
return QString();
}
const auto harnessThemeBase = st::windowBg->c;
const auto baseMatched = SampledMatchPermille(image, harnessThemeBase);
if (!baseMatched) {
return QString();
}
const auto unpainted = UnpaintedPermille(widget, logicalRect);
if (logCoverage) {
Note(u"capture coverage: harnessThemeBase=%1/1000 unpainted=%2/1000 "
u"(threshold %3/1000)"_q
.arg(baseMatched)
.arg(unpainted)
.arg(kUnpaintedMinPermille));
}
if (unpainted < kUnpaintedMinPermille) {
return QString();
}
return u"render root paints no background of its own: %1 has neither "
u"Qt::WA_OpaquePaintEvent nor Qt::WA_NoSystemBackground, and %2/1000 "
u"sampled points were painted by neither the widget nor its "
u"children; the harness theme base is active st::windowBg %3 "
u"(%4/1000 of the grab matches that base) "
u"- %5"_q
.arg(WidgetDescription(widget))
.arg(unpainted)
.arg(harnessThemeBase.name())
.arg(baseMatched)
.arg(BackgroundOwnerDetails(widget, logicalRect));
}
// The walk a refusal prints always names the window it stopped at, and never
// more than kWalkedChainHead entries before it, so a target buried deep in a
// widget tree cannot turn one refusal into a multi-kilobyte log line.
[[nodiscard]] QString ElidedChain(const QStringList &walked) {
if (walked.size() <= kWalkedChainHead + 1) {
return walked.join(u" < "_q);
}
auto shown = QStringList();
for (auto i = 0; i != kWalkedChainHead; ++i) {
shown.push_back(walked[i]);
}
shown.push_back(u"\u2026"_q);
shown.push_back(walked.back());
return shown.join(u" < "_q);
}
[[nodiscard]] QWidget *MappedClipper(QWidget *origin) {
for (auto widget = origin; widget; widget = widget->parentWidget()) {
if (const auto elastic = dynamic_cast<Ui::ElasticScroll*>(widget)) {
return elastic;
} else if (const auto area = dynamic_cast<QAbstractScrollArea*>(widget)) {
return area->viewport();
} else if (widget == widget->window()) {
break;
}
}
return nullptr;
}
// Qt's ancestry stops at the window, so a widget of another top level is
// never inside |owner|.
[[nodiscard]] bool InsideOwner(
not_null<QWidget*> owner,
not_null<QWidget*> widget) {
return (owner == widget) || owner->isAncestorOf(widget);
}
[[nodiscard]] QString MappedTargetText(const MappedTarget &reading) {
return u"mapped-target: %1 local=%2 mapped=%3 inViewport=%4 viewport=%5"
u"%6%7"_q
.arg(reading.identity.isEmpty() ? u"<none>"_q : reading.identity)
.arg(RectText(reading.local))
.arg(RectText(reading.mapped))
.arg(RectText(reading.inViewport))
.arg(reading.viewport
? WidgetDescription(reading.viewport.data())
: u"<none>"_q)
.arg(reading.binding.isEmpty()
? QString()
: u" binding=%1"_q.arg(reading.binding))
.arg(reading.refusal.isEmpty()
? QString()
: u" - %1"_q.arg(reading.refusal));
}
// WidgetDescription takes not_null, so a destroyed painted widget prints
// as <gone>.
[[nodiscard]] QString MappedRectText(const MappedRect &target) {
const auto widget = target.widget();
return u"%1 %2 rect=%3"_q.arg(
target.parentRelative() ? u"in parent of"_q : u"local to"_q,
widget ? WidgetDescription(widget) : u"<gone>"_q,
RectText(target.rect()));
}
// A refusal of the typed reading itself, before any mapping: the requested
// rect and the bound rect stay printable, nothing is resolved.
[[nodiscard]] MappedTarget TypedRefusal(
not_null<QWidget*> owner,
const MappedRect &target,
QString refusal) {
const auto origin = target.origin();
return {
.local = target.rect(),
.identity = u"origin=%1 owner=%2"_q.arg(
origin ? WidgetDescription(origin) : u"<none>"_q,
WidgetDescription(owner)),
.refusal = std::move(refusal),
.binding = MappedRectText(target),
};
}
[[nodiscard]] QString ViaWindowText(const WindowMappedCapture &reading) {
return u"window-mapped capture: target=%1 window=%2 mapped=%3 - a blank "
u"frame is a Note and never a FAIL, because the decisive oracle for a "
u"widget that paints no opaque background of its own is textual and "
u"this capture only corroborates it%4"_q
.arg(reading.identity.isEmpty() ? u"<none>"_q : reading.identity)
.arg(reading.window
? WidgetDescription(reading.window.data())
: u"<none>"_q)
.arg(RectText(reading.mapped))
.arg(reading.refusal.isEmpty()
? QString()
: u" - %1"_q.arg(reading.refusal));
}
[[nodiscard]] QString InvalidRenderText(const StrictRender &render) {
if (!render.refusal.isEmpty()) {
return u"the render was refused"_q;
} else if (!render.owner) {
return u"the render owner is gone"_q;
}
return u"the render has no image"_q;
}
// The first applicable refusal name, empty when the two records describe
// the same render path and comparable images.
[[nodiscard]] QString StrictRefusal(
const StrictRender &a,
const StrictRender &b) {
if (!a.valid()) {
return u"invalid-a: %1"_q.arg(InvalidRenderText(a));
} else if (!b.valid()) {
return u"invalid-b: %1"_q.arg(InvalidRenderText(b));
} else if (a.owner != b.owner) {
return u"render-owner-differs"_q;
} else if (a.rendered != b.rendered) {
return u"render-path-differs: rendered=%1 vs %2"_q.arg(
RectText(a.rendered),
RectText(b.rendered));
} else if (a.crop != b.crop) {
return u"crop-differs: crop=%1 vs %2"_q.arg(
RectText(a.crop),
RectText(b.crop));
} else if (a.image.size() != b.image.size()) {
return u"decoded-size-differs: %1x%2 vs %3x%4"_q
.arg(a.image.width())
.arg(a.image.height())
.arg(b.image.width())
.arg(b.image.height());
} else if (a.image.devicePixelRatio() != b.image.devicePixelRatio()) {
return u"dpr-differs: %1 vs %2"_q
.arg(a.image.devicePixelRatio())
.arg(b.image.devicePixelRatio());
} else if (a.image.format() != b.image.format()) {
return u"format-differs: %1 vs %2"_q
.arg(int(a.image.format()))
.arg(int(b.image.format()));
} else if (a.image.depth() != kStrictDepth) {
return u"unsupported-depth: %1"_q.arg(a.image.depth());
}
return QString();
}
[[nodiscard]] bool StrictComparable(const QImage &a, const QImage &b) {
return !a.isNull()
&& (a.size() == b.size())
&& (a.devicePixelRatio() == b.devicePixelRatio())
&& (a.format() == b.format())
&& (a.depth() == kStrictDepth);
}
// Every 32-bit pixel value of two comparable images, line by line, so a
// padded bytesPerLine is never read as pixels.
[[nodiscard]] StrictComparison CountStrictPixels(
const QImage &a,
const QImage &b) {
auto result = StrictComparison{
.compared = a.width() * a.height(),
.differing = 0,
.maxChannelDelta = 0,
};
for (auto y = 0; y != a.height(); ++y) {
const auto lineA = reinterpret_cast<const quint32*>(
a.constScanLine(y));
const auto lineB = reinterpret_cast<const quint32*>(
b.constScanLine(y));
for (auto x = 0; x != a.width(); ++x) {
const auto valueA = lineA[x];
const auto valueB = lineB[x];
if (valueA == valueB) {
continue;
} else if (!result.differing) {
result.first = QPoint(x, y);
}
++result.differing;
for (auto shift = 0; shift != kStrictDepth; shift += kChannelBits) {
const auto channelA = int((valueA >> shift) & kChannelMask);
const auto channelB = int((valueB >> shift) & kChannelMask);
result.maxChannelDelta = std::max(
result.maxChannelDelta,
std::abs(channelA - channelB));
}
}
}
return result;
}
} // namespace
QString RectText(const QRect &rect) {
return u"%1,%2 %3x%4"_q
.arg(rect.x())
.arg(rect.y())
.arg(rect.width())
.arg(rect.height());
}
QString MisframedDetails(
not_null<QWidget*> widget,
const QRect &logicalRect) {
const auto bounds = widget->rect();
if (!logicalRect.isEmpty() && bounds.contains(logicalRect)) {
return QString();
}
const auto inside = bounds.intersected(logicalRect);
return u"requested rect is not fully inside the grabbed widget: "
u"requested=%1 widget=%2 inside=%3 rows=%4/%5 columns=%6/%7"_q
.arg(RectText(logicalRect), RectText(bounds), RectText(inside))
.arg(inside.height())
.arg(logicalRect.height())
.arg(inside.width())
.arg(logicalRect.width());
}
QString WidgetDescription(not_null<QWidget*> widget) {
const auto &instance = *widget;
return u"%1 %2"_q.arg(
QString::fromUtf8(typeid(instance).name()),
RectText(widget->geometry()));
}
QImage GrabWidget(not_null<QWidget*> widget) {
return Ui::GrabWidgetToImage(widget, QRect(), st::windowBg->c);
}
QImage GrabRect(
not_null<QWidget*> widget,
const QRect &logicalRect) {
const auto bounded = logicalRect.intersected(widget->rect());
return bounded.isEmpty()
? QImage()
: Ui::GrabWidgetToImage(widget, bounded, st::windowBg->c);
}
bool LooksBlank(const QImage &image) {
if (image.isNull() || image.width() < 2 || image.height() < 2) {
return true;
}
auto minLuma = 255;
auto maxLuma = 0;
const auto columns = std::min(image.width(), 32);
const auto rows = std::min(image.height(), 32);
for (auto y = 0; y != rows; ++y) {
for (auto x = 0; x != columns; ++x) {
const auto pixel = image.pixelColor(
(x * (image.width() - 1)) / std::max(columns - 1, 1),
(y * (image.height() - 1)) / std::max(rows - 1, 1));
const auto luma = int(std::round(255 * pixel.lightnessF()));
minLuma = std::min(minLuma, luma);
maxLuma = std::max(maxLuma, luma);
}
}
return (maxLuma - minLuma) < kBlankSpreadThreshold;
}
bool PreparedWidgetCapture::prepare(QWidget *widget) {
_widget = nullptr;
_image = QImage();
_globalGeometry = QRect();
if (!widget) {
_pendingReason = u"target does not exist"_q;
return false;
} else if (!widget->isVisible()) {
_pendingReason = u"target is not visible: %1"_q.arg(
WidgetDescription(widget));
return false;
} else if (widget->size().isEmpty()) {
_pendingReason = u"target has empty geometry: %1"_q.arg(
WidgetDescription(widget));
return false;
}
const auto image = GrabWidget(widget);
if (LooksBlank(image)) {
_pendingReason = u"target grab still looks blank: %1"_q.arg(
WidgetDescription(widget));
return false;
}
const auto blankRoot = BlankRootDetails(widget, image, QRect(), false);
if (!blankRoot.isEmpty()) {
_pendingReason = blankRoot;
return false;
}
_widget = widget;
_image = image;
_globalGeometry = QRect(widget->mapToGlobal(QPoint()), widget->size());
_pendingReason = QString();
return true;
}
bool PreparedWidgetCapture::prepare(
QWidget *owner,
QWidget *origin,
const QRect &localRect) {
_widget = nullptr;
_image = QImage();
_globalGeometry = QRect();
const auto reading = ReadMappedTarget(owner, origin, localRect);
if (!reading.resolved()) {
_pendingReason = reading.refusal;
return false;
}
const auto image = GrabRect(reading.owner.data(), reading.mapped);
if (LooksBlank(image)) {
_pendingReason = u"mapped target grab still looks blank: %1 mapped=%2"_q
.arg(reading.identity, RectText(reading.mapped));
return false;
}
const auto blankRoot = BlankRootDetails(
reading.owner.data(),
image,
reading.mapped,
false);
if (!blankRoot.isEmpty()) {
_pendingReason = blankRoot;
return false;
}
_widget = reading.owner;
_image = image;
_globalGeometry = QRect(
reading.owner->mapToGlobal(reading.mapped.topLeft()),
reading.mapped.size());
_pendingReason = QString();
return true;
}
bool PreparedWidgetCapture::prepare(
QWidget *owner,
const MappedRect &target) {
const auto reading = ReadMappedTarget(owner, target);
if (!reading.resolved()) {
invalidate(reading.refusal);
return false;
}
return prepare(
reading.owner.data(),
reading.origin.data(),
target.rect());
}
bool PreparedWidgetCapture::prepareCrop(
QWidget *owner,
QWidget *descendant,
const QRect &crop) {
invalidate(QString());
if (!owner || !descendant) {
invalidate(u"no painted owner or descendant was handed to the "
u"checked full-owner crop: owner=%1 descendant=%2"_q.arg(
owner ? WidgetDescription(owner) : u"<none>"_q,
descendant ? WidgetDescription(descendant) : u"<none>"_q));
return false;
} else if (descendant == owner) {
invalidate(u"owner-as-origin substitution: %1 cannot certify a "
u"descendant's scroll viewport"_q.arg(WidgetDescription(owner)));
return false;
} else if (!InsideOwner(owner, descendant)) {
invalidate(u"descendant is not inside the painted owner: "
u"descendant=%1 owner=%2"_q.arg(
WidgetDescription(descendant),
WidgetDescription(owner)));
return false;
}
const auto reading = ReadMappedTarget(
owner,
descendant,
descendant->rect());
if (!reading.resolved()) {
invalidate(u"descendant: "_q + reading.refusal);
return false;
}
const auto misframed = MisframedDetails(owner, crop);
if (!misframed.isEmpty()) {
invalidate(u"crop: %1 owner=%2"_q.arg(
misframed,
WidgetDescription(owner)));
return false;
} else if (!prepare(owner)) {
return false;
}
const auto pixels = DevicePixelRect(crop, _image.devicePixelRatio());
if (!_image.rect().contains(pixels)) {
invalidate(u"device crop is not fully inside the full-owner render: "
u"requested=%1 pixels=%2 image=%3x%4 dpr=%5 owner=%6"_q
.arg(RectText(crop))
.arg(RectText(pixels))
.arg(_image.width())
.arg(_image.height())
.arg(_image.devicePixelRatio())
.arg(WidgetDescription(owner)));
return false;
}
const auto cropped = Crop(_image, pixels);
if (cropped.size() != pixels.size()) {
invalidate(u"cropped extent requested=%1x%2 actual=%3x%4: "
u"crop=%5 owner=%6"_q
.arg(pixels.width())
.arg(pixels.height())
.arg(cropped.width())
.arg(cropped.height())
.arg(RectText(crop))
.arg(WidgetDescription(owner)));
return false;
}
_image = cropped;
_globalGeometry = QRect(owner->mapToGlobal(crop.topLeft()), crop.size());
return true;
}
void PreparedWidgetCapture::invalidate(QString reason) {
_widget = nullptr;
_image = QImage();
_globalGeometry = QRect();
_pendingReason = std::move(reason);
}
bool PreparedWidgetCapture::save(const QString &name) {
if (!_widget || _image.isNull()) {
Fail(
u"prepared capture %1"_q.arg(name),
_pendingReason.isEmpty()
? u"no accepted frame"_q
: _pendingReason);
return false;
}
LogGeometry(name, _globalGeometry);
const auto path = SaveImage(_image, name);
if (path.isEmpty()) {
Fail(u"prepared capture %1"_q.arg(name), u"could not save image"_q);
return false;
}
return true;
}
QWidget *PreparedWidgetCapture::widget() const {
return _widget.data();
}
const QImage &PreparedWidgetCapture::image() const {
return _image;
}
QString PreparedWidgetCapture::pendingReason() const {
return _pendingReason;
}
QString SaveImage(const QImage &image, const QString &name) {
if (image.isNull()) {
return QString();
}
const auto path = ScreenshotsDir() + WithPngExtension(name);
if (!image.save(path, "PNG")) {
return QString();
}
const auto relative = path.mid(EvidenceDir().size())
.replace(QChar('\\'), u"\\\\"_q)
.replace(QChar('"'), u"\\\""_q);
LogRaw(u"SCREENSHOT: \""_q + relative + QChar('"'));
return path;
}
bool CaptureWidget(not_null<QWidget*> widget, const QString &name) {
LogGeometry(name, QRect(widget->mapToGlobal(QPoint()), widget->size()));
if (!widget->isVisible()) {
Fail(u"capture %1"_q.arg(name), u"widget is not visible"_q);
return false;
}
const auto image = GrabWidget(widget);
if (LooksBlank(image)) {
Fail(u"capture %1"_q.arg(name), u"grabbed image looks blank"_q);
return false;
}
const auto blankRoot = BlankRootDetails(widget, image, QRect());
if (!blankRoot.isEmpty()) {
Fail(u"capture %1"_q.arg(name), blankRoot);
return false;
}
return !SaveImage(image, name).isEmpty();
}
bool CaptureRect(
not_null<QWidget*> widget,
const QRect &logicalRect,
const QString &name) {
LogGeometry(name, logicalRect);
if (!widget->isVisible()) {
Fail(u"capture %1"_q.arg(name), u"widget is not visible"_q);
return false;
}
const auto misframed = MisframedDetails(widget, logicalRect);
if (!misframed.isEmpty()) {
Fail(u"capture %1"_q.arg(name), misframed);
return false;
}
const auto image = GrabRect(widget, logicalRect);
if (LooksBlank(image)) {
Fail(u"capture %1"_q.arg(name), u"grabbed image looks blank"_q);
return false;
}
const auto blankRoot = BlankRootDetails(widget, image, logicalRect);
if (!blankRoot.isEmpty()) {
Fail(u"capture %1"_q.arg(name), blankRoot);
return false;
}
return !SaveImage(image, name).isEmpty();
}
bool CaptureMappedRect(
not_null<QWidget*> widget,
not_null<QWidget*> rectOrigin,
const QRect &logicalRect,
const QString &name) {
return CaptureRect(
widget,
Ui::MapFrom(widget, rectOrigin, logicalRect),
name);
}
MappedTarget ReadMappedTarget(
QWidget *owner,
QWidget *origin,
const QRect &localRect) {
if (!owner && !origin) {
return {
.refusal = u"no painted owner or rectangle origin was handed "
u"to the mapped-target reading"_q,
};
} else if (!owner) {
return {
.identity = WidgetDescription(origin),
.refusal = u"no painted owner was handed to the mapped-target "
u"reading"_q,
};
} else if (!origin) {
return {
.identity = WidgetDescription(owner),
.refusal = u"no rectangle origin was handed to the mapped-target "
u"reading"_q,
};
}
auto result = MappedTarget{
.local = localRect,
.identity = u"origin=%1 owner=%2"_q.arg(
WidgetDescription(origin),
WidgetDescription(owner)),
};
if (!origin->isVisible()) {
result.refusal = u"rectangle origin is not visible: %1"_q.arg(
result.identity);
return result;
} else if (!owner->isVisible()) {
result.refusal = u"painted owner is not visible: %1"_q.arg(
result.identity);
return result;
} else if (origin->size().isEmpty()) {
result.refusal = u"rectangle origin has empty geometry: %1"_q.arg(
result.identity);
return result;
} else if (owner->size().isEmpty()) {
result.refusal = u"painted owner has empty geometry: %1"_q.arg(
result.identity);
return result;
} else if (localRect.isEmpty()) {
result.refusal = u"requested target rect is empty: local=%1 %2"_q
.arg(RectText(localRect), result.identity);
return result;
}
const auto clipper = MappedClipper(origin);
if (clipper && !clipper->isVisible()) {
result.refusal = u"relevant viewport is not visible: %1 clipper=%2"_q
.arg(result.identity, WidgetDescription(clipper));
return result;
}
result.mapped = Ui::MapFrom(owner, origin, localRect);
if (const auto misframed = MisframedDetails(owner, result.mapped)
; !misframed.isEmpty()) {
result.refusal = u"mapped target is not fully inside the painted "
u"owner: %1 local=%2 mapped=%3 clipper=%4 - %5"_q
.arg(result.identity)
.arg(RectText(localRect))
.arg(RectText(result.mapped))
.arg(clipper ? WidgetDescription(clipper) : u"<none>"_q)
.arg(misframed);
return result;
}
if (clipper) {
result.inViewport = Ui::MapFrom(clipper, origin, localRect);
if (const auto misframed = MisframedDetails(
clipper,
result.inViewport)
; !misframed.isEmpty()) {
result.refusal = u"mapped target is not fully inside the "
u"relevant viewport: %1 local=%2 mapped=%3 inViewport=%4 "
u"clipper=%5 - %6"_q
.arg(result.identity)
.arg(RectText(localRect))
.arg(RectText(result.mapped))
.arg(RectText(result.inViewport))
.arg(WidgetDescription(clipper))
.arg(misframed);
return result;
}
}
result.origin = origin;
result.owner = owner;
result.viewport = clipper;
return result;
}
bool MappedTargetReady(
QWidget *owner,
QWidget *origin,
const QRect &localRect) {
return ReadMappedTarget(owner, origin, localRect).resolved();
}
QString MappedTargetDetails(const MappedTarget &reading) {
return MappedTargetText(reading);
}
bool CaptureMappedTarget(
QWidget *owner,
QWidget *origin,
const QRect &localRect,
const QString &name) {
const auto reading = ReadMappedTarget(owner, origin, localRect);
if (!reading.resolved()) {
Fail(u"capture %1"_q.arg(name), reading.refusal);
return false;
}
return CaptureMappedRect(
reading.owner.data(),
reading.origin.data(),
localRect,
name);
}
MappedRect::MappedRect(
not_null<QWidget*> widget,
const QRect &rect,
bool parentRelative)
: _widget(widget.get())
, _rect(rect)
, _parentRelative(parentRelative) {
}
MappedRect MappedRect::Local(not_null<QWidget*> widget, const QRect &rect) {
return MappedRect(widget, rect, false);
}
MappedRect MappedRect::InParent(
not_null<QWidget*> widget,
const QRect &rect) {
return MappedRect(widget, rect, true);
}
QWidget *MappedRect::widget() const {
return _widget.data();
}
QWidget *MappedRect::origin() const {
const auto widget = _widget.data();
if (!widget || !_parentRelative) {
return widget;
}
return widget->isWindow() ? nullptr : widget->parentWidget();
}
QRect MappedRect::rect() const {
return _rect;
}
bool MappedRect::parentRelative() const {
return _parentRelative;
}
MappedTarget ReadMappedTarget(QWidget *owner, const MappedRect &target) {
const auto painted = target.widget();
const auto origin = target.origin();
const auto rect = target.rect();
if (!owner || !painted) {
auto result = ReadMappedTarget(owner, origin, rect);
result.binding = MappedRectText(target);
return result;
} else if (!origin) {
return TypedRefusal(owner, target, u"detached: %1 has no parent "
u"coordinate space (no parent widget, or it is a window), so a "
u"parent-relative rect has no coordinate owner"_q.arg(
WidgetDescription(painted)));
} else if (!InsideOwner(owner, painted)) {
return TypedRefusal(owner, target, u"wrong owner: painted %1 is not "
u"%2 or inside it"_q.arg(
WidgetDescription(painted),
WidgetDescription(owner)));
} else if (target.parentRelative() && !painted->isVisible()) {
return TypedRefusal(owner, target, u"painted widget is not visible: "
u"painted=%1 owner=%2 - its parent-relative rect would map "
u"through the parent alone"_q.arg(
WidgetDescription(painted),
WidgetDescription(owner)));
}
const auto bounds = target.parentRelative()
? painted->geometry()
: painted->rect();
if (!rect.isEmpty() && !bounds.contains(rect)) {
return TypedRefusal(owner, target, u"coordinate mismatch: "
u"requested=%1 space=%2 origin=%3 painted=%4 bounds=%5 owner=%6 "
u"would map to %7 - a parent-relative rect handed as local (or "
u"the reverse) applies the position twice"_q
.arg(RectText(rect))
.arg(target.parentRelative() ? u"parent"_q : u"local"_q)
.arg(WidgetDescription(origin))
.arg(WidgetDescription(painted))
.arg(RectText(bounds))
.arg(WidgetDescription(owner))
.arg(RectText(Ui::MapFrom(owner, origin, rect))));
}
auto result = ReadMappedTarget(owner, origin, rect);
result.binding = MappedRectText(target);
return result;
}
bool CaptureMappedTarget(
QWidget *owner,
const MappedRect &target,
const QString &name) {
const auto reading = ReadMappedTarget(owner, target);
if (!reading.resolved()) {
Fail(u"capture %1"_q.arg(name), reading.refusal);
return false;
}
return CaptureMappedTarget(
reading.owner.data(),
reading.origin.data(),
target.rect(),
name);
}
PaintingLayerRootResult PaintingLayerRoot(QWidget *box) {
if (!box) {
return {
.refusal = u"no widget was handed to the painting layer root "
u"resolver"_q,
};
}
auto walked = QStringList();
for (auto widget = box; widget; widget = widget->parentWidget()) {
if (const auto layer = dynamic_cast<Ui::BoxLayerWidget*>(widget)) {
return { .widget = layer };
}
walked.push_back(WidgetDescription(widget));
if (widget == widget->window()) {
break;
}
}
return {
.refusal = u"no Ui::BoxLayerWidget between the target and its own "
u"window, so it is not a box inside a layer and has no painting "
u"layer root; walked %1 widget(s) and stopped at the window: "
u"[%2]"_q.arg(walked.size()).arg(ElidedChain(walked)),
};
}
bool CaptureInLayerRoot(not_null<QWidget*> box, const QString &name) {
const auto root = PaintingLayerRoot(box);
if (!root.resolved()) {
Fail(u"capture %1"_q.arg(name), root.refusal);
return false;
}
return CaptureMappedRect(root.widget.data(), box, box->rect(), name);
}
bool CaptureBoxLayer(not_null<QWidget*> box, const QString &name) {
const auto root = PaintingLayerRoot(box);
if (!root.resolved()) {
Fail(u"capture %1"_q.arg(name), root.refusal);
return false;
}
return CaptureWidget(root.widget.data(), name);
}
WindowMappedCapture ReadViaWindow(QWidget *widget) {
if (!widget) {
return {
.refusal = u"no widget was handed to the window-mapped "
u"capture"_q,
};
}
auto result = WindowMappedCapture{
.identity = WidgetDescription(widget),
};
if (!widget->isVisible()) {
result.refusal = u"target is not visible: %1"_q.arg(result.identity);
return result;
} else if (widget->size().isEmpty()) {
result.refusal = u"target has empty geometry: %1"_q.arg(
result.identity);
return result;
}
const auto window = widget->window();
if (window == widget) {
result.refusal = u"target is its own window, so there is no opaque "
u"window behind it to grab: %1"_q.arg(result.identity);
return result;
}
result.mapped = Ui::MapFrom(window, widget, widget->rect());
const auto misframed = MisframedDetails(window, result.mapped);
if (!misframed.isEmpty()) {
result.refusal = misframed;
return result;
}
result.window = window;
return result;
}
QImage GrabViaWindow(QWidget *widget) {
const auto reading = ReadViaWindow(widget);
return reading.resolved()
? GrabRect(reading.window.data(), reading.mapped)
: QImage();
}
bool ViaWindowReady(QWidget *widget) {
return !LooksBlank(GrabViaWindow(widget));
}
QString ViaWindowDetails(QWidget *widget) {
return ViaWindowText(ReadViaWindow(widget));
}
bool CaptureViaWindow(not_null<QWidget*> widget, const QString &name) {
const auto reading = ReadViaWindow(widget);
if (!reading.resolved()) {
Fail(u"capture %1"_q.arg(name), reading.refusal);
return false;
}
LogGeometry(name, QRect(widget->mapToGlobal(QPoint()), widget->size()));
const auto image = GrabRect(reading.window.data(), reading.mapped);
if (LooksBlank(image)) {
Note(u"capture %1 declined a blank frame: %2"_q
.arg(name, ViaWindowText(reading)));
return false;
}
return !SaveImage(image, name).isEmpty();
}
bool StrictRender::valid() const {
return owner && refusal.isEmpty() && !image.isNull();
}
StrictRender RenderStrict(
QWidget *owner,
const QRect &rendered,
const QRect &crop) {
auto result = StrictRender{
.rendered = rendered,
.crop = crop,
};
if (!owner) {
result.refusal = u"no render owner was handed to the strict "
u"render"_q;
return result;
}
result.identity = WidgetDescription(owner);
if (rendered.isEmpty()) {
result.refusal = u"rendered rect is empty: rendered=%1 owner=%2"_q
.arg(RectText(rendered), result.identity);
return result;
}
const auto misframed = MisframedDetails(owner, rendered);
if (!misframed.isEmpty()) {
result.refusal = u"rendered rect is not fully inside the render "
u"owner: owner=%1 - %2"_q.arg(result.identity, misframed);
return result;
} else if (crop.isEmpty() || !rendered.contains(crop)) {
result.refusal = u"crop is not fully inside the rendered rect: "
u"requested=%1 rendered=%2 owner=%3"_q.arg(
RectText(crop),
RectText(rendered),
result.identity);
return result;
}
const auto image = GrabRect(owner, rendered);
result.pixels = DevicePixelRect(
crop.translated(-rendered.topLeft()),
image.devicePixelRatio());
if (!image.rect().contains(result.pixels)) {
result.refusal = u"device crop is not fully inside the render: "
u"pixels=%1 image=%2x%3 dpr=%4 owner=%5"_q
.arg(RectText(result.pixels))
.arg(image.width())
.arg(image.height())
.arg(image.devicePixelRatio())
.arg(result.identity);
return result;
}
result.image = Crop(image, result.pixels);
result.owner = owner;
return result;
}
QString StrictRenderText(const StrictRender &render) {
return u"owner=%1 rendered=%2 crop=%3 pixels=%4 image=%5x%6 dpr=%7 "
u"format=%8%9"_q
.arg(render.identity.isEmpty() ? u"<none>"_q : render.identity)
.arg(RectText(render.rendered))
.arg(RectText(render.crop))
.arg(RectText(render.pixels))
.arg(render.image.width())
.arg(render.image.height())
.arg(render.image.devicePixelRatio())
.arg(int(render.image.format()))
.arg(render.refusal.isEmpty()
? QString()
: u" refusal=%1"_q.arg(render.refusal));
}
bool StrictComparison::equal() const {
return refusal.isEmpty() && (compared > 0) && (differing == 0);
}
StrictComparison CompareStrict(
const StrictRender &a,
const StrictRender &b) {
auto result = StrictComparable(a.image, b.image)
? CountStrictPixels(a.image, b.image)
: StrictComparison();
const auto refusal = StrictRefusal(a, b);
if (!refusal.isEmpty()) {
result.refusal = u"%1 - a={%2} b={%3}"_q.arg(
refusal,
StrictRenderText(a),
StrictRenderText(b));
}
return result;
}
QString StrictComparisonText(const StrictComparison &comparison) {
return u"compared=%1 differing=%2 maxChannelDelta=%3 first=%4,%5 "
u"equal=%6%7"_q
.arg(comparison.compared)
.arg(comparison.differing)
.arg(comparison.maxChannelDelta)
.arg(comparison.first.x())
.arg(comparison.first.y())
.arg(comparison.equal() ? 1 : 0)
.arg(comparison.refusal.isEmpty()
? QString()
: u" refusal=%1"_q.arg(comparison.refusal));
}
QImage Crop(const QImage &image, const QRect &pixelRect) {
const auto bounded = pixelRect.intersected(image.rect());
return bounded.isEmpty() ? QImage() : image.copy(bounded);
}
QRect DevicePixelRect(const QRect &logical, qreal ratio) {
const auto left = int(std::floor(logical.x() * ratio));
const auto top = int(std::floor(logical.y() * ratio));
const auto right = int(std::ceil(
(logical.x() + logical.width()) * ratio));
const auto bottom = int(std::ceil(
(logical.y() + logical.height()) * ratio));
return QRect(left, top, right - left, bottom - top);
}
QImage Zoom(const QImage &image, int factor) {
return (image.isNull() || factor <= 1)
? image
: image.scaled(
image.size() * factor,
Qt::KeepAspectRatio,
Qt::FastTransformation);
}
QImage ContactSheet(const std::vector<QImage> &images) {
auto width = 0;
auto height = 0;
for (const auto &image : images) {
if (image.isNull()) {
continue;
}
width += image.width() + (width ? kContactSheetGap : 0);
height = std::max(height, image.height());
}
if (!width) {
return QImage();
}
auto result = QImage(width, height, QImage::Format_ARGB32_Premultiplied);
result.fill(Qt::white);
auto painter = QPainter(&result);
auto x = 0;
for (const auto &image : images) {
if (image.isNull()) {
continue;
}
auto copy = image;
copy.setDevicePixelRatio(1.);
painter.drawImage(x, 0, copy);
x += copy.width() + kContactSheetGap;
}
painter.end();
return result;
}
} // namespace Test
#endif // _DEBUG || TDESKTOP_RELEASE_TEST_HARNESS