From 1542311d896a2f08ed3abd3340c476486bf2cbb1 Mon Sep 17 00:00:00 2001
From: John Preston <johnprestonmail@gmail.com>
Date: Wed, 20 May 2020 16:50:15 +0400
Subject: [PATCH] Preload documents in media viewer.

---
 .../media/view/media_view_overlay_widget.cpp         | 12 +++++++-----
 .../media/view/media_view_overlay_widget.h           |  1 +
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/Telegram/SourceFiles/media/view/media_view_overlay_widget.cpp b/Telegram/SourceFiles/media/view/media_view_overlay_widget.cpp
index 6f9d83c6e..9e68a0913 100644
--- a/Telegram/SourceFiles/media/view/media_view_overlay_widget.cpp
+++ b/Telegram/SourceFiles/media/view/media_view_overlay_widget.cpp
@@ -3482,23 +3482,25 @@ void OverlayWidget::preloadData(int delta) {
 		auto entity = entityByIndex(forgetIndex);
 		if (auto photo = base::get_if<not_null<PhotoData*>>(&entity.data)) {
 			(*photo)->unload();
-		} else if (auto document = base::get_if<not_null<DocumentData*>>(&entity.data)) {
-			(*document)->unload();
 		}
 	}
 
+	auto medias = base::flat_set<std::shared_ptr<Data::DocumentMedia>>();
 	for (auto index = from; index != till; ++index) {
 		auto entity = entityByIndex(index);
 		if (auto photo = base::get_if<not_null<PhotoData*>>(&entity.data)) {
 			(*photo)->download(fileOrigin());
 		} else if (auto document = base::get_if<not_null<DocumentData*>>(
 				&entity.data)) {
+			const auto [i, ok] = medias.emplace(
+				(*document)->createMediaView());
 			(*document)->loadThumbnail(fileOrigin());
-			//if (!(*document)->canBePlayed()) { // #TODO optimize
-			//	(*document)->automaticLoad(fileOrigin(), entity.item);
-			//}
+			if (!(*i)->canBePlayed()) {
+				(*i)->automaticLoad(fileOrigin(), entity.item);
+			}
 		}
 	}
+	_preloadMedias = std::move(medias);
 }
 
 void OverlayWidget::mousePressEvent(QMouseEvent *e) {
diff --git a/Telegram/SourceFiles/media/view/media_view_overlay_widget.h b/Telegram/SourceFiles/media/view/media_view_overlay_widget.h
index a665e48ad..7308e047b 100644
--- a/Telegram/SourceFiles/media/view/media_view_overlay_widget.h
+++ b/Telegram/SourceFiles/media/view/media_view_overlay_widget.h
@@ -349,6 +349,7 @@ private:
 	PhotoData *_photo = nullptr;
 	DocumentData *_doc = nullptr;
 	std::shared_ptr<Data::DocumentMedia> _docMedia;
+	base::flat_set<std::shared_ptr<Data::DocumentMedia>> _preloadMedias;
 	int _rotation = 0;
 	std::unique_ptr<SharedMedia> _sharedMedia;
 	std::optional<SharedMediaWithLastSlice> _sharedMediaData;