tdesktop/Telegram/SourceFiles/window/themes/window_theme.cpp

1358 lines
39 KiB
C++
Raw Normal View History

/*
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 "window/themes/window_theme.h"
#include "window/themes/window_theme_preview.h"
2019-08-23 13:52:59 +00:00
#include "window/themes/window_themes_embedded.h"
#include "mainwidget.h"
2019-07-24 11:45:24 +00:00
#include "main/main_session.h"
2019-02-08 16:20:08 +00:00
#include "apiwrap.h"
2017-03-04 10:23:56 +00:00
#include "storage/localstorage.h"
2019-02-08 16:20:08 +00:00
#include "storage/localimageloader.h"
#include "storage/file_upload.h"
2017-04-06 14:38:10 +00:00
#include "base/parse_helper.h"
#include "base/zlib_help.h"
2019-09-03 08:25:19 +00:00
#include "base/unixtime.h"
2019-02-08 16:20:08 +00:00
#include "data/data_session.h"
2019-06-06 09:37:12 +00:00
#include "main/main_account.h" // Account::sessionValue.
2019-01-28 13:59:49 +00:00
#include "ui/image/image.h"
#include "boxes/background_box.h"
2019-02-08 16:20:08 +00:00
#include "core/application.h"
#include "styles/style_widgets.h"
#include "styles/style_history.h"
2019-01-28 13:59:49 +00:00
2019-09-04 07:19:15 +00:00
#include <QtCore/QBuffer>
namespace Window {
namespace Theme {
namespace {
constexpr auto kThemeFileSizeLimit = 5 * 1024 * 1024;
constexpr auto kThemeBackgroundSizeLimit = 4 * 1024 * 1024;
constexpr auto kBackgroundSizeLimit = 25 * 1024 * 1024;
constexpr auto kNightThemeFile = str_const(":/gui/night.tdesktop-theme");
2019-08-23 13:52:59 +00:00
constexpr auto kMinimumTiledSize = 512;
2019-01-16 17:26:26 +00:00
struct Applying {
2019-09-03 18:04:38 +00:00
Saved data;
2019-01-16 17:26:26 +00:00
QByteArray paletteForRevert;
Fn<void()> overrideKeep;
};
2019-01-16 17:26:26 +00:00
NeverFreedPointer<ChatBackground> GlobalBackground;
Applying GlobalApplying;
inline bool AreTestingTheme() {
2019-01-16 17:26:26 +00:00
return !GlobalApplying.paletteForRevert.isEmpty();
};
2019-09-02 16:10:18 +00:00
[[nodiscard]] bool IsEditingTheme(const QString &path) {
static const auto kEditingPath = QFileInfo(
EditingPalettePath()
).absoluteFilePath();
return !path.compare(kEditingPath, Qt::CaseInsensitive)
&& QFileInfo(path).exists();
}
bool CalculateIsMonoColorImage(const QImage &image) {
if (!image.isNull()) {
const auto bits = reinterpret_cast<const uint32*>(image.constBits());
const auto first = bits[0];
for (auto i = 0; i < image.width() * image.height(); i++) {
if (first != bits[i]) {
return false;
}
}
return true;
}
return false;
}
QByteArray readThemeContent(const QString &path) {
QFile file(path);
if (!file.exists()) {
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: theme file not found: %1").arg(path));
return QByteArray();
}
if (file.size() > kThemeFileSizeLimit) {
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: theme file too large: %1 (should be less than 5 MB, got %2)").arg(path).arg(file.size()));
return QByteArray();
}
if (!file.open(QIODevice::ReadOnly)) {
LOG(("Theme Error: could not open theme file: %1").arg(path));
return QByteArray();
}
return file.readAll();
}
inline uchar readHexUchar(char code, bool &error) {
if (code >= '0' && code <= '9') {
return ((code - '0') & 0xFF);
} else if (code >= 'a' && code <= 'f') {
return ((code + 10 - 'a') & 0xFF);
} else if (code >= 'A' && code <= 'F') {
return ((code + 10 - 'A') & 0xFF);
}
error = true;
return 0xFF;
}
inline uchar readHexUchar(char char1, char char2, bool &error) {
return ((readHexUchar(char1, error) & 0x0F) << 4) | (readHexUchar(char2, error) & 0x0F);
}
bool readNameAndValue(const char *&from, const char *end, QLatin1String *outName, QLatin1String *outValue) {
using base::parse::skipWhitespaces;
using base::parse::readName;
if (!skipWhitespaces(from, end)) return true;
*outName = readName(from, end);
if (outName->size() == 0) {
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: Could not read name in the color scheme."));
return false;
}
if (!skipWhitespaces(from, end)) {
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: Unexpected end of the color scheme."));
return false;
}
if (*from != ':') {
LOG(("Theme Error: Expected ':' between each name and value in the color scheme (while reading key '%1')").arg(*outName));
return false;
}
if (!skipWhitespaces(++from, end)) {
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: Unexpected end of the color scheme."));
return false;
}
auto valueStart = from;
if (*from == '#') ++from;
if (readName(from, end).size() == 0) {
LOG(("Theme Error: Expected a color value in #rrggbb or #rrggbbaa format in the color scheme (while reading key '%1')").arg(*outName));
return false;
}
*outValue = QLatin1String(valueStart, from - valueStart);
if (!skipWhitespaces(from, end)) {
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: Unexpected end of the color scheme."));
return false;
}
if (*from != ';') {
LOG(("Theme Error: Expected ';' after each value in the color scheme (while reading key '%1')").arg(*outName));
return false;
}
++from;
return true;
}
enum class SetResult {
Ok,
Bad,
NotFound,
};
SetResult setColorSchemeValue(
QLatin1String name,
QLatin1String value,
2019-08-27 13:59:15 +00:00
const Colorizer &colorizer,
Instance *out) {
auto result = style::palette::SetResult::Ok;
auto size = value.size();
auto data = value.data();
if (data[0] == '#' && (size == 7 || size == 9)) {
auto error = false;
auto r = readHexUchar(data[1], data[2], error);
auto g = readHexUchar(data[3], data[4], error);
auto b = readHexUchar(data[5], data[6], error);
auto a = (size == 9) ? readHexUchar(data[7], data[8], error) : uchar(255);
2019-08-27 13:59:15 +00:00
if (colorizer) {
Colorize(name, r, g, b, colorizer);
}
if (error) {
LOG(("Theme Warning: Skipping value '%1: %2' (expected a color value in #rrggbb or #rrggbbaa or a previously defined key in the color scheme)").arg(name).arg(value));
return SetResult::Ok;
} else if (out) {
result = out->palette.setColor(name, r, g, b, a);
} else {
result = style::main_palette::setColor(name, r, g, b, a);
}
} else {
if (out) {
result = out->palette.setColor(name, value);
} else {
result = style::main_palette::setColor(name, value);
}
}
if (result == style::palette::SetResult::Ok) {
return SetResult::Ok;
} else if (result == style::palette::SetResult::KeyNotFound) {
return SetResult::NotFound;
} else if (result == style::palette::SetResult::ValueNotFound) {
LOG(("Theme Warning: Skipping value '%1: %2' (expected a color value in #rrggbb or #rrggbbaa or a previously defined key in the color scheme)").arg(name).arg(value));
return SetResult::Ok;
} else if (result == style::palette::SetResult::Duplicate) {
LOG(("Theme Warning: Color value appears more than once in the color scheme (while applying '%1: %2')").arg(name).arg(value));
return SetResult::Ok;
} else {
LOG(("Theme Error: Unexpected internal error."));
}
return SetResult::Bad;
}
bool loadColorScheme(
const QByteArray &content,
2019-08-27 13:59:15 +00:00
const Colorizer &colorizer,
Instance *out) {
auto unsupported = QMap<QLatin1String, QLatin1String>();
return ReadPaletteValues(content, [&](QLatin1String name, QLatin1String value) {
// Find the named value in the already read unsupported list.
value = unsupported.value(value, value);
2019-08-27 13:59:15 +00:00
auto result = setColorSchemeValue(name, value, colorizer, out);
if (result == SetResult::Bad) {
return false;
} else if (result == SetResult::NotFound) {
unsupported.insert(name, value);
}
return true;
});
}
void applyBackground(QImage &&background, bool tiled, Instance *out) {
if (out) {
out->background = std::move(background);
out->tiled = tiled;
} else {
Background()->setThemeData(std::move(background), tiled);
}
}
enum class LoadResult {
Loaded,
Failed,
NotFound,
};
LoadResult loadBackgroundFromFile(zlib::FileToRead &file, const char *filename, QByteArray *outBackground) {
*outBackground = file.readFileContent(filename, zlib::kCaseInsensitive, kThemeBackgroundSizeLimit);
if (file.error() == UNZ_OK) {
return LoadResult::Loaded;
} else if (file.error() == UNZ_END_OF_LIST_OF_FILE) {
file.clearError();
return LoadResult::NotFound;
}
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: could not read '%1' in the theme file.").arg(filename));
return LoadResult::Failed;
}
bool loadBackground(zlib::FileToRead &file, QByteArray *outBackground, bool *outTiled) {
auto result = loadBackgroundFromFile(file, "background.jpg", outBackground);
if (result != LoadResult::NotFound) return (result == LoadResult::Loaded);
result = loadBackgroundFromFile(file, "background.png", outBackground);
if (result != LoadResult::NotFound) return (result == LoadResult::Loaded);
*outTiled = true;
result = loadBackgroundFromFile(file, "tiled.jpg", outBackground);
if (result != LoadResult::NotFound) return (result == LoadResult::Loaded);
result = loadBackgroundFromFile(file, "tiled.png", outBackground);
if (result != LoadResult::NotFound) return (result == LoadResult::Loaded);
return true;
}
bool loadTheme(
const QByteArray &content,
2019-09-05 06:51:46 +00:00
const std::optional<QByteArray> &editedPalette,
Cached &cache,
2019-08-27 13:59:15 +00:00
const Colorizer &colorizer,
Instance *out = nullptr) {
cache = Cached();
zlib::FileToRead file(content);
2019-09-05 06:51:46 +00:00
const auto emptyColorizer = Colorizer();
const auto &applyColorizer = editedPalette ? emptyColorizer : colorizer;
unz_global_info globalInfo = { 0 };
file.getGlobalInfo(&globalInfo);
if (file.error() == UNZ_OK) {
2019-09-05 06:51:46 +00:00
auto schemeContent = editedPalette.value_or(QByteArray());
if (schemeContent.isEmpty()) {
schemeContent = file.readFileContent("colors.tdesktop-theme", zlib::kCaseInsensitive, kThemeSchemeSizeLimit);
}
if (schemeContent.isEmpty()) {
file.clearError();
schemeContent = file.readFileContent("colors.tdesktop-palette", zlib::kCaseInsensitive, kThemeSchemeSizeLimit);
}
if (file.error() != UNZ_OK) {
LOG(("Theme Error: could not read 'colors.tdesktop-theme' or 'colors.tdesktop-palette' in the theme file."));
return false;
}
2019-09-05 06:51:46 +00:00
if (!loadColorScheme(schemeContent, applyColorizer, out)) {
return false;
}
2018-07-21 13:54:00 +00:00
Background()->saveAdjustableColors();
auto backgroundTiled = false;
auto backgroundContent = QByteArray();
if (!loadBackground(file, &backgroundContent, &backgroundTiled)) {
return false;
}
if (!backgroundContent.isEmpty()) {
auto check = QBuffer(&backgroundContent);
auto reader = QImageReader(&check);
const auto size = reader.size();
if (size.isEmpty()
|| (size.width() * size.height() > kBackgroundSizeLimit)) {
LOG(("Theme Error: bad background image size in the theme file."));
return false;
}
auto background = App::readImage(backgroundContent);
if (background.isNull()) {
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: could not read background image in the theme file."));
return false;
}
if (colorizer) {
Colorize(background, colorizer);
}
auto buffer = QBuffer(&cache.background);
if (!background.save(&buffer, "BMP")) {
2017-02-02 16:29:36 +00:00
LOG(("Theme Error: could not write background image as a BMP to cache."));
return false;
}
cache.tiled = backgroundTiled;
applyBackground(std::move(background), cache.tiled, out);
}
} else {
// Looks like it is not a .zip theme.
2019-09-05 06:51:46 +00:00
if (!loadColorScheme(editedPalette.value_or(content), applyColorizer, out)) {
return false;
}
2018-07-21 13:54:00 +00:00
Background()->saveAdjustableColors();
}
if (out) {
cache.colors = out->palette.save();
} else {
cache.colors = style::main_palette::save();
}
2016-10-31 12:29:26 +00:00
cache.paletteChecksum = style::palette::Checksum();
cache.contentChecksum = hashCrc32(content.constData(), content.size());
return true;
}
2019-09-05 06:51:46 +00:00
bool InitializeFromCache(
const QByteArray &content,
const Cached &cache) {
if (cache.paletteChecksum != style::palette::Checksum()) {
return false;
}
if (cache.contentChecksum != hashCrc32(content.constData(), content.size())) {
return false;
}
QImage background;
if (!cache.background.isEmpty()) {
QDataStream stream(cache.background);
QImageReader reader(stream.device());
#ifndef OS_MAC_OLD
reader.setAutoTransform(true);
#endif // OS_MAC_OLD
if (!reader.read(&background) || background.isNull()) {
return false;
}
}
if (!style::main_palette::load(cache.colors)) {
return false;
}
Background()->saveAdjustableColors();
if (!background.isNull()) {
applyBackground(std::move(background), cache.tiled, nullptr);
}
return true;
}
[[nodiscard]] std::optional<QByteArray> ReadEditingPalette() {
auto file = QFile(EditingPalettePath());
return file.open(QIODevice::ReadOnly)
? std::make_optional(file.readAll())
: std::nullopt;
}
bool InitializeFromSaved(Saved &&saved) {
if (saved.object.content.size() < 4) {
LOG(("Theme Error: Could not load theme from '%1' (%2)"
).arg(saved.object.pathRelative
).arg(saved.object.pathAbsolute));
return false;
}
const auto editing = ReadEditingPalette();
GlobalBackground.createIfNull();
if (!editing && InitializeFromCache(saved.object.content, saved.cache)) {
return true;
}
const auto colorizer = editing
? Colorizer()
: ColorizerForTheme(saved.object.pathAbsolute);
if (!loadTheme(saved.object.content, editing, saved.cache, colorizer)) {
return false;
}
if (editing) {
Background()->setIsEditingTheme(true);
} else {
Local::writeTheme(saved);
}
return true;
}
2019-01-29 10:57:29 +00:00
QImage validateBackgroundImage(QImage image) {
if (image.format() != QImage::Format_ARGB32_Premultiplied) {
image = std::move(image).convertToFormat(
QImage::Format_ARGB32_Premultiplied);
}
image.setDevicePixelRatio(cRetinaFactor());
2019-01-29 10:57:29 +00:00
return image;
}
2018-08-02 12:47:50 +00:00
void ClearApplying() {
2019-01-16 17:26:26 +00:00
GlobalApplying = Applying();
2018-08-02 12:47:50 +00:00
}
2019-09-03 08:25:19 +00:00
SendMediaReady PrepareWallPaper(const QImage &image) {
PreparedPhotoThumbs thumbnails;
QVector<MTPPhotoSize> sizes;
QByteArray jpeg;
QBuffer jpegBuffer(&jpeg);
image.save(&jpegBuffer, "JPG", 87);
const auto scaled = [&](int size) {
return image.scaled(
size,
size,
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
};
const auto push = [&](const char *type, QImage &&image) {
sizes.push_back(MTP_photoSize(
MTP_string(type),
MTP_fileLocationToBeDeprecated(MTP_long(0), MTP_int(0)),
MTP_int(image.width()),
MTP_int(image.height()), MTP_int(0)));
thumbnails.emplace(type[0], std::move(image));
};
push("s", scaled(320));
const auto filename = qsl("wallpaper.jpg");
auto attributes = QVector<MTPDocumentAttribute>(
1,
MTP_documentAttributeFilename(MTP_string(filename)));
attributes.push_back(MTP_documentAttributeImageSize(
MTP_int(image.width()),
MTP_int(image.height())));
const auto id = rand_value<DocumentId>();
const auto document = MTP_document(
MTP_flags(0),
MTP_long(id),
MTP_long(0),
MTP_bytes(),
MTP_int(base::unixtime::now()),
MTP_string("image/jpeg"),
MTP_int(jpeg.size()),
MTP_vector<MTPPhotoSize>(sizes),
MTP_int(MTP::maindc()),
MTP_vector<MTPDocumentAttribute>(attributes));
return SendMediaReady(
SendMediaType::ThemeFile,
QString(), // filepath
filename,
jpeg.size(),
jpeg,
id,
0,
QString(),
PeerId(),
MTP_photoEmpty(MTP_long(0)),
thumbnails,
document,
QByteArray(),
0);
}
} // namespace
2018-07-21 13:54:00 +00:00
ChatBackground::AdjustableColor::AdjustableColor(style::color data)
: item(data)
, original(data->c) {
}
ChatBackground::ChatBackground() : _adjustableColors({
st::msgServiceBg,
st::msgServiceBgSelected,
st::historyScrollBg,
st::historyScrollBgOver,
st::historyScrollBarBg,
st::historyScrollBarBgOver }) {
saveAdjustableColors();
}
void ChatBackground::setThemeData(QImage &&themeImage, bool themeTile) {
2019-01-29 10:57:29 +00:00
_themeImage = validateBackgroundImage(std::move(themeImage));
_themeTile = themeTile;
}
void ChatBackground::start() {
2019-06-06 09:37:12 +00:00
if (!Data::details::IsUninitializedWallPaper(_paper)) {
return;
}
if (!Local::readBackground()) {
set(Data::ThemeWallPaper());
2019-02-08 16:20:08 +00:00
}
2019-06-06 09:37:12 +00:00
Core::App().activeAccount().sessionValue(
2019-07-24 11:45:24 +00:00
) | rpl::filter([=](Main::Session *session) {
2019-06-06 09:37:12 +00:00
return session != _session;
2019-07-24 11:45:24 +00:00
}) | rpl::start_with_next([=](Main::Session *session) {
2019-02-08 16:20:08 +00:00
_session = session;
checkUploadWallPaper();
2019-06-06 09:37:12 +00:00
}, _lifetime);
2019-02-08 16:20:08 +00:00
}
void ChatBackground::checkUploadWallPaper() {
if (!_session) {
_wallPaperUploadLifetime = rpl::lifetime();
_wallPaperUploadId = FullMsgId();
_wallPaperRequestId = 0;
return;
}
if (const auto id = base::take(_wallPaperUploadId)) {
_session->uploader().cancel(id);
}
if (const auto id = base::take(_wallPaperRequestId)) {
_session->api().request(id).cancel();
}
2019-02-09 13:36:07 +00:00
if (!Data::IsCustomWallPaper(_paper)
|| _original.isNull()
2019-09-02 16:10:18 +00:00
|| isEditingTheme()) {
2019-02-08 16:20:08 +00:00
return;
}
const auto ready = PrepareWallPaper(_original);
const auto documentId = ready.id;
2019-08-12 16:33:36 +00:00
_wallPaperUploadId = FullMsgId(0, _session->data().nextLocalMessageId());
2019-02-08 16:20:08 +00:00
_session->uploader().uploadMedia(_wallPaperUploadId, ready);
if (_wallPaperUploadLifetime) {
return;
}
_wallPaperUploadLifetime = _session->uploader().documentReady(
) | rpl::start_with_next([=](const Storage::UploadedDocument &data) {
if (data.fullId != _wallPaperUploadId) {
return;
}
_wallPaperUploadId = FullMsgId();
_wallPaperRequestId = _session->api().request(
MTPaccount_UploadWallPaper(
data.file,
MTP_string("image/jpeg"),
_paper.mtpSettings()
)
).done([=](const MTPWallPaper &result) {
result.match([&](const MTPDwallPaper &data) {
_session->data().documentConvert(
_session->data().document(documentId),
2019-07-05 13:38:38 +00:00
data.vdocument());
2019-02-08 16:20:08 +00:00
});
if (const auto paper = Data::WallPaper::Create(result)) {
2019-02-09 13:36:07 +00:00
setPaper(*paper);
2019-02-08 16:20:08 +00:00
writeNewBackgroundSettings();
2019-02-09 13:36:07 +00:00
notify(BackgroundUpdate(BackgroundUpdate::Type::New, tile()));
2019-02-08 16:20:08 +00:00
}
}).send();
});
}
2019-01-29 10:57:29 +00:00
void ChatBackground::set(const Data::WallPaper &paper, QImage image) {
image = ProcessBackgroundImage(std::move(image));
2019-01-29 07:29:38 +00:00
2019-01-28 13:59:49 +00:00
const auto needResetAdjustable = Data::IsDefaultWallPaper(paper)
&& !Data::IsDefaultWallPaper(_paper)
&& !nightMode()
2019-09-03 18:04:38 +00:00
&& _themeObject.pathAbsolute.isEmpty();
2019-01-28 13:59:49 +00:00
if (Data::IsThemeWallPaper(paper) && _themeImage.isNull()) {
setPaper(Data::DefaultWallPaper());
2019-01-16 17:26:26 +00:00
} else {
setPaper(paper);
2019-01-16 17:26:26 +00:00
if (needResetAdjustable) {
// If we had a default color theme with non-default background,
// and we switch to default background we must somehow switch from
// adjusted service colors to default (non-adjusted) service colors.
// The only way to do that right now is through full palette reset.
restoreAdjustableColors();
}
}
2019-01-28 13:59:49 +00:00
if (Data::IsThemeWallPaper(_paper)) {
(nightMode() ? _tileNightValue : _tileDayValue) = _themeTile;
2019-01-29 10:57:29 +00:00
setPreparedImage(_themeImage, _themeImage);
2019-01-28 13:59:49 +00:00
} else if (Data::details::IsTestingThemeWallPaper(_paper)
|| Data::details::IsTestingDefaultWallPaper(_paper)
|| Data::details::IsTestingEditorWallPaper(_paper)) {
2019-01-29 10:57:29 +00:00
if (Data::details::IsTestingDefaultWallPaper(_paper)
|| image.isNull()) {
image.load(qsl(":/gui/art/bg.jpg"));
2019-01-28 13:59:49 +00:00
setPaper(Data::details::TestingDefaultWallPaper());
}
2019-01-29 10:57:29 +00:00
image = validateBackgroundImage(std::move(image));
setPreparedImage(image, image);
} else {
2019-01-28 13:59:49 +00:00
if (Data::IsLegacy1DefaultWallPaper(_paper)) {
image.load(qsl(":/gui/art/bg_initial.jpg"));
const auto scale = cScale() * cIntRetinaFactor();
if (scale != 100) {
image = image.scaledToWidth(
ConvertScale(image.width(), scale),
Qt::SmoothTransformation);
}
2019-01-28 13:59:49 +00:00
} else if (Data::IsDefaultWallPaper(_paper)
2019-01-29 07:29:38 +00:00
|| (!_paper.backgroundColor() && image.isNull())) {
2019-02-08 13:43:31 +00:00
setPaper(Data::DefaultWallPaper().withParamsFrom(_paper));
image.load(qsl(":/gui/art/bg.jpg"));
}
2019-01-16 17:26:26 +00:00
Local::writeBackground(
_paper,
2019-01-28 13:59:49 +00:00
((Data::IsDefaultWallPaper(_paper)
|| Data::IsLegacy1DefaultWallPaper(_paper))
2019-01-16 17:26:26 +00:00
? QImage()
: image));
2019-01-29 07:29:38 +00:00
if (const auto fill = _paper.backgroundColor()) {
if (_paper.isPattern() && !image.isNull()) {
2019-01-29 10:57:29 +00:00
auto prepared = validateBackgroundImage(
Data::PreparePatternImage(
image,
*fill,
Data::PatternColor(*fill),
2019-01-29 10:57:29 +00:00
_paper.patternIntensity()));
setPreparedImage(std::move(image), std::move(prepared));
2019-01-29 07:29:38 +00:00
} else {
2019-01-29 10:57:29 +00:00
_original = QImage();
2019-01-29 07:29:38 +00:00
_pixmap = QPixmap();
_pixmapForTiled = QPixmap();
if (adjustPaletteRequired()) {
adjustPaletteUsingColor(*fill);
}
}
} else {
2019-01-29 10:57:29 +00:00
image = validateBackgroundImage(std::move(image));
setPreparedImage(image, image);
}
}
2019-01-29 10:57:29 +00:00
Assert(colorForFill()
|| (!_original.isNull()
&& !_pixmap.isNull()
&& !_pixmapForTiled.isNull()));
notify(BackgroundUpdate(BackgroundUpdate::Type::New, tile()));
2018-07-21 13:54:00 +00:00
if (needResetAdjustable) {
notify(BackgroundUpdate(BackgroundUpdate::Type::TestingTheme, tile()), true);
notify(BackgroundUpdate(BackgroundUpdate::Type::ApplyingTheme, tile()), true);
}
2019-02-08 16:20:08 +00:00
checkUploadWallPaper();
}
2019-01-29 10:57:29 +00:00
void ChatBackground::setPreparedImage(QImage original, QImage prepared) {
Expects(original.format() == QImage::Format_ARGB32_Premultiplied);
Expects(original.width() > 0 && original.height() > 0);
Expects(prepared.format() == QImage::Format_ARGB32_Premultiplied);
Expects(prepared.width() > 0 && prepared.height() > 0);
2019-01-29 10:57:29 +00:00
_original = std::move(original);
2019-02-06 14:38:37 +00:00
if (!_paper.isPattern() && _paper.isBlurred()) {
prepared = Data::PrepareBlurredBackground(std::move(prepared));
}
if (adjustPaletteRequired()) {
2019-01-29 10:57:29 +00:00
adjustPaletteUsingBackground(prepared);
}
2019-01-29 10:57:29 +00:00
preparePixmaps(std::move(prepared));
}
2019-01-29 10:57:29 +00:00
void ChatBackground::preparePixmaps(QImage image) {
const auto width = image.width();
const auto height = image.height();
const auto isSmallForTiled = (width < kMinimumTiledSize)
|| (height < kMinimumTiledSize);
if (isSmallForTiled) {
2019-01-29 10:57:29 +00:00
const auto repeatTimesX = qCeil(kMinimumTiledSize / (1. * width));
const auto repeatTimesY = qCeil(kMinimumTiledSize / (1. * height));
auto imageForTiled = QImage(
width * repeatTimesX,
height * repeatTimesY,
QImage::Format_ARGB32_Premultiplied);
imageForTiled.setDevicePixelRatio(image.devicePixelRatio());
auto imageForTiledBytes = imageForTiled.bits();
auto bytesInLine = width * sizeof(uint32);
for (auto timesY = 0; timesY != repeatTimesY; ++timesY) {
auto imageBytes = image.constBits();
for (auto y = 0; y != height; ++y) {
for (auto timesX = 0; timesX != repeatTimesX; ++timesX) {
memcpy(imageForTiledBytes, imageBytes, bytesInLine);
imageForTiledBytes += bytesInLine;
}
imageBytes += image.bytesPerLine();
imageForTiledBytes += imageForTiled.bytesPerLine() - (repeatTimesX * bytesInLine);
}
}
_pixmapForTiled = App::pixmapFromImageInPlace(std::move(imageForTiled));
}
_isMonoColorImage = CalculateIsMonoColorImage(image);
_pixmap = App::pixmapFromImageInPlace(std::move(image));
if (!isSmallForTiled) {
_pixmapForTiled = _pixmap;
}
}
void ChatBackground::setPaper(const Data::WallPaper &paper) {
2019-02-08 13:43:31 +00:00
_paper = paper.withoutImageData();
}
bool ChatBackground::adjustPaletteRequired() {
const auto usingThemeBackground = [&] {
2019-01-28 13:59:49 +00:00
return Data::IsThemeWallPaper(_paper)
|| Data::details::IsTestingThemeWallPaper(_paper);
};
const auto usingDefaultBackground = [&] {
2019-01-28 13:59:49 +00:00
return Data::IsDefaultWallPaper(_paper)
|| Data::details::IsTestingDefaultWallPaper(_paper);
};
2019-09-02 16:10:18 +00:00
if (isEditingTheme()) {
return false;
} else if (isNonDefaultThemeOrBackground() || nightMode()) {
return !usingThemeBackground();
}
return !usingDefaultBackground();
}
2019-09-02 16:10:18 +00:00
bool ChatBackground::isEditingTheme() const {
2019-09-05 06:51:46 +00:00
return _editingTheme;
}
void ChatBackground::setIsEditingTheme(bool editing) {
if (_editingTheme == editing) {
return;
}
_editingTheme = editing;
if (!_editingTheme) {
reapplyWithNightMode(std::nullopt, _nightMode);
KeepApplied();
}
2019-02-09 13:36:07 +00:00
}
2019-01-29 10:57:29 +00:00
void ChatBackground::adjustPaletteUsingBackground(const QImage &image) {
2019-01-29 17:03:51 +00:00
adjustPaletteUsingColor(CountAverageColor(image));
}
void ChatBackground::adjustPaletteUsingColor(QColor color) {
2019-01-29 17:03:51 +00:00
const auto prepared = color.toHsl();
for (const auto &adjustable : _adjustableColors) {
const auto adjusted = AdjustedColor(adjustable.item->c, prepared);
adjustable.item.set(
adjusted.red(),
adjusted.green(),
adjusted.blue(),
adjusted.alpha());
2018-07-21 13:54:00 +00:00
}
}
2019-01-29 07:29:38 +00:00
std::optional<QColor> ChatBackground::colorForFill() const {
return _pixmap.isNull() ? _paper.backgroundColor() : std::nullopt;
}
QImage ChatBackground::createCurrentImage() const {
2019-01-29 07:29:38 +00:00
if (const auto fill = colorForFill()) {
auto result = QImage(
kMinimumTiledSize,
kMinimumTiledSize,
QImage::Format_ARGB32_Premultiplied);
result.fill(*fill);
return result;
}
2019-01-29 10:57:29 +00:00
return pixmap().toImage();
}
bool ChatBackground::tile() const {
return nightMode() ? _tileNightValue : _tileDayValue;
}
bool ChatBackground::tileDay() const {
2019-01-28 13:59:49 +00:00
if (Data::details::IsTestingThemeWallPaper(_paper) ||
Data::details::IsTestingDefaultWallPaper(_paper)) {
if (!nightMode()) {
return _tileForRevert;
}
}
return _tileDayValue;
}
bool ChatBackground::tileNight() const {
2019-01-28 13:59:49 +00:00
if (Data::details::IsTestingThemeWallPaper(_paper) ||
Data::details::IsTestingDefaultWallPaper(_paper)) {
if (nightMode()) {
return _tileForRevert;
}
}
return _tileNightValue;
}
bool ChatBackground::isMonoColorImage() const {
return _isMonoColorImage;
}
void ChatBackground::ensureStarted() {
2019-01-29 07:29:38 +00:00
if (_pixmap.isNull() && !_paper.backgroundColor()) {
// We should start first, otherwise the default call
// to start() will reset this value to _themeTile.
start();
}
}
void ChatBackground::setTile(bool tile) {
ensureStarted();
const auto old = this->tile();
if (nightMode()) {
setTileNightValue(tile);
} else {
setTileDayValue(tile);
}
if (this->tile() != old) {
2019-01-28 13:59:49 +00:00
if (!Data::details::IsTestingThemeWallPaper(_paper)
&& !Data::details::IsTestingDefaultWallPaper(_paper)) {
Local::writeUserSettings();
}
notify(BackgroundUpdate(BackgroundUpdate::Type::Changed, tile));
}
}
void ChatBackground::setTileDayValue(bool tile) {
ensureStarted();
_tileDayValue = tile;
}
void ChatBackground::setTileNightValue(bool tile) {
ensureStarted();
_tileNightValue = tile;
}
2019-09-03 18:04:38 +00:00
void ChatBackground::setThemeObject(const Object &object) {
_themeObject = object;
2019-09-05 07:42:06 +00:00
_themeObject.content = QByteArray();
}
2019-09-03 18:04:38 +00:00
const Object &ChatBackground::themeObject() const {
return _themeObject;
}
void ChatBackground::reset() {
2019-01-28 13:59:49 +00:00
if (Data::details::IsTestingThemeWallPaper(_paper)
|| Data::details::IsTestingDefaultWallPaper(_paper)) {
if (_themeImage.isNull()) {
2019-01-28 13:59:49 +00:00
_paperForRevert = Data::DefaultWallPaper();
2019-01-29 10:57:29 +00:00
_originalForRevert = QImage();
_tileForRevert = false;
} else {
2019-01-28 13:59:49 +00:00
_paperForRevert = Data::ThemeWallPaper();
2019-01-29 10:57:29 +00:00
_originalForRevert = _themeImage;
_tileForRevert = _themeTile;
}
} else {
2019-01-29 10:57:29 +00:00
set(Data::ThemeWallPaper());
2018-07-21 13:54:00 +00:00
restoreAdjustableColors();
notify(BackgroundUpdate(BackgroundUpdate::Type::TestingTheme, tile()), true);
notify(BackgroundUpdate(BackgroundUpdate::Type::ApplyingTheme, tile()), true);
}
}
void ChatBackground::saveForRevert() {
ensureStarted();
2019-01-28 13:59:49 +00:00
if (!Data::details::IsTestingThemeWallPaper(_paper)
&& !Data::details::IsTestingDefaultWallPaper(_paper)) {
2019-01-16 17:26:26 +00:00
_paperForRevert = _paper;
2019-01-29 10:57:29 +00:00
_originalForRevert = std::move(_original);
_tileForRevert = tile();
}
}
2018-07-21 13:54:00 +00:00
void ChatBackground::saveAdjustableColors() {
for (auto &color : _adjustableColors) {
color.original = color.item->c;
}
}
void ChatBackground::restoreAdjustableColors() {
for (const auto &color : _adjustableColors) {
const auto value = color.original;
color.item.set(value.red(), value.green(), value.blue(), value.alpha());
}
}
void ChatBackground::setTestingTheme(Instance &&theme) {
style::main_palette::apply(theme.palette);
2018-07-21 13:54:00 +00:00
saveAdjustableColors();
auto switchToThemeBackground = !theme.background.isNull()
2019-01-28 13:59:49 +00:00
|| Data::IsThemeWallPaper(_paper)
|| (Data::IsDefaultWallPaper(_paper)
&& !nightMode()
2019-09-03 18:04:38 +00:00
&& _themeObject.pathAbsolute.isEmpty());
2019-09-02 16:10:18 +00:00
if (AreTestingTheme() && isEditingTheme()) {
// Grab current background image if it is not already custom
2019-01-29 10:57:29 +00:00
// Use prepared pixmap, not original image, because we're
// for sure switching to a non-pattern wall-paper (testing editor).
2019-01-28 13:59:49 +00:00
if (!Data::IsCustomWallPaper(_paper)) {
saveForRevert();
2019-01-29 10:57:29 +00:00
set(
2019-01-28 13:59:49 +00:00
Data::details::TestingEditorWallPaper(),
std::move(_pixmap).toImage());
}
} else if (switchToThemeBackground) {
saveForRevert();
2019-01-29 10:57:29 +00:00
set(
2019-01-28 13:59:49 +00:00
Data::details::TestingThemeWallPaper(),
std::move(theme.background));
setTile(theme.tiled);
} else {
// Apply current background image so that service bg colors are recounted.
2019-01-29 10:57:29 +00:00
set(_paper, std::move(_original));
}
notify(BackgroundUpdate(BackgroundUpdate::Type::TestingTheme, tile()), true);
}
void ChatBackground::setTestingDefaultTheme() {
style::main_palette::reset();
2018-07-21 13:54:00 +00:00
saveAdjustableColors();
saveForRevert();
2019-01-29 10:57:29 +00:00
set(Data::details::TestingDefaultWallPaper());
setTile(false);
notify(BackgroundUpdate(BackgroundUpdate::Type::TestingTheme, tile()), true);
}
2019-09-03 18:04:38 +00:00
void ChatBackground::keepApplied(const Object &object, bool write) {
setThemeObject(object);
2019-01-28 13:59:49 +00:00
if (Data::details::IsTestingEditorWallPaper(_paper)) {
setPaper(Data::CustomWallPaper());
_themeImage = QImage();
_themeTile = false;
if (write) {
writeNewBackgroundSettings();
}
2019-01-28 13:59:49 +00:00
} else if (Data::details::IsTestingThemeWallPaper(_paper)) {
setPaper(Data::ThemeWallPaper());
2019-01-29 10:57:29 +00:00
_themeImage = validateBackgroundImage(base::duplicate(_original));
_themeTile = tile();
if (write) {
writeNewBackgroundSettings();
}
2019-01-28 13:59:49 +00:00
} else if (Data::details::IsTestingDefaultWallPaper(_paper)) {
setPaper(Data::DefaultWallPaper());
_themeImage = QImage();
_themeTile = false;
if (write) {
writeNewBackgroundSettings();
}
}
notify(BackgroundUpdate(BackgroundUpdate::Type::ApplyingTheme, tile()), true);
}
2018-07-21 13:54:00 +00:00
bool ChatBackground::isNonDefaultThemeOrBackground() {
start();
return nightMode()
2019-09-03 18:04:38 +00:00
? (_themeObject.pathAbsolute != NightThemePath()
2019-01-28 13:59:49 +00:00
|| !Data::IsThemeWallPaper(_paper))
2019-09-03 18:04:38 +00:00
: (!_themeObject.pathAbsolute.isEmpty()
2019-01-28 13:59:49 +00:00
|| !Data::IsDefaultWallPaper(_paper));
}
bool ChatBackground::isNonDefaultBackground() {
start();
2019-09-03 18:04:38 +00:00
return _themeObject.pathAbsolute.isEmpty()
2019-01-28 13:59:49 +00:00
? !Data::IsDefaultWallPaper(_paper)
: !Data::IsThemeWallPaper(_paper);
}
void ChatBackground::writeNewBackgroundSettings() {
if (tile() != _tileForRevert) {
Local::writeUserSettings();
}
Local::writeBackground(
2019-01-16 17:26:26 +00:00
_paper,
2019-01-28 13:59:49 +00:00
((Data::IsThemeWallPaper(_paper)
|| Data::IsDefaultWallPaper(_paper))
? QImage()
2019-01-29 10:57:29 +00:00
: _original));
}
void ChatBackground::revert() {
2019-01-28 13:59:49 +00:00
if (Data::details::IsTestingThemeWallPaper(_paper)
|| Data::details::IsTestingDefaultWallPaper(_paper)
|| Data::details::IsTestingEditorWallPaper(_paper)) {
setTile(_tileForRevert);
2019-01-29 10:57:29 +00:00
set(_paperForRevert, std::move(_originalForRevert));
} else {
// Apply current background image so that service bg colors are recounted.
2019-01-29 10:57:29 +00:00
set(_paper, std::move(_original));
}
notify(BackgroundUpdate(BackgroundUpdate::Type::RevertingTheme, tile()), true);
}
void ChatBackground::setNightModeValue(bool nightMode) {
_nightMode = nightMode;
}
bool ChatBackground::nightMode() const {
return _nightMode;
}
2019-09-05 06:51:46 +00:00
void ChatBackground::reapplyWithNightMode(
std::optional<QString> themePath,
bool newNightMode) {
const auto settingExactTheme = themePath.has_value();
const auto nightModeChanged = (newNightMode != _nightMode);
const auto oldNightMode = _nightMode;
_nightMode = newNightMode;
2019-09-05 06:51:46 +00:00
auto read = settingExactTheme ? Saved() : Local::readThemeAfterSwitch();
2019-09-03 18:04:38 +00:00
auto path = read.object.pathAbsolute;
_nightMode = oldNightMode;
auto oldTileValue = (_nightMode ? _tileNightValue : _tileDayValue);
2018-08-02 12:47:50 +00:00
const auto alreadyOnDisk = [&] {
2019-09-03 18:04:38 +00:00
if (read.object.content.isEmpty()) {
return false;
}
auto preview = std::make_unique<Preview>();
2019-09-03 18:04:38 +00:00
preview->object = std::move(read.object);
preview->instance.cached = std::move(read.cache);
const auto loaded = loadTheme(
2019-09-03 18:04:38 +00:00
preview->object.content,
2019-09-05 06:51:46 +00:00
std::nullopt,
preview->instance.cached,
2019-08-27 13:59:15 +00:00
ColorizerForTheme(path),
&preview->instance);
if (!loaded) {
return false;
}
Apply(std::move(preview));
return true;
}();
2018-08-02 12:47:50 +00:00
if (!alreadyOnDisk) {
path = themePath
? *themePath
: (newNightMode ? NightThemePath() : QString());
2019-08-27 13:59:15 +00:00
ApplyDefaultWithPath(path);
}
// Theme editor could have already reverted the testing of this toggle.
if (AreTestingTheme()) {
2019-01-16 17:26:26 +00:00
GlobalApplying.overrideKeep = [=] {
2019-09-05 06:51:46 +00:00
if (nightModeChanged) {
_nightMode = newNightMode;
2018-07-24 19:49:37 +00:00
2019-09-05 06:51:46 +00:00
// Restore the value, it was set inside theme testing.
(oldNightMode ? _tileNightValue : _tileDayValue) = oldTileValue;
}
2019-09-03 18:04:38 +00:00
const auto saved = std::move(GlobalApplying.data);
if (!alreadyOnDisk) {
// First-time switch to default night mode should write it.
2019-09-03 18:04:38 +00:00
Local::writeTheme(saved);
}
ClearApplying();
2019-09-05 06:51:46 +00:00
keepApplied(saved.object, settingExactTheme);
if (tile() != _tileForRevert) {
Local::writeUserSettings();
}
2019-09-05 06:51:46 +00:00
if (nightModeChanged) {
Local::writeSettings();
}
if (!settingExactTheme && !Local::readBackground()) {
2019-01-29 10:57:29 +00:00
set(Data::ThemeWallPaper());
}
};
}
}
2019-09-05 06:51:46 +00:00
void ChatBackground::toggleNightMode(std::optional<QString> themePath) {
reapplyWithNightMode(themePath, !_nightMode);
}
ChatBackground *Background() {
2019-01-16 17:26:26 +00:00
GlobalBackground.createIfNull();
return GlobalBackground.data();
}
2019-09-05 07:42:06 +00:00
bool IsEmbeddedTheme(const QString &path) {
return path.isEmpty() || path.startsWith(qstr(":/gui/"));
}
2019-09-05 06:51:46 +00:00
bool Initialize(Saved &&saved) {
if (InitializeFromSaved(std::move(saved))) {
2019-09-03 18:04:38 +00:00
Background()->setThemeObject(saved.object);
return true;
}
2019-09-05 06:51:46 +00:00
return false;
}
2019-09-05 06:51:46 +00:00
void Uninitialize() {
2019-01-16 17:26:26 +00:00
GlobalBackground.clear();
GlobalApplying = Applying();
}
2019-09-05 05:18:21 +00:00
bool Apply(
const QString &filepath,
const Data::CloudTheme &cloud) {
2019-09-05 07:42:06 +00:00
if (auto preview = PreviewFromFile(QByteArray(), filepath, cloud)) {
return Apply(std::move(preview));
}
return false;
}
bool Apply(std::unique_ptr<Preview> preview) {
2019-09-03 18:04:38 +00:00
GlobalApplying.data.object = std::move(preview->object);
GlobalApplying.data.cache = std::move(preview->instance.cached);
2019-01-16 17:26:26 +00:00
if (GlobalApplying.paletteForRevert.isEmpty()) {
GlobalApplying.paletteForRevert = style::main_palette::save();
}
Background()->setTestingTheme(std::move(preview->instance));
return true;
}
2019-08-27 13:59:15 +00:00
void ApplyDefaultWithPath(const QString &themePath) {
if (!themePath.isEmpty()) {
2019-09-05 07:42:06 +00:00
if (auto preview = PreviewFromFile(QByteArray(), themePath, {})) {
Apply(std::move(preview));
}
} else {
2019-09-03 18:04:38 +00:00
GlobalApplying.data = Saved();
2019-01-16 17:26:26 +00:00
if (GlobalApplying.paletteForRevert.isEmpty()) {
GlobalApplying.paletteForRevert = style::main_palette::save();
}
Background()->setTestingDefaultTheme();
}
}
2019-09-05 06:51:46 +00:00
bool ApplyEditedPalette(const QByteArray &content) {
auto out = Instance();
2019-08-27 13:59:15 +00:00
if (!loadColorScheme(content, Colorizer(), &out)) {
return false;
}
2019-09-05 06:51:46 +00:00
style::main_palette::apply(out.palette);
Background()->notify(BackgroundUpdate(BackgroundUpdate::Type::ApplyingEdit, Background()->tile()), true);
return true;
}
void KeepApplied() {
if (!AreTestingTheme()) {
return;
2019-01-16 17:26:26 +00:00
} else if (GlobalApplying.overrideKeep) {
2018-09-26 13:06:30 +00:00
// This callback will be destroyed while running.
// And it won't be able to safely access captures after that.
// So we save it on stack for the time while it is running.
2019-01-16 17:26:26 +00:00
const auto onstack = base::take(GlobalApplying.overrideKeep);
onstack();
return;
}
2019-09-03 18:04:38 +00:00
const auto saved = std::move(GlobalApplying.data);
Local::writeTheme(saved);
2018-08-02 12:47:50 +00:00
ClearApplying();
2019-09-03 18:04:38 +00:00
Background()->keepApplied(saved.object, true);
}
void Revert() {
if (!AreTestingTheme()) {
return;
}
2019-01-16 17:26:26 +00:00
style::main_palette::load(GlobalApplying.paletteForRevert);
2018-07-21 13:54:00 +00:00
Background()->saveAdjustableColors();
2018-08-02 12:47:50 +00:00
ClearApplying();
Background()->revert();
}
QString NightThemePath() {
return str_const_toString(kNightThemeFile);
}
bool IsNonDefaultBackground() {
return Background()->isNonDefaultBackground();
}
bool IsNightMode() {
2019-01-16 17:26:26 +00:00
return GlobalBackground ? Background()->nightMode() : false;
}
void SetNightModeValue(bool nightMode) {
2019-01-16 17:26:26 +00:00
if (GlobalBackground || nightMode) {
Background()->setNightModeValue(nightMode);
}
}
void ToggleNightMode() {
2019-08-27 13:59:15 +00:00
Background()->toggleNightMode(std::nullopt);
}
2019-08-27 13:59:15 +00:00
void ToggleNightMode(const QString &path) {
Background()->toggleNightMode(path);
}
2019-09-03 15:24:51 +00:00
bool LoadFromContent(
const QByteArray &content,
not_null<Instance*> out,
const Colorizer &colorizer) {
if (content.size() < 4) {
LOG(("Theme Error: Bad theme content size: %1").arg(content.size()));
return false;
}
2019-09-05 06:51:46 +00:00
return loadTheme(content, std::nullopt, out->cached, colorizer, out);
2019-09-03 15:24:51 +00:00
}
bool LoadFromFile(
const QString &path,
2019-09-03 15:24:51 +00:00
not_null<Instance*> out,
not_null<QByteArray*> outContent) {
*outContent = readThemeContent(path);
2019-09-03 15:24:51 +00:00
return LoadFromContent(*outContent, out, ColorizerForTheme(path));
}
2019-09-03 15:24:51 +00:00
bool LoadFromContent(const QByteArray &content, not_null<Instance*> out) {
return LoadFromContent(content, out, {});
}
2019-09-02 16:10:18 +00:00
QString EditingPalettePath() {
return cWorkingDir() + "tdata/editing-theme.tdesktop-palette";
}
2019-09-05 06:51:46 +00:00
void ClearEditingPalette() {
QFile(EditingPalettePath()).remove();
}
2019-01-29 17:03:51 +00:00
QColor CountAverageColor(const QImage &image) {
Expects(image.format() == QImage::Format_ARGB32_Premultiplied);
uint64 components[3] = { 0 };
uint64 componentsScroll[3] = { 0 };
const auto w = image.width();
const auto h = image.height();
const auto size = w * h;
if (const auto pix = image.constBits()) {
for (auto i = 0, l = size * 4; i != l; i += 4) {
components[2] += pix[i + 0];
components[1] += pix[i + 1];
components[0] += pix[i + 2];
}
}
if (size) {
for (auto i = 0; i != 3; ++i) {
components[i] /= size;
}
}
return QColor(components[0], components[1], components[2]);
}
QColor AdjustedColor(QColor original, QColor background) {
return QColor::fromHslF(
background.hslHueF(),
background.hslSaturationF(),
original.lightnessF(),
original.alphaF()
).toRgb();
}
QImage ProcessBackgroundImage(QImage image) {
constexpr auto kMaxSize = 2960;
if (image.format() != QImage::Format_ARGB32_Premultiplied) {
image = std::move(image).convertToFormat(
QImage::Format_ARGB32_Premultiplied);
}
if (image.width() > 40 * image.height()) {
const auto width = 40 * image.height();
const auto height = image.height();
image = image.copy((image.width() - width) / 2, 0, width, height);
} else if (image.height() > 40 * image.width()) {
const auto width = image.width();
const auto height = 40 * image.width();
image = image.copy(0, (image.height() - height) / 2, width, height);
}
if (image.width() > kMaxSize || image.height() > kMaxSize) {
image = image.scaled(
kMaxSize,
kMaxSize,
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
}
return image;
}
void ComputeBackgroundRects(QRect wholeFill, QSize imageSize, QRect &to, QRect &from) {
if (uint64(imageSize.width()) * wholeFill.height() > uint64(imageSize.height()) * wholeFill.width()) {
float64 pxsize = wholeFill.height() / float64(imageSize.height());
int takewidth = qCeil(wholeFill.width() / pxsize);
if (takewidth > imageSize.width()) {
takewidth = imageSize.width();
} else if ((imageSize.width() % 2) != (takewidth % 2)) {
++takewidth;
}
to = QRect(int((wholeFill.width() - takewidth * pxsize) / 2.), 0, qCeil(takewidth * pxsize), wholeFill.height());
from = QRect((imageSize.width() - takewidth) / 2, 0, takewidth, imageSize.height());
} else {
float64 pxsize = wholeFill.width() / float64(imageSize.width());
int takeheight = qCeil(wholeFill.height() / pxsize);
if (takeheight > imageSize.height()) {
takeheight = imageSize.height();
} else if ((imageSize.height() % 2) != (takeheight % 2)) {
++takeheight;
}
to = QRect(0, int((wholeFill.height() - takeheight * pxsize) / 2.), wholeFill.width(), qCeil(takeheight * pxsize));
from = QRect(0, (imageSize.height() - takeheight) / 2, imageSize.width(), takeheight);
}
}
bool ReadPaletteValues(const QByteArray &content, Fn<bool(QLatin1String name, QLatin1String value)> callback) {
if (content.size() > kThemeSchemeSizeLimit) {
LOG(("Theme Error: color scheme file too large (should be less than 1 MB, got %2)").arg(content.size()));
return false;
}
auto data = base::parse::stripComments(content);
auto from = data.constData(), end = from + data.size();
while (from != end) {
auto name = QLatin1String("");
auto value = QLatin1String("");
if (!readNameAndValue(from, end, &name, &value)) {
return false;
}
if (name.size() == 0) { // End of content reached.
return true;
}
if (!callback(name, value)) {
return false;
}
}
return true;
}
} // namespace Theme
} // namespace Window