2
0
mirror of https://github.com/telegramdesktop/tdesktop synced 2025-08-31 06:26:18 +00:00

Divide structs into several data/ modules.

This commit is contained in:
John Preston
2017-09-26 14:49:16 +03:00
parent f2a5862714
commit ffc20e4492
68 changed files with 4985 additions and 4065 deletions

View File

@@ -0,0 +1,951 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "data/data_document.h"
#include "lang/lang_keys.h"
#include "inline_bots/inline_bot_layout_item.h"
//#include "observer_peer.h"
#include "mainwidget.h"
//#include "application.h"
//#include "storage/file_upload.h"
//#include "mainwindow.h"
#include "core/file_utilities.h"
//#include "apiwrap.h"
//#include "boxes/confirm_box.h"
#include "media/media_audio.h"
#include "storage/localstorage.h"
#include "platform/platform_specific.h"
#include "history/history_media_types.h"
//#include "styles/style_history.h"
//#include "window/themes/window_theme.h"
//#include "auth_session.h"
#include "messenger.h"
//#include "storage/file_download.h"
QString joinList(const QStringList &list, const QString &sep) {
QString result;
if (list.isEmpty()) return result;
int32 l = list.size(), s = sep.size() * (l - 1);
for (int32 i = 0; i < l; ++i) {
s += list.at(i).size();
}
result.reserve(s);
result.append(list.at(0));
for (int32 i = 1; i < l; ++i) {
result.append(sep).append(list.at(i));
}
return result;
}
QString saveFileName(const QString &title, const QString &filter, const QString &prefix, QString name, bool savingAs, const QDir &dir) {
#ifdef Q_OS_WIN
name = name.replace(QRegularExpression(qsl("[\\\\\\/\\:\\*\\?\\\"\\<\\>\\|]")), qsl("_"));
#elif defined Q_OS_MAC
name = name.replace(QRegularExpression(qsl("[\\:]")), qsl("_"));
#elif defined Q_OS_LINUX
name = name.replace(QRegularExpression(qsl("[\\/]")), qsl("_"));
#endif
if (Global::AskDownloadPath() || savingAs) {
if (!name.isEmpty() && name.at(0) == QChar::fromLatin1('.')) {
name = filedialogDefaultName(prefix, name);
} else if (dir.path() != qsl(".")) {
QString path = dir.absolutePath();
if (path != cDialogLastPath()) {
cSetDialogLastPath(path);
Local::writeUserSettings();
}
}
// check if extension of filename is present in filter
// it should be in first filter section on the first place
// place it there, if it is not
QString ext = QFileInfo(name).suffix(), fil = filter, sep = qsl(";;");
if (!ext.isEmpty()) {
if (QRegularExpression(qsl("^[a-zA-Z_0-9]+$")).match(ext).hasMatch()) {
QStringList filters = filter.split(sep);
if (filters.size() > 1) {
QString first = filters.at(0);
int32 start = first.indexOf(qsl("(*."));
if (start >= 0) {
if (!QRegularExpression(qsl("\\(\\*\\.") + ext + qsl("[\\)\\s]"), QRegularExpression::CaseInsensitiveOption).match(first).hasMatch()) {
QRegularExpressionMatch m = QRegularExpression(qsl(" \\*\\.") + ext + qsl("[\\)\\s]"), QRegularExpression::CaseInsensitiveOption).match(first);
if (m.hasMatch() && m.capturedStart() > start + 3) {
int32 oldpos = m.capturedStart(), oldend = m.capturedEnd();
fil = first.mid(0, start + 3) + ext + qsl(" *.") + first.mid(start + 3, oldpos - start - 3) + first.mid(oldend - 1) + sep + joinList(filters.mid(1), sep);
} else {
fil = first.mid(0, start + 3) + ext + qsl(" *.") + first.mid(start + 3) + sep + joinList(filters.mid(1), sep);
}
}
} else {
fil = QString();
}
} else {
fil = QString();
}
} else {
fil = QString();
}
}
return filedialogGetSaveFile(name, title, fil, name) ? name : QString();
}
QString path;
if (Global::DownloadPath().isEmpty()) {
path = psDownloadPath();
} else if (Global::DownloadPath() == qsl("tmp")) {
path = cTempDir();
} else {
path = Global::DownloadPath();
}
if (name.isEmpty()) name = qsl(".unknown");
if (name.at(0) == QChar::fromLatin1('.')) {
if (!QDir().exists(path)) QDir().mkpath(path);
return filedialogDefaultName(prefix, name, path);
}
if (dir.path() != qsl(".")) {
path = dir.absolutePath() + '/';
}
QString nameStart, extension;
int32 extPos = name.lastIndexOf('.');
if (extPos >= 0) {
nameStart = name.mid(0, extPos);
extension = name.mid(extPos);
} else {
nameStart = name;
}
QString nameBase = path + nameStart;
name = nameBase + extension;
for (int i = 0; QFileInfo(name).exists(); ++i) {
name = nameBase + QString(" (%1)").arg(i + 2) + extension;
}
if (!QDir().exists(path)) QDir().mkpath(path);
return name;
}
bool StickerData::setInstalled() const {
switch (set.type()) {
case mtpc_inputStickerSetID: {
auto it = Global::StickerSets().constFind(set.c_inputStickerSetID().vid.v);
return (it != Global::StickerSets().cend()) && !(it->flags & MTPDstickerSet::Flag::f_archived) && (it->flags & MTPDstickerSet::Flag::f_installed);
} break;
case mtpc_inputStickerSetShortName: {
auto name = qs(set.c_inputStickerSetShortName().vshort_name).toLower();
for (auto it = Global::StickerSets().cbegin(), e = Global::StickerSets().cend(); it != e; ++it) {
if (it->shortName.toLower() == name) {
return !(it->flags & MTPDstickerSet::Flag::f_archived) && (it->flags & MTPDstickerSet::Flag::f_installed);
}
}
} break;
}
return false;
}
QString documentSaveFilename(const DocumentData *data, bool forceSavingAs = false, const QString already = QString(), const QDir &dir = QDir()) {
auto alreadySavingFilename = data->loadingFilePath();
if (!alreadySavingFilename.isEmpty()) {
return alreadySavingFilename;
}
QString name, filter, caption, prefix;
MimeType mimeType = mimeTypeForName(data->mime);
QStringList p = mimeType.globPatterns();
QString pattern = p.isEmpty() ? QString() : p.front();
if (data->voice()) {
bool mp3 = (data->mime == qstr("audio/mp3"));
name = already.isEmpty() ? (mp3 ? qsl(".mp3") : qsl(".ogg")) : already;
filter = mp3 ? qsl("MP3 Audio (*.mp3);;") : qsl("OGG Opus Audio (*.ogg);;");
filter += FileDialog::AllFilesFilter();
caption = lang(lng_save_audio);
prefix = qsl("audio");
} else if (data->isVideo()) {
name = already.isEmpty() ? data->name : already;
if (name.isEmpty()) {
name = pattern.isEmpty() ? qsl(".mov") : pattern.replace('*', QString());
}
if (pattern.isEmpty()) {
filter = qsl("MOV Video (*.mov);;") + FileDialog::AllFilesFilter();
} else {
filter = mimeType.filterString() + qsl(";;") + FileDialog::AllFilesFilter();
}
caption = lang(lng_save_video);
prefix = qsl("video");
} else {
name = already.isEmpty() ? data->name : already;
if (name.isEmpty()) {
name = pattern.isEmpty() ? qsl(".unknown") : pattern.replace('*', QString());
}
if (pattern.isEmpty()) {
filter = QString();
} else {
filter = mimeType.filterString() + qsl(";;") + FileDialog::AllFilesFilter();
}
caption = lang(data->song() ? lng_save_audio_file : lng_save_file);
prefix = qsl("doc");
}
return saveFileName(caption, filter, prefix, name, forceSavingAs, dir);
}
void DocumentOpenClickHandler::doOpen(DocumentData *data, HistoryItem *context, ActionOnLoad action) {
if (!data->date) return;
auto msgId = context ? context->fullId() : FullMsgId();
bool playVoice = data->voice();
bool playMusic = data->tryPlaySong();
bool playVideo = data->isVideo();
bool playAnimation = data->isAnimation();
auto &location = data->location(true);
if (auto applyTheme = data->isTheme()) {
if (!location.isEmpty() && location.accessEnable()) {
Messenger::Instance().showDocument(data, context);
location.accessDisable();
return;
}
}
if (!location.isEmpty() || (!data->data().isEmpty() && (playVoice || playMusic || playVideo || playAnimation))) {
using State = Media::Player::State;
if (playVoice) {
auto state = Media::Player::mixer()->currentState(AudioMsgId::Type::Voice);
if (state.id == AudioMsgId(data, msgId) && !Media::Player::IsStoppedOrStopping(state.state)) {
if (Media::Player::IsPaused(state.state) || state.state == State::Pausing) {
Media::Player::mixer()->resume(state.id);
} else {
Media::Player::mixer()->pause(state.id);
}
} else {
auto audio = AudioMsgId(data, msgId);
Media::Player::mixer()->play(audio);
Media::Player::Updated().notify(audio);
if (App::main()) {
App::main()->mediaMarkRead(data);
}
}
} else if (playMusic) {
auto state = Media::Player::mixer()->currentState(AudioMsgId::Type::Song);
if (state.id == AudioMsgId(data, msgId) && !Media::Player::IsStoppedOrStopping(state.state)) {
if (Media::Player::IsPaused(state.state) || state.state == State::Pausing) {
Media::Player::mixer()->resume(state.id);
} else {
Media::Player::mixer()->pause(state.id);
}
} else {
auto song = AudioMsgId(data, msgId);
Media::Player::mixer()->play(song);
Media::Player::Updated().notify(song);
}
} else if (playVideo) {
if (!data->data().isEmpty()) {
Messenger::Instance().showDocument(data, context);
} else if (location.accessEnable()) {
Messenger::Instance().showDocument(data, context);
location.accessDisable();
} else {
auto filepath = location.name();
if (documentIsValidMediaFile(filepath)) {
File::Launch(filepath);
}
}
if (App::main()) App::main()->mediaMarkRead(data);
} else if (data->voice() || data->song() || data->isVideo()) {
auto filepath = location.name();
if (documentIsValidMediaFile(filepath)) {
File::Launch(filepath);
}
if (App::main()) App::main()->mediaMarkRead(data);
} else if (data->size < App::kImageSizeLimit) {
if (!data->data().isEmpty() && playAnimation) {
if (action == ActionOnLoadPlayInline && context && context->getMedia()) {
context->getMedia()->playInline();
} else {
Messenger::Instance().showDocument(data, context);
}
} else if (location.accessEnable()) {
if (data->isAnimation() || QImageReader(location.name()).canRead()) {
if (action == ActionOnLoadPlayInline && context && context->getMedia()) {
context->getMedia()->playInline();
} else {
Messenger::Instance().showDocument(data, context);
}
} else {
File::Launch(location.name());
}
location.accessDisable();
} else {
File::Launch(location.name());
}
} else {
File::Launch(location.name());
}
return;
}
if (data->status != FileReady) return;
QString filename;
if (!data->saveToCache()) {
filename = documentSaveFilename(data);
if (filename.isEmpty()) return;
}
data->save(filename, action, msgId);
}
void DocumentOpenClickHandler::onClickImpl() const {
auto item = App::hoveredLinkItem() ? App::hoveredLinkItem() : (App::contextItem() ? App::contextItem() : nullptr);
doOpen(document(), item, document()->voice() ? ActionOnLoadNone : ActionOnLoadOpen);
}
void GifOpenClickHandler::onClickImpl() const {
auto item = App::hoveredLinkItem() ? App::hoveredLinkItem() : (App::contextItem() ? App::contextItem() : nullptr);
doOpen(document(), item, ActionOnLoadPlayInline);
}
void DocumentSaveClickHandler::doSave(DocumentData *data, bool forceSavingAs) {
if (!data->date) return;
auto filepath = data->filepath(DocumentData::FilePathResolveSaveFromDataSilent, forceSavingAs);
if (!filepath.isEmpty() && !forceSavingAs) {
File::OpenWith(filepath, QCursor::pos());
} else {
auto fileinfo = QFileInfo(filepath);
auto filedir = filepath.isEmpty() ? QDir() : fileinfo.dir();
auto filename = filepath.isEmpty() ? QString() : fileinfo.fileName();
auto newfname = documentSaveFilename(data, forceSavingAs, filename, filedir);
if (!newfname.isEmpty()) {
auto action = (filename.isEmpty() || forceSavingAs) ? ActionOnLoadNone : ActionOnLoadOpenWith;
auto actionMsgId = App::hoveredLinkItem() ? App::hoveredLinkItem()->fullId() : (App::contextItem() ? App::contextItem()->fullId() : FullMsgId());
data->save(newfname, action, actionMsgId);
}
}
}
void DocumentSaveClickHandler::onClickImpl() const {
doSave(document());
}
void DocumentCancelClickHandler::onClickImpl() const {
auto data = document();
if (!data->date) return;
if (data->uploading()) {
if (auto item = App::hoveredLinkItem() ? App::hoveredLinkItem() : (App::contextItem() ? App::contextItem() : nullptr)) {
if (auto media = item->getMedia()) {
if (media->getDocument() == data) {
App::contextItem(item);
App::main()->cancelUploadLayer();
}
}
}
} else {
data->cancel();
}
}
VoiceData::~VoiceData() {
if (!waveform.isEmpty() && waveform.at(0) == -1 && waveform.size() > int32(sizeof(TaskId))) {
TaskId taskId = 0;
memcpy(&taskId, waveform.constData() + 1, sizeof(taskId));
Local::cancelTask(taskId);
}
}
DocumentData::DocumentData(DocumentId id, int32 dc, uint64 accessHash, int32 version, const QString &url, const QVector<MTPDocumentAttribute> &attributes)
: id(id)
, _dc(dc)
, _access(accessHash)
, _version(version)
, _url(url) {
setattributes(attributes);
if (_dc && _access) {
_location = Local::readFileLocation(mediaKey());
}
}
DocumentData *DocumentData::create(DocumentId id) {
return new DocumentData(id, 0, 0, 0, QString(), QVector<MTPDocumentAttribute>());
}
DocumentData *DocumentData::create(DocumentId id, int32 dc, uint64 accessHash, int32 version, const QVector<MTPDocumentAttribute> &attributes) {
return new DocumentData(id, dc, accessHash, version, QString(), attributes);
}
DocumentData *DocumentData::create(DocumentId id, const QString &url, const QVector<MTPDocumentAttribute> &attributes) {
return new DocumentData(id, 0, 0, 0, url, attributes);
}
void DocumentData::setattributes(const QVector<MTPDocumentAttribute> &attributes) {
for (int32 i = 0, l = attributes.size(); i < l; ++i) {
switch (attributes[i].type()) {
case mtpc_documentAttributeImageSize: {
auto &d = attributes[i].c_documentAttributeImageSize();
dimensions = QSize(d.vw.v, d.vh.v);
} break;
case mtpc_documentAttributeAnimated: if (type == FileDocument || type == StickerDocument || type == VideoDocument) {
type = AnimatedDocument;
_additional = nullptr;
} break;
case mtpc_documentAttributeSticker: {
auto &d = attributes[i].c_documentAttributeSticker();
if (type == FileDocument) {
type = StickerDocument;
_additional = std::make_unique<StickerData>();
}
if (sticker()) {
sticker()->alt = qs(d.valt);
if (sticker()->set.type() != mtpc_inputStickerSetID || d.vstickerset.type() == mtpc_inputStickerSetID) {
sticker()->set = d.vstickerset;
}
}
} break;
case mtpc_documentAttributeVideo: {
auto &d = attributes[i].c_documentAttributeVideo();
if (type == FileDocument) {
type = d.is_round_message() ? RoundVideoDocument : VideoDocument;
}
_duration = d.vduration.v;
dimensions = QSize(d.vw.v, d.vh.v);
} break;
case mtpc_documentAttributeAudio: {
auto &d = attributes[i].c_documentAttributeAudio();
if (type == FileDocument) {
if (d.is_voice()) {
type = VoiceDocument;
_additional = std::make_unique<VoiceData>();
} else {
type = SongDocument;
_additional = std::make_unique<SongData>();
}
}
if (voice()) {
voice()->duration = d.vduration.v;
VoiceWaveform waveform = documentWaveformDecode(qba(d.vwaveform));
uchar wavemax = 0;
for (int32 i = 0, l = waveform.size(); i < l; ++i) {
uchar waveat = waveform.at(i);
if (wavemax < waveat) wavemax = waveat;
}
voice()->waveform = waveform;
voice()->wavemax = wavemax;
} else if (song()) {
song()->duration = d.vduration.v;
song()->title = qs(d.vtitle);
song()->performer = qs(d.vperformer);
}
} break;
case mtpc_documentAttributeFilename: name = qs(attributes[i].c_documentAttributeFilename().vfile_name); break;
}
}
if (type == StickerDocument) {
if (dimensions.width() <= 0
|| dimensions.height() <= 0
|| dimensions.width() > StickerMaxSize
|| dimensions.height() > StickerMaxSize
|| !saveToCache()) {
type = FileDocument;
_additional = nullptr;
}
}
}
bool DocumentData::saveToCache() const {
return (type == StickerDocument && size < Storage::kMaxStickerInMemory)
|| (isAnimation() && size < Storage::kMaxAnimationInMemory)
|| (voice() && size < Storage::kMaxVoiceInMemory);
}
void DocumentData::forget() {
thumb->forget();
if (sticker()) sticker()->img->forget();
replyPreview->forget();
_data.clear();
}
void DocumentData::automaticLoad(const HistoryItem *item) {
if (loaded() || status != FileReady) return;
if (saveToCache() && _loader != CancelledMtpFileLoader) {
if (type == StickerDocument) {
save(QString(), _actionOnLoad, _actionOnLoadMsgId);
} else if (isAnimation()) {
bool loadFromCloud = false;
if (item) {
if (item->history()->peer->isUser()) {
loadFromCloud = !(cAutoDownloadGif() & dbiadNoPrivate);
} else {
loadFromCloud = !(cAutoDownloadGif() & dbiadNoGroups);
}
} else { // if load at least anywhere
loadFromCloud = !(cAutoDownloadGif() & dbiadNoPrivate) || !(cAutoDownloadGif() & dbiadNoGroups);
}
save(QString(), _actionOnLoad, _actionOnLoadMsgId, loadFromCloud ? LoadFromCloudOrLocal : LoadFromLocalOnly, true);
} else if (voice()) {
if (item) {
bool loadFromCloud = false;
if (item->history()->peer->isUser()) {
loadFromCloud = !(cAutoDownloadAudio() & dbiadNoPrivate);
} else {
loadFromCloud = !(cAutoDownloadAudio() & dbiadNoGroups);
}
save(QString(), _actionOnLoad, _actionOnLoadMsgId, loadFromCloud ? LoadFromCloudOrLocal : LoadFromLocalOnly, true);
}
}
}
}
void DocumentData::automaticLoadSettingsChanged() {
if (loaded() || status != FileReady || (!isAnimation() && !voice()) || !saveToCache() || _loader != CancelledMtpFileLoader) {
return;
}
_loader = nullptr;
}
void DocumentData::performActionOnLoad() {
if (_actionOnLoad == ActionOnLoadNone) return;
auto loc = location(true);
auto already = loc.name();
auto item = _actionOnLoadMsgId.msg ? App::histItemById(_actionOnLoadMsgId) : nullptr;
auto showImage = !isVideo() && (size < App::kImageSizeLimit);
auto playVoice = voice() && (_actionOnLoad == ActionOnLoadPlayInline || _actionOnLoad == ActionOnLoadOpen);
auto playMusic = tryPlaySong() && (_actionOnLoad == ActionOnLoadPlayInline || _actionOnLoad == ActionOnLoadOpen);
auto playAnimation = isAnimation() && (_actionOnLoad == ActionOnLoadPlayInline || _actionOnLoad == ActionOnLoadOpen) && showImage && item && item->getMedia();
if (auto applyTheme = isTheme()) {
if (!loc.isEmpty() && loc.accessEnable()) {
Messenger::Instance().showDocument(this, item);
loc.accessDisable();
return;
}
}
using State = Media::Player::State;
if (playVoice) {
if (loaded()) {
auto state = Media::Player::mixer()->currentState(AudioMsgId::Type::Voice);
if (state.id == AudioMsgId(this, _actionOnLoadMsgId) && !Media::Player::IsStoppedOrStopping(state.state)) {
if (Media::Player::IsPaused(state.state) || state.state == State::Pausing) {
Media::Player::mixer()->resume(state.id);
} else {
Media::Player::mixer()->pause(state.id);
}
} else if (Media::Player::IsStopped(state.state)) {
Media::Player::mixer()->play(AudioMsgId(this, _actionOnLoadMsgId));
if (App::main()) App::main()->mediaMarkRead(this);
}
}
} else if (playMusic) {
if (loaded()) {
auto state = Media::Player::mixer()->currentState(AudioMsgId::Type::Song);
if (state.id == AudioMsgId(this, _actionOnLoadMsgId) && !Media::Player::IsStoppedOrStopping(state.state)) {
if (Media::Player::IsPaused(state.state) || state.state == State::Pausing) {
Media::Player::mixer()->resume(state.id);
} else {
Media::Player::mixer()->pause(state.id);
}
} else if (Media::Player::IsStopped(state.state)) {
auto song = AudioMsgId(this, _actionOnLoadMsgId);
Media::Player::mixer()->play(song);
Media::Player::Updated().notify(song);
}
}
} else if (playAnimation) {
if (loaded()) {
if (_actionOnLoad == ActionOnLoadPlayInline && item->getMedia()) {
item->getMedia()->playInline();
} else {
Messenger::Instance().showDocument(this, item);
}
}
} else {
if (already.isEmpty()) return;
if (_actionOnLoad == ActionOnLoadOpenWith) {
File::OpenWith(already, QCursor::pos());
} else if (_actionOnLoad == ActionOnLoadOpen || _actionOnLoad == ActionOnLoadPlayInline) {
if (voice() || song() || isVideo()) {
if (documentIsValidMediaFile(already)) {
File::Launch(already);
}
if (App::main()) App::main()->mediaMarkRead(this);
} else if (loc.accessEnable()) {
if (showImage && QImageReader(loc.name()).canRead()) {
if (_actionOnLoad == ActionOnLoadPlayInline && item && item->getMedia()) {
item->getMedia()->playInline();
} else {
Messenger::Instance().showDocument(this, item);
}
} else {
File::Launch(already);
}
loc.accessDisable();
} else {
File::Launch(already);
}
}
}
_actionOnLoad = ActionOnLoadNone;
}
bool DocumentData::loaded(FilePathResolveType type) const {
if (loading() && _loader->finished()) {
if (_loader->cancelled()) {
destroyLoaderDelayed(CancelledMtpFileLoader);
} else {
auto that = const_cast<DocumentData*>(this);
that->_location = FileLocation(_loader->fileName());
that->_data = _loader->bytes();
if (that->sticker() && !_loader->imagePixmap().isNull()) {
that->sticker()->img = ImagePtr(_data, _loader->imageFormat(), _loader->imagePixmap());
}
destroyLoaderDelayed();
}
notifyLayoutChanged();
}
return !data().isEmpty() || !filepath(type).isEmpty();
}
void DocumentData::destroyLoaderDelayed(mtpFileLoader *newValue) const {
_loader->stop();
auto loader = std::unique_ptr<FileLoader>(std::exchange(_loader, newValue));
Auth().downloader().delayedDestroyLoader(std::move(loader));
}
bool DocumentData::loading() const {
return _loader && _loader != CancelledMtpFileLoader;
}
QString DocumentData::loadingFilePath() const {
return loading() ? _loader->fileName() : QString();
}
bool DocumentData::displayLoading() const {
return loading() ? (!_loader->loadingLocal() || !_loader->autoLoading()) : uploading();
}
float64 DocumentData::progress() const {
if (uploading()) {
return snap((size > 0) ? float64(uploadOffset) / size : 0., 0., 1.);
}
return loading() ? _loader->currentProgress() : (loaded() ? 1. : 0.);
}
int32 DocumentData::loadOffset() const {
return loading() ? _loader->currentOffset() : 0;
}
bool DocumentData::uploading() const {
return status == FileUploading;
}
void DocumentData::save(const QString &toFile, ActionOnLoad action, const FullMsgId &actionMsgId, LoadFromCloudSetting fromCloud, bool autoLoading) {
if (loaded(FilePathResolveChecked)) {
auto &l = location(true);
if (!toFile.isEmpty()) {
if (!_data.isEmpty()) {
QFile f(toFile);
f.open(QIODevice::WriteOnly);
f.write(_data);
f.close();
setLocation(FileLocation(toFile));
Local::writeFileLocation(mediaKey(), FileLocation(toFile));
} else if (l.accessEnable()) {
auto alreadyName = l.name();
if (alreadyName != toFile) {
QFile(toFile).remove();
QFile(alreadyName).copy(toFile);
}
l.accessDisable();
}
}
_actionOnLoad = action;
_actionOnLoadMsgId = actionMsgId;
performActionOnLoad();
return;
}
if (_loader == CancelledMtpFileLoader) _loader = nullptr;
if (_loader) {
if (!_loader->setFileName(toFile)) {
cancel(); // changes _actionOnLoad
_loader = nullptr;
}
}
_actionOnLoad = action;
_actionOnLoadMsgId = actionMsgId;
if (_loader) {
if (fromCloud == LoadFromCloudOrLocal) _loader->permitLoadFromCloud();
} else {
status = FileReady;
if (!_access && !_url.isEmpty()) {
_loader = new webFileLoader(_url, toFile, fromCloud, autoLoading);
} else {
_loader = new mtpFileLoader(_dc, id, _access, _version, locationType(), toFile, size, (saveToCache() ? LoadToCacheAsWell : LoadToFileOnly), fromCloud, autoLoading);
}
_loader->connect(_loader, SIGNAL(progress(FileLoader*)), App::main(), SLOT(documentLoadProgress(FileLoader*)));
_loader->connect(_loader, SIGNAL(failed(FileLoader*,bool)), App::main(), SLOT(documentLoadFailed(FileLoader*,bool)));
_loader->start();
}
notifyLayoutChanged();
}
void DocumentData::cancel() {
if (!loading()) return;
auto loader = std::unique_ptr<FileLoader>(std::exchange(_loader, CancelledMtpFileLoader));
loader->cancel();
loader->stop();
Auth().downloader().delayedDestroyLoader(std::move(loader));
notifyLayoutChanged();
if (auto main = App::main()) {
main->documentLoadProgress(this);
}
_actionOnLoad = ActionOnLoadNone;
}
void DocumentData::notifyLayoutChanged() const {
auto &items = App::documentItems();
for (auto item : items.value(const_cast<DocumentData*>(this))) {
Notify::historyItemLayoutChanged(item);
}
if (auto items = InlineBots::Layout::documentItems()) {
for (auto item : items->value(const_cast<DocumentData*>(this))) {
item->layoutChanged();
}
}
}
VoiceWaveform documentWaveformDecode(const QByteArray &encoded5bit) {
auto bitsCount = static_cast<int>(encoded5bit.size() * 8);
auto valuesCount = bitsCount / 5;
if (!valuesCount) {
return VoiceWaveform();
}
// Read each 5 bit of encoded5bit as 0-31 unsigned char.
// We count the index of the byte in which the desired 5-bit sequence starts.
// And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.
//
// BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.
// Because it will be an overflow (we'll access one byte after the available memory).
// We see, that only the last 5 bits could start in the last available byte and be problematic.
// So we read in a general way all the entries in a general way except the last one.
auto result = VoiceWaveform(valuesCount, 0);
auto bitsData = encoded5bit.constData();
for (auto i = 0, l = valuesCount - 1; i != l; ++i) {
auto byteIndex = (i * 5) / 8;
auto bitShift = (i * 5) % 8;
auto value = *reinterpret_cast<const uint16*>(bitsData + byteIndex);
result[i] = static_cast<char>((value >> bitShift) & 0x1F);
}
auto lastByteIndex = ((valuesCount - 1) * 5) / 8;
auto lastBitShift = ((valuesCount - 1) * 5) % 8;
auto lastValue = (lastByteIndex == encoded5bit.size() - 1)
? static_cast<uint16>(*reinterpret_cast<const uchar*>(bitsData + lastByteIndex))
: *reinterpret_cast<const uint16*>(bitsData + lastByteIndex);
result[valuesCount - 1] = static_cast<char>((lastValue >> lastBitShift) & 0x1F);
return result;
}
QByteArray documentWaveformEncode5bit(const VoiceWaveform &waveform) {
auto bitsCount = waveform.size() * 5;
auto bytesCount = (bitsCount + 7) / 8;
auto result = QByteArray(bytesCount + 1, 0);
auto bitsData = result.data();
// Write each 0-31 unsigned char as 5 bit to result.
// We reserve one extra byte to be able to dereference any of required bytes
// as a uint16 without overflowing, even the byte with index "bytesCount - 1".
for (auto i = 0, l = waveform.size(); i < l; ++i) {
auto byteIndex = (i * 5) / 8;
auto bitShift = (i * 5) % 8;
auto value = (static_cast<uint16>(waveform[i]) & 0x1F) << bitShift;
*reinterpret_cast<uint16*>(bitsData + byteIndex) |= value;
}
result.resize(bytesCount);
return result;
}
QByteArray DocumentData::data() const {
return _data;
}
const FileLocation &DocumentData::location(bool check) const {
if (check && !_location.check()) {
const_cast<DocumentData*>(this)->_location = Local::readFileLocation(mediaKey());
}
return _location;
}
void DocumentData::setLocation(const FileLocation &loc) {
if (loc.check()) {
_location = loc;
}
}
QString DocumentData::filepath(FilePathResolveType type, bool forceSavingAs) const {
bool check = (type != FilePathResolveCached);
QString result = (check && _location.name().isEmpty()) ? QString() : location(check).name();
bool saveFromData = result.isEmpty() && !data().isEmpty();
if (saveFromData) {
if (type != FilePathResolveSaveFromData && type != FilePathResolveSaveFromDataSilent) {
saveFromData = false;
} else if (type == FilePathResolveSaveFromDataSilent && (Global::AskDownloadPath() || forceSavingAs)) {
saveFromData = false;
}
}
if (saveFromData) {
QString filename = documentSaveFilename(this, forceSavingAs);
if (!filename.isEmpty()) {
QFile f(filename);
if (f.open(QIODevice::WriteOnly)) {
if (f.write(data()) == data().size()) {
f.close();
const_cast<DocumentData*>(this)->_location = FileLocation(filename);
Local::writeFileLocation(mediaKey(), _location);
result = filename;
}
}
}
}
return result;
}
ImagePtr DocumentData::makeReplyPreview() {
if (replyPreview->isNull() && !thumb->isNull()) {
if (thumb->loaded()) {
int w = thumb->width(), h = thumb->height();
if (w <= 0) w = 1;
if (h <= 0) h = 1;
auto thumbSize = (w > h) ? QSize(w * st::msgReplyBarSize.height() / h, st::msgReplyBarSize.height()) : QSize(st::msgReplyBarSize.height(), h * st::msgReplyBarSize.height() / w);
thumbSize *= cIntRetinaFactor();
auto options = Images::Option::Smooth | (isRoundVideo() ? Images::Option::Circled : Images::Option::None) | Images::Option::TransparentBackground;
auto outerSize = st::msgReplyBarSize.height();
auto image = thumb->pixNoCache(thumbSize.width(), thumbSize.height(), options, outerSize, outerSize);
replyPreview = ImagePtr(image, "PNG");
} else {
thumb->load();
}
}
return replyPreview;
}
bool fileIsImage(const QString &name, const QString &mime) {
QString lowermime = mime.toLower(), namelower = name.toLower();
if (lowermime.startsWith(qstr("image/"))) {
return true;
} else if (namelower.endsWith(qstr(".bmp"))
|| namelower.endsWith(qstr(".jpg"))
|| namelower.endsWith(qstr(".jpeg"))
|| namelower.endsWith(qstr(".gif"))
|| namelower.endsWith(qstr(".webp"))
|| namelower.endsWith(qstr(".tga"))
|| namelower.endsWith(qstr(".tiff"))
|| namelower.endsWith(qstr(".tif"))
|| namelower.endsWith(qstr(".psd"))
|| namelower.endsWith(qstr(".png"))) {
return true;
}
return false;
}
void DocumentData::recountIsImage() {
if (isAnimation() || isVideo()) {
return;
}
_duration = fileIsImage(name, mime) ? 1 : -1; // hack
}
bool DocumentData::setRemoteVersion(int32 version) {
if (_version == version) {
return false;
}
_version = version;
_location = FileLocation();
_data = QByteArray();
status = FileReady;
if (loading()) {
destroyLoaderDelayed();
}
return true;
}
void DocumentData::setRemoteLocation(int32 dc, uint64 access) {
_dc = dc;
_access = access;
if (isValid()) {
if (_location.check()) {
Local::writeFileLocation(mediaKey(), _location);
} else {
_location = Local::readFileLocation(mediaKey());
}
}
}
void DocumentData::setContentUrl(const QString &url) {
_url = url;
}
void DocumentData::collectLocalData(DocumentData *local) {
if (local == this) return;
if (!local->_data.isEmpty()) {
_data = local->_data;
if (voice()) {
if (!Local::copyAudio(local->mediaKey(), mediaKey())) {
Local::writeAudio(mediaKey(), _data);
}
} else {
if (!Local::copyStickerImage(local->mediaKey(), mediaKey())) {
Local::writeStickerImage(mediaKey(), _data);
}
}
}
if (!local->_location.isEmpty()) {
_location = local->_location;
Local::writeFileLocation(mediaKey(), _location);
}
}
DocumentData::~DocumentData() {
if (loading()) {
destroyLoaderDelayed();
}
}
QString DocumentData::composeNameString(const QString &filename, const QString &songTitle, const QString &songPerformer) {
if (songTitle.isEmpty() && songPerformer.isEmpty()) {
return filename.isEmpty() ? qsl("Unknown File") : filename;
}
if (songPerformer.isEmpty()) {
return songTitle;
}
auto trackTitle = (songTitle.isEmpty() ? qsl("Unknown Track") : songTitle);
return songPerformer + QString::fromUtf8(" \xe2\x80\x93 ") + trackTitle;
}

View File

@@ -0,0 +1,401 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#include "data/data_types.h"
inline uint64 mediaMix32To64(int32 a, int32 b) {
return (uint64(*reinterpret_cast<uint32*>(&a)) << 32)
| uint64(*reinterpret_cast<uint32*>(&b));
}
// Old method, should not be used anymore.
//inline MediaKey mediaKey(LocationType type, int32 dc, const uint64 &id) {
// return MediaKey(mediaMix32To64(type, dc), id);
//}
// New method when version was introduced, type is not relevant anymore (all files are Documents).
inline MediaKey mediaKey(
LocationType type,
int32 dc,
const uint64 &id,
int32 version) {
return (version > 0) ? MediaKey(mediaMix32To64(version, dc), id) : MediaKey(mediaMix32To64(type, dc), id);
}
inline StorageKey mediaKey(const MTPDfileLocation &location) {
return storageKey(
location.vdc_id.v,
location.vvolume_id.v,
location.vlocal_id.v);
}
struct DocumentAdditionalData {
virtual ~DocumentAdditionalData() = default;
};
struct StickerData : public DocumentAdditionalData {
ImagePtr img;
QString alt;
MTPInputStickerSet set = MTP_inputStickerSetEmpty();
bool setInstalled() const;
StorageImageLocation loc; // doc thumb location
};
struct SongData : public DocumentAdditionalData {
int32 duration = 0;
QString title, performer;
};
struct VoiceData : public DocumentAdditionalData {
~VoiceData();
int duration = 0;
VoiceWaveform waveform;
char wavemax = 0;
};
bool fileIsImage(const QString &name, const QString &mime);
namespace Serialize {
class Document;
} // namespace Serialize;
class DocumentData {
public:
static DocumentData *create(DocumentId id);
static DocumentData *create(
DocumentId id,
int32 dc,
uint64 accessHash,
int32 version,
const QVector<MTPDocumentAttribute> &attributes);
static DocumentData *create(
DocumentId id,
const QString &url,
const QVector<MTPDocumentAttribute> &attributes);
void setattributes(
const QVector<MTPDocumentAttribute> &attributes);
void automaticLoad(const HistoryItem *item); // auto load sticker or video
void automaticLoadSettingsChanged();
enum FilePathResolveType {
FilePathResolveCached,
FilePathResolveChecked,
FilePathResolveSaveFromData,
FilePathResolveSaveFromDataSilent,
};
bool loaded(
FilePathResolveType type = FilePathResolveCached) const;
bool loading() const;
QString loadingFilePath() const;
bool displayLoading() const;
void save(
const QString &toFile,
ActionOnLoad action = ActionOnLoadNone,
const FullMsgId &actionMsgId = FullMsgId(),
LoadFromCloudSetting fromCloud = LoadFromCloudOrLocal,
bool autoLoading = false);
void cancel();
float64 progress() const;
int32 loadOffset() const;
bool uploading() const;
QByteArray data() const;
const FileLocation &location(bool check = false) const;
void setLocation(const FileLocation &loc);
QString filepath(
FilePathResolveType type = FilePathResolveCached,
bool forceSavingAs = false) const;
bool saveToCache() const;
void performActionOnLoad();
void forget();
ImagePtr makeReplyPreview();
StickerData *sticker() {
return (type == StickerDocument)
? static_cast<StickerData*>(_additional.get())
: nullptr;
}
void checkSticker() {
StickerData *s = sticker();
if (!s) return;
automaticLoad(nullptr);
if (s->img->isNull() && loaded()) {
if (_data.isEmpty()) {
const FileLocation &loc(location(true));
if (loc.accessEnable()) {
s->img = ImagePtr(loc.name());
loc.accessDisable();
}
} else {
s->img = ImagePtr(_data);
}
}
}
SongData *song() {
return (type == SongDocument)
? static_cast<SongData*>(_additional.get())
: nullptr;
}
const SongData *song() const {
return const_cast<DocumentData*>(this)->song();
}
VoiceData *voice() {
return (type == VoiceDocument)
? static_cast<VoiceData*>(_additional.get())
: nullptr;
}
const VoiceData *voice() const {
return const_cast<DocumentData*>(this)->voice();
}
bool isRoundVideo() const {
return (type == RoundVideoDocument);
}
bool isAnimation() const {
return (type == AnimatedDocument)
|| isRoundVideo()
|| !mime.compare(qstr("image/gif"), Qt::CaseInsensitive);
}
bool isGifv() const {
return (type == AnimatedDocument)
&& !mime.compare(qstr("video/mp4"), Qt::CaseInsensitive);
}
bool isTheme() const {
return
name.endsWith(
qstr(".tdesktop-theme"),
Qt::CaseInsensitive)
|| name.endsWith(
qstr(".tdesktop-palette"),
Qt::CaseInsensitive);
}
bool tryPlaySong() const {
return (song() != nullptr)
|| mime.startsWith(qstr("audio/"), Qt::CaseInsensitive);
}
bool isMusic() const {
if (auto s = song()) {
return (s->duration > 0);
}
return false;
}
bool isVideo() const {
return (type == VideoDocument);
}
int32 duration() const {
return (isAnimation() || isVideo()) ? _duration : -1;
}
bool isImage() const {
return !isAnimation() && !isVideo() && (_duration > 0);
}
void recountIsImage();
void setData(const QByteArray &data) {
_data = data;
}
bool setRemoteVersion(int32 version); // Returns true if version has changed.
void setRemoteLocation(int32 dc, uint64 access);
void setContentUrl(const QString &url);
bool hasRemoteLocation() const {
return (_dc != 0 && _access != 0);
}
bool isValid() const {
return hasRemoteLocation() || !_url.isEmpty();
}
MTPInputDocument mtpInput() const {
if (_access) {
return MTP_inputDocument(
MTP_long(id),
MTP_long(_access));
}
return MTP_inputDocumentEmpty();
}
// When we have some client-side generated document
// (for example for displaying an external inline bot result)
// and it has downloaded data, we can collect that data from it
// to (this) received from the server "same" document.
void collectLocalData(DocumentData *local);
~DocumentData();
DocumentId id = 0;
DocumentType type = FileDocument;
QSize dimensions;
int32 date = 0;
QString name;
QString mime;
ImagePtr thumb, replyPreview;
int32 size = 0;
FileStatus status = FileReady;
int32 uploadOffset = 0;
int32 md5[8];
MediaKey mediaKey() const {
return ::mediaKey(locationType(), _dc, id, _version);
}
static QString composeNameString(
const QString &filename,
const QString &songTitle,
const QString &songPerformer);
QString composeNameString() const {
if (auto songData = song()) {
return composeNameString(
name,
songData->title,
songData->performer);
}
return composeNameString(name, QString(), QString());
}
private:
DocumentData(
DocumentId id,
int32 dc,
uint64 accessHash,
int32 version,
const QString &url,
const QVector<MTPDocumentAttribute> &attributes);
friend class Serialize::Document;
LocationType locationType() const {
return voice()
? AudioFileLocation
: isVideo()
? VideoFileLocation
: DocumentFileLocation;
}
// Two types of location: from MTProto by dc+access+version or from web by url
int32 _dc = 0;
uint64 _access = 0;
int32 _version = 0;
QString _url;
FileLocation _location;
QByteArray _data;
std::unique_ptr<DocumentAdditionalData> _additional;
int32 _duration = -1;
ActionOnLoad _actionOnLoad = ActionOnLoadNone;
FullMsgId _actionOnLoadMsgId;
mutable FileLoader *_loader = nullptr;
void notifyLayoutChanged() const;
void destroyLoaderDelayed(
mtpFileLoader *newValue = nullptr) const;
};
VoiceWaveform documentWaveformDecode(const QByteArray &encoded5bit);
QByteArray documentWaveformEncode5bit(const VoiceWaveform &waveform);
class DocumentClickHandler : public LeftButtonClickHandler {
public:
DocumentClickHandler(DocumentData *document)
: _document(document) {
}
DocumentData *document() const {
return _document;
}
private:
DocumentData *_document;
};
class DocumentSaveClickHandler : public DocumentClickHandler {
public:
using DocumentClickHandler::DocumentClickHandler;
static void doSave(
DocumentData *document,
bool forceSavingAs = false);
protected:
void onClickImpl() const override;
};
class DocumentOpenClickHandler : public DocumentClickHandler {
public:
using DocumentClickHandler::DocumentClickHandler;
static void doOpen(
DocumentData *document,
HistoryItem *context,
ActionOnLoad action = ActionOnLoadOpen);
protected:
void onClickImpl() const override;
};
class DocumentCancelClickHandler : public DocumentClickHandler {
public:
using DocumentClickHandler::DocumentClickHandler;
protected:
void onClickImpl() const override;
};
class GifOpenClickHandler : public DocumentOpenClickHandler {
public:
using DocumentOpenClickHandler::DocumentOpenClickHandler;
protected:
void onClickImpl() const override;
};
class VoiceSeekClickHandler : public DocumentOpenClickHandler {
public:
using DocumentOpenClickHandler::DocumentOpenClickHandler;
protected:
void onClickImpl() const override {
}
};
QString saveFileName(
const QString &title,
const QString &filter,
const QString &prefix,
QString name,
bool savingAs,
const QDir &dir = QDir());

View File

@@ -0,0 +1,87 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#include <rpl/event_stream.h>
namespace Data {
template <
typename FlagsType,
typename FlagsType::Type kEssential = -1>
class Flags {
public:
struct Change {
Change(FlagsType diff, FlagsType value)
: diff(diff)
, value(value) {
}
FlagsType diff = 0;
FlagsType value = 0;
};
Flags() = default;
Flags(FlagsType value) : _value(value) {
}
void set(FlagsType which) {
if (auto diff = which ^ _value) {
_value = which;
updated(diff);
}
}
void add(FlagsType which) {
if (auto diff = which & ~_value) {
_value |= which;
updated(diff);
}
}
void remove(FlagsType which) {
if (auto diff = which & _value) {
_value &= ~which;
updated(diff);
}
}
FlagsType current() const {
return _value;
}
rpl::producer<Change> changes() const {
return _changes.events();
}
rpl::producer<Change> value() const {
return _changes.events_starting_with({
FlagsType::from_raw(kEssential),
_value });
}
private:
void updated(FlagsType diff) {
if ((diff &= FlagsType::from_raw(kEssential))) {
_changes.fire({ diff, _value });
}
}
FlagsType _value = 0;
rpl::event_stream<Change> _changes;
};
} // namespace Data

View File

@@ -0,0 +1,59 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#include "data/data_photo.h"
#include "data/data_document.h"
struct GameData {
GameData(const GameId &id) : id(id) {
}
GameData(
const GameId &id,
const uint64 &accessHash,
const QString &shortName,
const QString &title,
const QString &description,
PhotoData *photo,
DocumentData *document)
: id(id)
, accessHash(accessHash)
, shortName(shortName)
, title(title)
, description(description)
, photo(photo)
, document(document) {
}
void forget() {
if (document) document->forget();
if (photo) photo->forget();
}
GameId id = 0;
uint64 accessHash = 0;
QString shortName;
QString title;
QString description;
PhotoData *photo = nullptr;
DocumentData *document = nullptr;
};

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,164 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "data/data_photo.h"
//#include "lang/lang_keys.h"
//#include "inline_bots/inline_bot_layout_item.h"
//#include "observer_peer.h"
#include "mainwidget.h"
//#include "application.h"
//#include "storage/file_upload.h"
//#include "mainwindow.h"
//#include "core/file_utilities.h"
//#include "apiwrap.h"
//#include "boxes/confirm_box.h"
//#include "media/media_audio.h"
//#include "storage/localstorage.h"
#include "history/history_media_types.h"
//#include "styles/style_history.h"
//#include "window/themes/window_theme.h"
//#include "auth_session.h"
#include "messenger.h"
//#include "storage/file_download.h"
PhotoData::PhotoData(const PhotoId &id, const uint64 &access, int32 date, const ImagePtr &thumb, const ImagePtr &medium, const ImagePtr &full)
: id(id)
, access(access)
, date(date)
, thumb(thumb)
, medium(medium)
, full(full) {
}
void PhotoData::automaticLoad(const HistoryItem *item) {
full->automaticLoad(item);
}
void PhotoData::automaticLoadSettingsChanged() {
full->automaticLoadSettingsChanged();
}
void PhotoData::download() {
full->loadEvenCancelled();
notifyLayoutChanged();
}
bool PhotoData::loaded() const {
bool wasLoading = loading();
if (full->loaded()) {
if (wasLoading) {
notifyLayoutChanged();
}
return true;
}
return false;
}
bool PhotoData::loading() const {
return full->loading();
}
bool PhotoData::displayLoading() const {
return full->loading() ? full->displayLoading() : uploading();
}
void PhotoData::cancel() {
full->cancel();
notifyLayoutChanged();
}
void PhotoData::notifyLayoutChanged() const {
auto &items = App::photoItems();
auto i = items.constFind(const_cast<PhotoData*>(this));
if (i != items.cend()) {
for_const (auto item, i.value()) {
Notify::historyItemLayoutChanged(item);
}
}
}
float64 PhotoData::progress() const {
if (uploading()) {
if (uploadingData->size > 0) {
return float64(uploadingData->offset) / uploadingData->size;
}
return 0;
}
return full->progress();
}
int32 PhotoData::loadOffset() const {
return full->loadOffset();
}
bool PhotoData::uploading() const {
return !!uploadingData;
}
void PhotoData::forget() {
thumb->forget();
replyPreview->forget();
medium->forget();
full->forget();
}
ImagePtr PhotoData::makeReplyPreview() {
if (replyPreview->isNull() && !thumb->isNull()) {
if (thumb->loaded()) {
int w = thumb->width(), h = thumb->height();
if (w <= 0) w = 1;
if (h <= 0) h = 1;
replyPreview = ImagePtr(w > h ? thumb->pix(w * st::msgReplyBarSize.height() / h, st::msgReplyBarSize.height()) : thumb->pix(st::msgReplyBarSize.height()), "PNG");
} else {
thumb->load();
}
}
return replyPreview;
}
void PhotoOpenClickHandler::onClickImpl() const {
Messenger::Instance().showPhoto(this, App::hoveredLinkItem() ? App::hoveredLinkItem() : App::contextItem());
}
void PhotoSaveClickHandler::onClickImpl() const {
auto data = photo();
if (!data->date) return;
data->download();
}
void PhotoCancelClickHandler::onClickImpl() const {
auto data = photo();
if (!data->date) return;
if (data->uploading()) {
if (auto item = App::hoveredLinkItem() ? App::hoveredLinkItem() : (App::contextItem() ? App::contextItem() : nullptr)) {
if (auto media = item->getMedia()) {
if (media->type() == MediaTypePhoto && static_cast<HistoryPhoto*>(media)->photo() == data) {
App::contextItem(item);
App::main()->cancelUploadLayer();
}
}
}
} else {
data->cancel();
}
}

View File

@@ -0,0 +1,118 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#include "data/data_types.h"
class PhotoData {
public:
PhotoData(
const PhotoId &id,
const uint64 &access = 0,
int32 date = 0,
const ImagePtr &thumb = ImagePtr(),
const ImagePtr &medium = ImagePtr(),
const ImagePtr &full = ImagePtr());
void automaticLoad(const HistoryItem *item);
void automaticLoadSettingsChanged();
void download();
bool loaded() const;
bool loading() const;
bool displayLoading() const;
void cancel();
float64 progress() const;
int32 loadOffset() const;
bool uploading() const;
void forget();
ImagePtr makeReplyPreview();
PhotoId id;
uint64 access;
int32 date;
ImagePtr thumb, replyPreview;
ImagePtr medium;
ImagePtr full;
PeerData *peer = nullptr; // for chat and channel photos connection
// geo, caption
struct UploadingData {
UploadingData(int size) : size(size) {
}
int offset = 0;
int size = 0;
};
std::unique_ptr<UploadingData> uploadingData;
private:
void notifyLayoutChanged() const;
};
class PhotoClickHandler : public LeftButtonClickHandler {
public:
PhotoClickHandler(
not_null<PhotoData*> photo,
PeerData *peer = nullptr)
: _photo(photo), _peer(peer) {
}
not_null<PhotoData*> photo() const {
return _photo;
}
PeerData *peer() const {
return _peer;
}
private:
not_null<PhotoData*> _photo;
PeerData *_peer;
};
class PhotoOpenClickHandler : public PhotoClickHandler {
public:
using PhotoClickHandler::PhotoClickHandler;
protected:
void onClickImpl() const override;
};
class PhotoSaveClickHandler : public PhotoClickHandler {
public:
using PhotoClickHandler::PhotoClickHandler;
protected:
void onClickImpl() const override;
};
class PhotoCancelClickHandler : public PhotoClickHandler {
public:
using PhotoClickHandler::PhotoClickHandler;
protected:
void onClickImpl() const override;
};

View File

@@ -0,0 +1,55 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "data/data_types.h"
#include "data/data_document.h"
void AudioMsgId::setTypeFromAudio() {
if (_audio->voice() || _audio->isRoundVideo()) {
_type = Type::Voice;
} else if (_audio->isVideo()) {
_type = Type::Video;
} else if (_audio->tryPlaySong()) {
_type = Type::Song;
} else {
_type = Type::Unknown;
}
}
void MessageCursor::fillFrom(const QTextEdit *edit) {
QTextCursor c = edit->textCursor();
position = c.position();
anchor = c.anchor();
QScrollBar *s = edit->verticalScrollBar();
scroll = (s && (s->value() != s->maximum()))
? s->value()
: QFIXED_MAX;
}
void MessageCursor::applyTo(QTextEdit *edit) {
auto cursor = edit->textCursor();
cursor.setPosition(anchor, QTextCursor::MoveAnchor);
cursor.setPosition(position, QTextCursor::KeepAnchor);
edit->setTextCursor(cursor);
if (auto scrollbar = edit->verticalScrollBar()) {
scrollbar->setValue(scroll);
}
}

View File

@@ -0,0 +1,390 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
class PeerData;
class UserData;
class ChatData;
class ChannelData;
using UserId = int32;
using ChatId = int32;
using ChannelId = int32;
constexpr auto NoChannel = ChannelId(0);
using PeerId = uint64;
constexpr auto PeerIdMask = PeerId(0xFFFFFFFFULL);
constexpr auto PeerIdTypeMask = PeerId(0x300000000ULL);
constexpr auto PeerIdUserShift = PeerId(0x000000000ULL);
constexpr auto PeerIdChatShift = PeerId(0x100000000ULL);
constexpr auto PeerIdChannelShift = PeerId(0x200000000ULL);
inline bool peerIsUser(const PeerId &id) {
return (id & PeerIdTypeMask) == PeerIdUserShift;
}
inline bool peerIsChat(const PeerId &id) {
return (id & PeerIdTypeMask) == PeerIdChatShift;
}
inline bool peerIsChannel(const PeerId &id) {
return (id & PeerIdTypeMask) == PeerIdChannelShift;
}
inline PeerId peerFromUser(UserId user_id) {
return PeerIdUserShift | uint64(uint32(user_id));
}
inline PeerId peerFromChat(ChatId chat_id) {
return PeerIdChatShift | uint64(uint32(chat_id));
}
inline PeerId peerFromChannel(ChannelId channel_id) {
return PeerIdChannelShift | uint64(uint32(channel_id));
}
inline PeerId peerFromUser(const MTPint &user_id) {
return peerFromUser(user_id.v);
}
inline PeerId peerFromChat(const MTPint &chat_id) {
return peerFromChat(chat_id.v);
}
inline PeerId peerFromChannel(const MTPint &channel_id) {
return peerFromChannel(channel_id.v);
}
inline int32 peerToBareInt(const PeerId &id) {
return int32(uint32(id & PeerIdMask));
}
inline UserId peerToUser(const PeerId &id) {
return peerIsUser(id) ? peerToBareInt(id) : 0;
}
inline ChatId peerToChat(const PeerId &id) {
return peerIsChat(id) ? peerToBareInt(id) : 0;
}
inline ChannelId peerToChannel(const PeerId &id) {
return peerIsChannel(id) ? peerToBareInt(id) : NoChannel;
}
inline MTPint peerToBareMTPInt(const PeerId &id) {
return MTP_int(peerToBareInt(id));
}
inline PeerId peerFromMTP(const MTPPeer &peer) {
switch (peer.type()) {
case mtpc_peerUser: return peerFromUser(peer.c_peerUser().vuser_id);
case mtpc_peerChat: return peerFromChat(peer.c_peerChat().vchat_id);
case mtpc_peerChannel: return peerFromChannel(peer.c_peerChannel().vchannel_id);
}
return 0;
}
inline MTPpeer peerToMTP(const PeerId &id) {
if (peerIsUser(id)) {
return MTP_peerUser(peerToBareMTPInt(id));
} else if (peerIsChat(id)) {
return MTP_peerChat(peerToBareMTPInt(id));
} else if (peerIsChannel(id)) {
return MTP_peerChannel(peerToBareMTPInt(id));
}
return MTP_peerUser(MTP_int(0));
}
using MsgId = int32;
constexpr auto StartClientMsgId = MsgId(-0x7FFFFFFF);
constexpr auto EndClientMsgId = MsgId(-0x40000000);
constexpr auto ShowAtTheEndMsgId = MsgId(-0x40000000);
constexpr auto SwitchAtTopMsgId = MsgId(-0x3FFFFFFF);
constexpr auto ShowAtProfileMsgId = MsgId(-0x3FFFFFFE);
constexpr auto ShowAndStartBotMsgId = MsgId(-0x3FFFFFD);
constexpr auto ShowAtGameShareMsgId = MsgId(-0x3FFFFFC);
constexpr auto ServerMaxMsgId = MsgId(0x3FFFFFFF);
constexpr auto ShowAtUnreadMsgId = MsgId(0);
constexpr inline bool IsClientMsgId(MsgId id) {
return (id >= StartClientMsgId && id < EndClientMsgId);
}
constexpr inline bool IsServerMsgId(MsgId id) {
return (id > 0 && id < ServerMaxMsgId);
}
struct MsgRange {
MsgRange() = default;
MsgRange(MsgId from, MsgId till) : from(from), till(till) {
}
MsgId from = 0;
MsgId till = 0;
};
inline bool operator==(const MsgRange &a, const MsgRange &b) {
return (a.from == b.from) && (a.till == b.till);
}
inline bool operator!=(const MsgRange &a, const MsgRange &b) {
return !(a == b);
}
struct FullMsgId {
FullMsgId() = default;
FullMsgId(ChannelId channel, MsgId msg) : channel(channel), msg(msg) {
}
explicit operator bool() const {
return msg != 0;
}
ChannelId channel = NoChannel;
MsgId msg = 0;
};
inline bool operator==(const FullMsgId &a, const FullMsgId &b) {
return (a.channel == b.channel) && (a.msg == b.msg);
}
inline bool operator!=(const FullMsgId &a, const FullMsgId &b) {
return !(a == b);
}
inline bool operator<(const FullMsgId &a, const FullMsgId &b) {
if (a.msg < b.msg) return true;
if (a.msg > b.msg) return false;
return a.channel < b.channel;
}
inline PeerId peerFromMessage(const MTPmessage &msg) {
auto compute = [](auto &message) {
auto from_id = message.has_from_id() ? peerFromUser(message.vfrom_id) : 0;
auto to_id = peerFromMTP(message.vto_id);
auto out = message.is_out();
return (out || !peerIsUser(to_id)) ? to_id : from_id;
};
switch (msg.type()) {
case mtpc_message: return compute(msg.c_message());
case mtpc_messageService: return compute(msg.c_messageService());
}
return 0;
}
inline MTPDmessage::Flags flagsFromMessage(const MTPmessage &msg) {
switch (msg.type()) {
case mtpc_message: return msg.c_message().vflags.v;
case mtpc_messageService: return mtpCastFlags(msg.c_messageService().vflags.v);
}
return 0;
}
inline MsgId idFromMessage(const MTPmessage &msg) {
switch (msg.type()) {
case mtpc_messageEmpty: return msg.c_messageEmpty().vid.v;
case mtpc_message: return msg.c_message().vid.v;
case mtpc_messageService: return msg.c_messageService().vid.v;
}
Unexpected("Type in idFromMessage()");
}
inline TimeId dateFromMessage(const MTPmessage &msg) {
switch (msg.type()) {
case mtpc_message: return msg.c_message().vdate.v;
case mtpc_messageService: return msg.c_messageService().vdate.v;
}
return 0;
}
class DocumentData;
class PhotoData;
struct WebPageData;
struct GameData;
class AudioMsgId;
class PhotoClickHandler;
class PhotoOpenClickHandler;
class PhotoSaveClickHandler;
class PhotoCancelClickHandler;
class DocumentClickHandler;
class DocumentSaveClickHandler;
class DocumentOpenClickHandler;
class DocumentCancelClickHandler;
class GifOpenClickHandler;
class VoiceSeekClickHandler;
using PhotoId = uint64;
using VideoId = uint64;
using AudioId = uint64;
using DocumentId = uint64;
using WebPageId = uint64;
using GameId = uint64;
constexpr auto CancelledWebPageId = WebPageId(0xFFFFFFFFFFFFFFFFULL);
using PreparedPhotoThumbs = QMap<char, QPixmap>;
// [0] == -1 -- counting, [0] == -2 -- could not count
using VoiceWaveform = QVector<char>;
enum ActionOnLoad {
ActionOnLoadNone,
ActionOnLoadOpen,
ActionOnLoadOpenWith,
ActionOnLoadPlayInline
};
enum LocationType {
UnknownFileLocation = 0,
// 1, 2, etc are used as "version" value in mediaKey() method.
DocumentFileLocation = 0x4e45abe9, // mtpc_inputDocumentFileLocation
AudioFileLocation = 0x74dc404d, // mtpc_inputAudioFileLocation
VideoFileLocation = 0x3d0364ec, // mtpc_inputVideoFileLocation
};
enum FileStatus {
FileDownloadFailed = -2,
FileUploadFailed = -1,
FileUploading = 0,
FileReady = 1,
};
// Don't change the values. This type is used for serialization.
enum DocumentType {
FileDocument = 0,
VideoDocument = 1,
SongDocument = 2,
StickerDocument = 3,
AnimatedDocument = 4,
VoiceDocument = 5,
RoundVideoDocument = 6,
};
using MediaKey = QPair<uint64, uint64>;
class AudioMsgId {
public:
enum class Type {
Unknown,
Voice,
Song,
Video,
};
AudioMsgId() = default;
AudioMsgId(
DocumentData *audio,
const FullMsgId &msgId,
uint32 playId = 0)
: _audio(audio)
, _contextId(msgId)
, _playId(playId) {
setTypeFromAudio();
}
Type type() const {
return _type;
}
DocumentData *audio() const {
return _audio;
}
FullMsgId contextId() const {
return _contextId;
}
uint32 playId() const {
return _playId;
}
explicit operator bool() const {
return _audio != nullptr;
}
private:
void setTypeFromAudio();
DocumentData *_audio = nullptr;
Type _type = Type::Unknown;
FullMsgId _contextId;
uint32 _playId = 0;
};
inline bool operator<(const AudioMsgId &a, const AudioMsgId &b) {
if (quintptr(a.audio()) < quintptr(b.audio())) {
return true;
} else if (quintptr(b.audio()) < quintptr(a.audio())) {
return false;
} else if (a.contextId() < b.contextId()) {
return true;
} else if (b.contextId() < a.contextId()) {
return false;
}
return (a.playId() < b.playId());
}
inline bool operator==(const AudioMsgId &a, const AudioMsgId &b) {
return (a.audio() == b.audio())
&& (a.contextId() == b.contextId())
&& (a.playId() == b.playId());
}
inline bool operator!=(const AudioMsgId &a, const AudioMsgId &b) {
return !(a == b);
}
inline MsgId clientMsgId() {
static MsgId CurrentClientMsgId = StartClientMsgId;
Assert(CurrentClientMsgId < EndClientMsgId);
return CurrentClientMsgId++;
}
struct MessageCursor {
MessageCursor() = default;
MessageCursor(int position, int anchor, int scroll)
: position(position)
, anchor(anchor)
, scroll(scroll) {
}
MessageCursor(const QTextEdit *edit) {
fillFrom(edit);
}
void fillFrom(const QTextEdit *edit);
void applyTo(QTextEdit *edit);
int position = 0;
int anchor = 0;
int scroll = QFIXED_MAX;
};
inline bool operator==(
const MessageCursor &a,
const MessageCursor &b) {
return (a.position == b.position)
&& (a.anchor == b.anchor)
&& (a.scroll == b.scroll);
}
struct SendAction {
enum class Type {
Typing,
RecordVideo,
UploadVideo,
RecordVoice,
UploadVoice,
RecordRound,
UploadRound,
UploadPhoto,
UploadFile,
ChooseLocation,
ChooseContact,
PlayGame,
};
SendAction(
Type type,
TimeMs until,
int progress = 0)
: type(type)
, until(until)
, progress(progress) {
}
Type type = Type::Typing;
TimeMs until = 0;
int progress = 0;
};

View File

@@ -0,0 +1,88 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#include "data/data_photo.h"
#include "data/data_document.h"
enum WebPageType {
WebPagePhoto,
WebPageVideo,
WebPageProfile,
WebPageArticle
};
inline WebPageType toWebPageType(const QString &type) {
if (type == qstr("photo")) return WebPagePhoto;
if (type == qstr("video")) return WebPageVideo;
if (type == qstr("profile")) return WebPageProfile;
return WebPageArticle;
}
struct WebPageData {
WebPageData(const WebPageId &id) : id(id) {
}
WebPageData(
const WebPageId &id,
WebPageType type,
const QString &url,
const QString &displayUrl,
const QString &siteName,
const QString &title,
const TextWithEntities &description,
DocumentData *document,
PhotoData *photo,
int32 duration,
const QString &author,
int32 pendingTill)
: id(id)
, type(type)
, url(url)
, displayUrl(displayUrl)
, siteName(siteName)
, title(title)
, description(description)
, duration(duration)
, author(author)
, photo(photo)
, document(document)
, pendingTill(pendingTill) {
}
void forget() {
if (document) document->forget();
if (photo) photo->forget();
}
WebPageId id = 0;
WebPageType type = WebPageArticle;
QString url;
QString displayUrl;
QString siteName;
QString title;
TextWithEntities description;
int32 duration = 0;
QString author;
PhotoData *photo = nullptr;
DocumentData *document = nullptr;
int32 pendingTill = 0;
};