ZaStoGram_desktop/Telegram/SourceFiles/ui/effects/thanos_effect.cpp
loop-uh d6b8f28ef7
All checks were successful
Desktop source guards / guards (push) Successful in 4s
Анимация удаления (Thanos) возвращена: поверхность живёт в окне-накладке
Причина закрытия приложения при первом удалении: GPU-виджет эффекта добавлялся в
уже показанное главное окно, Qt пересоздавал его нативный хэндл, WM_DESTROY
принимался за закрытие (Core::Quit), а MainWindow ещё и кеширует хэндл (psHwnd,
рамка, тени, панель задач), так что просто игнорировать закрытие нельзя. Если же
переводить на GPU-композицию всё главное окно (праймер lib_ui), каждый кадр ждёт
вертикальной синхронизации и анимации падают до ~30 кадров/с на 60 Гц
(lib_ui 6d6e1f0 убрал праймер намеренно).

Теперь на Windows поверхность создаётся внутри ThanosOverlay: прозрачного,
не принимающего ввод и фокус окна-владельца (Qt::Tool с родителем),
которое накрывает клиентскую область главного окна и создаётся уже вместе со
своим GPU-потомком, поэтому Qt ничего не пересоздаёт. Главное окно не
меняется. На других платформах прежний код.

Аварийный выключатель: ZSG_DISABLE_THANOS=1 или «Энергосбережение → Эффекты в
чатах». Диагностика core/zsg_diag пишет состояние накладки. Гарды в
test_zastogram_diag.py.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:58:23 -05:00

271 lines
6.6 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
*/
#include "ui/effects/thanos_effect.h"
#include "ui/effects/thanos_effect_renderer.h"
#include "ui/gl/gl_detection.h"
#include "ui/gl/gl_surface.h"
#include "ui/power_saving.h"
#include "ui/rp_widget.h"
#include "ui/ui_utility.h"
#include "base/event_filter.h"
#include "base/qt_signal_producer.h"
#include "core/zsg_diag.h"
#include "ui/effects/zsg_thanos_overlay.h"
#include <QtGui/QWindow>
namespace Ui {
bool ThanosEffectFailedOnce = false;
bool ThanosEffect::Supported() {
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) && !defined DESKTOP_APP_DISABLE_PRIVATE_QT_API
// ZaStoGram: kill switch. On Windows the surface is hosted by an overlay
// window (zsg_thanos_overlay.h); if that misbehaves on some machine,
// ZSG_DISABLE_THANOS=1 (or Settings > Power saving > Chat effects)
// makes deletions simply collapse again.
static const auto disabled = qEnvironmentVariableIsSet("ZSG_DISABLE_THANOS");
if (disabled) {
return false;
}
if (ThanosEffectFailedOnce
|| PowerSaving::On(PowerSaving::kChatEffects)
|| PowerSaving::On(PowerSaving::kAnimations)) {
return false;
}
if (!GL::WidgetsRhiEnabled()) {
return false;
}
return GL::CheckRhiCapabilities().compute;
#else
return false;
#endif
}
bool ThanosEffect::WindowVisible(QWidget *window) {
if (!window || window->isHidden() || window->isMinimized()) {
return false;
}
const auto handle = window->windowHandle();
return handle && handle->isExposed();
}
void ThanosEffect::WarmUp() {
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) && !defined DESKTOP_APP_DISABLE_PRIVATE_QT_API
if (PowerSaving::On(PowerSaving::kChatEffects)
|| PowerSaving::On(PowerSaving::kAnimations)) {
return;
}
if (!GL::WidgetsRhiEnabled()) {
return;
}
[[maybe_unused]] const auto capabilities = GL::CheckRhiCapabilities();
#endif
}
ThanosEffect::ThanosEffect(not_null<QWidget*> parent)
: _parent(parent)
, _animation([=] {
if (_renderer && _renderer->failed()) {
ThanosEffectFailedOnce = true;
hideSurface();
return;
}
if (const auto w = surfaceWidget()) {
w->update();
}
}) {
}
ThanosEffect::~ThanosEffect() {
// The surface is a child of the overlay, which is a child of the main
// window: free them in this order whatever the order of destruction.
_surface = nullptr;
if (_overlay) {
delete _overlay.data();
}
}
QWidget *ThanosEffect::surfaceWidget() const {
return _surface ? _surface->rpWidget() : nullptr;
}
void ThanosEffect::ensureSurface() {
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) && !defined DESKTOP_APP_DISABLE_PRIVATE_QT_API
if (_surface) {
return;
}
auto devicePixelRatio = [&]() -> rpl::producer<float64> {
const auto initial = float64(_parent->devicePixelRatioF());
const auto handle = _parent->windowHandle();
if (!handle) {
return rpl::single(initial);
}
return rpl::single(
initial
) | rpl::then(base::qt_signal_producer(
handle,
&QWindow::screenChanged
) | rpl::map([parent = _parent](QScreen*) {
return float64(parent->devicePixelRatioF());
}));
}();
auto renderer = std::make_unique<ThanosEffectRenderer>(
std::move(devicePixelRatio));
_renderer = renderer.get();
_renderer->allDone() | rpl::on_next([weak = base::make_weak(this)] {
if (const auto strong = weak.get()) {
strong->_animation.stop();
}
crl::on_main(weak, [weak] {
if (const auto strong = weak.get()) {
strong->hideSurface();
strong->_allDone.fire({});
}
});
}, _lifetime);
Core::ZsgDiag::Trace("thanos: creating surface");
#ifdef Q_OS_WIN
// The GPU widget goes into a window that does not exist yet, never into
// the main window: adding it there would recreate the main window.
_overlay = new ThanosOverlay(_parent);
const auto surfaceParent = not_null<QWidget*>(_overlay.data());
#else // Q_OS_WIN
const auto surfaceParent = _parent;
#endif // else for Q_OS_WIN
_surface = GL::CreateSurface(
surfaceParent,
GL::ChosenRenderer{
.renderer = std::move(renderer),
.backend = GL::Backend::QRhi,
});
Core::ZsgDiag::Trace("thanos: surface created", _surface ? 1 : 0);
if (!_surface) {
_renderer = nullptr;
if (_overlay) {
delete _overlay.data();
}
return;
}
if (const auto w = surfaceWidget()) {
w->setAttribute(Qt::WA_TransparentForMouseEvents);
w->setAttribute(Qt::WA_AlwaysStackOnTop);
w->setGeometry(_parent->rect());
w->hide();
}
if (const auto handle = _parent->windowHandle()) {
base::install_event_filter(handle, [=](not_null<QEvent*> e) {
if (e->type() == QEvent::Expose && !handle->isExposed()) {
finishNow();
}
return base::EventFilterResult::Continue;
}, _lifetime);
}
#endif
}
void ThanosEffect::showSurface() {
if (const auto w = surfaceWidget()) {
w->setGeometry(_parent->rect());
// Defer show until the current call stack returns to the event
// loop, so that all items from a batch deletion are added
// before the first render. Without this, w->show() triggers
// an immediate platform compositing pass with only the first
// item visible.
_shown = true;
Ui::PostponeCall(w, [=] {
if (!_shown) {
return;
}
if (_overlay) {
_overlay->present();
}
w->show();
w->raise();
});
_animation.start();
}
}
void ThanosEffect::hideSurface() {
_shown = false;
_animation.stop();
if (const auto w = surfaceWidget()) {
w->hide();
}
if (_overlay) {
_overlay->dismiss();
}
}
void ThanosEffect::finishNow() {
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) && !defined DESKTOP_APP_DISABLE_PRIVATE_QT_API
if (!_renderer || !_renderer->hasActiveItems()) {
return;
}
_renderer->finishAll();
hideSurface();
#endif
}
void ThanosEffect::addItem(QImage snapshot, QRect rect) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) && !defined DESKTOP_APP_DISABLE_PRIVATE_QT_API
ensureSurface();
if (!_renderer) {
return;
}
_renderer->addItem({
.snapshot = std::move(snapshot),
.rect = QRectF(rect),
});
if (!_shown) {
showSurface();
}
#endif
}
bool ThanosEffect::animating() const {
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) && !defined DESKTOP_APP_DISABLE_PRIVATE_QT_API
return _renderer && _renderer->hasActiveItems();
#else
return false;
#endif
}
rpl::producer<> ThanosEffect::allDone() const {
return _allDone.events();
}
bool ThanosEffect::FailedOnce() {
return ThanosEffectFailedOnce;
}
void ThanosEffect::setGeometry(QRect rect) {
if (const auto w = surfaceWidget()) {
if (w->isVisible()) {
w->setGeometry(rect);
}
}
}
void ThanosEffect::raise() {
if (const auto w = surfaceWidget()) {
w->raise();
}
}
} // namespace Ui