-
Notifications
You must be signed in to change notification settings - Fork 7.2k
Expand file tree
/
Copy pathdata_cloud_themes.cpp
More file actions
896 lines (840 loc) · 25.6 KB
/
Copy pathdata_cloud_themes.cpp
File metadata and controls
896 lines (840 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
/*
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 "data/data_cloud_themes.h"
#include "api/api_premium.h"
#include "window/themes/window_theme.h"
#include "window/themes/window_themes_chat.h"
#include "window/themes/window_theme_preview.h"
#include "window/themes/window_theme_editor_box.h"
#include "window/window_controller.h"
#include "window/window_session_controller.h"
#include "data/data_session.h"
#include "data/data_document.h"
#include "data/data_file_origin.h"
#include "data/data_document_media.h"
#include "main/main_session.h"
#include "ui/boxes/confirm_box.h"
#include "media/view/media_view_open_common.h"
#include "lang/lang_keys.h"
#include "apiwrap.h"
namespace Data {
namespace {
constexpr auto kFirstReloadTimeout = 10 * crl::time(1000);
constexpr auto kReloadTimeout = 3600 * crl::time(1000);
constexpr auto kGiftThemesLimit = 24;
[[nodiscard]] bool SamePaper(
const std::optional<WallPaper> &was,
const std::optional<WallPaper> &now) {
return (was.has_value() == now.has_value())
&& (!was || was->key() == now->key());
}
[[nodiscard]] bool SameThemeSettings(
const base::flat_map<CloudThemeType, CloudTheme::Settings> &was,
const base::flat_map<CloudThemeType, CloudTheme::Settings> &now) {
if (was.size() != now.size()) {
return false;
}
for (const auto &[type, settings] : was) {
const auto i = now.find(type);
if (i == end(now)) {
return false;
}
const auto &other = i->second;
if (settings.accentColor != other.accentColor
|| settings.outgoingAccentColor != other.outgoingAccentColor
|| (settings.outgoingMessagesColors
!= other.outgoingMessagesColors)
|| !SamePaper(settings.paper, other.paper)) {
return false;
}
}
return true;
}
bool IsTestingColors/* = false*/;
[[nodiscard]] Window::SessionController *ChatThemeWindow(
not_null<Main::Session*> session) {
const auto &windows = session->windows();
if (windows.empty()) {
return nullptr;
}
const auto primary = ranges::find_if(windows, [](
not_null<Window::SessionController*> window) {
return window->isPrimary();
});
return (primary != end(windows)) ? *primary : windows.front();
}
} // namespace
CloudTheme CloudTheme::Parse(
not_null<Main::Session*> session,
const MTPDtheme &data,
bool parseSettings) {
const auto document = data.vdocument();
const auto paper = [&](const MTPThemeSettings &settings) {
const auto &data = settings.data();
return data.vwallpaper()
? WallPaper::Create(session, *data.vwallpaper())
: std::nullopt;
};
const auto outgoingMessagesColors = [&](
const MTPThemeSettings &settings) {
auto result = std::vector<QColor>();
const auto &data = settings.data();
if (const auto colors = data.vmessage_colors()) {
for (const auto &color : colors->v) {
result.push_back(Ui::ColorFromSerialized(color));
}
}
return result;
};
const auto accentColor = [&](const MTPThemeSettings &settings) {
const auto &data = settings.data();
return Ui::ColorFromSerialized(data.vaccent_color());
};
const auto outgoingAccentColor = [&](const MTPThemeSettings &settings) {
const auto &data = settings.data();
return Ui::MaybeColorFromSerialized(data.voutbox_accent_color());
};
const auto basedOnDark = [&](const MTPThemeSettings &settings) {
const auto &data = settings.data();
return data.vbase_theme().match([](const MTPDbaseThemeNight &) {
return true;
}, [](const MTPDbaseThemeTinted &) {
return true;
}, [](const auto &) {
return false;
});
};
const auto settings = [&] {
auto result = base::flat_map<Type, Settings>();
const auto settings = data.vsettings();
if (!settings) {
return result;
}
for (const auto &fields : settings->v) {
const auto type = basedOnDark(fields) ? Type::Dark : Type::Light;
result.emplace(type, Settings{
.paper = paper(fields),
.accentColor = accentColor(fields),
.outgoingAccentColor = outgoingAccentColor(fields),
.outgoingMessagesColors = outgoingMessagesColors(fields),
});
}
return result;
};
return {
.id = data.vid().v,
.accessHash = data.vaccess_hash().v,
.slug = qs(data.vslug()),
.title = qs(data.vtitle()),
.documentId = (document
? session->data().processDocument(*document)->id
: DocumentId(0)),
.createdBy = data.is_creator() ? session->userId() : UserId(0),
.usersCount = data.vinstalls_count().value_or_empty(),
.emoticon = qs(data.vemoticon().value_or_empty()),
.settings = (parseSettings
? settings()
: base::flat_map<Type, Settings>()),
};
}
CloudTheme CloudTheme::Parse(
not_null<Main::Session*> session,
const MTPDchatThemeUniqueGift &data,
bool parseSettings) {
const auto gift = Api::FromTL(session, data.vgift());
if (!gift || !gift->unique) {
return {};
}
const auto paper = [&](const MTPThemeSettings &settings) {
const auto &data = settings.data();
return data.vwallpaper()
? WallPaper::Create(session, *data.vwallpaper())
: std::nullopt;
};
const auto basedOnDark = [&](const MTPThemeSettings &settings) {
const auto &data = settings.data();
return data.vbase_theme().match([](const MTPDbaseThemeNight &) {
return true;
}, [](const MTPDbaseThemeTinted &) {
return true;
}, [](const auto &) {
return false;
});
};
const auto outgoingMessagesColors = [&](
const MTPThemeSettings &settings) {
auto result = std::vector<QColor>();
const auto &data = settings.data();
if (const auto colors = data.vmessage_colors()) {
for (const auto &color : colors->v) {
result.push_back(Ui::ColorFromSerialized(color));
}
//} else if (basedOnDark(settings)) {
// result.push_back(gift->unique->backdrop.edgeColor);
//} else {
// result.push_back(anim::color(
// gift->unique->backdrop.patternColor,
// QColor(255, 255, 255, 255),
// 0.75));
}
return result;
};
const auto accentColor = [&](const MTPThemeSettings &settings) {
const auto &data = settings.data();
return Ui::ColorFromSerialized(data.vaccent_color());
};
const auto outgoingAccentColor = [&](const MTPThemeSettings &settings) {
const auto &data = settings.data();
return Ui::MaybeColorFromSerialized(
data.voutbox_accent_color()
);// .value_or(gift->unique->backdrop.patternColor);
};
const auto settings = [&] {
auto result = base::flat_map<Type, Settings>();
for (const auto &fields : data.vtheme_settings().v) {
const auto type = basedOnDark(fields) ? Type::Dark : Type::Light;
result.emplace(type, Settings{
.paper = paper(fields),
.accentColor = accentColor(fields),
.outgoingAccentColor = outgoingAccentColor(fields),
.outgoingMessagesColors = outgoingMessagesColors(fields),
});
}
return result;
};
return {
.id = gift->unique->id,
.unique = gift->unique,
.settings = (parseSettings
? settings()
: base::flat_map<Type, Settings>()),
};
}
CloudTheme CloudTheme::Parse(
not_null<Main::Session*> session,
const MTPTheme &data,
bool parseSettings) {
return data.match([&](const MTPDtheme &data) {
return CloudTheme::Parse(session, data, parseSettings);
});
}
QString CloudThemes::Format() {
static const auto kResult = QString::fromLatin1("tdesktop");
return kResult;
}
CloudThemes::CloudThemes(not_null<Main::Session*> session)
: _session(session)
, _reloadCurrentTimer([=] { reloadCurrent(); }) {
setupReload();
}
void CloudThemes::setupReload() {
using namespace Window::Theme;
if (needReload()) {
_reloadCurrentTimer.callOnce(kFirstReloadTimeout);
} else if (!Background()->themeObject().cloud.emoticon.isEmpty()) {
_reloadCurrentTimer.callOnce(kFirstReloadTimeout);
}
Background()->updates(
) | rpl::filter([](const BackgroundUpdate &update) {
return (update.type == BackgroundUpdate::Type::ApplyingTheme);
}) | rpl::map([=] {
return needReload();
}) | rpl::on_next([=](bool need) {
install();
if (need) {
scheduleReload();
} else {
_reloadCurrentTimer.cancel();
}
}, _lifetime);
}
bool CloudThemes::needReload() const {
const auto &fields = Window::Theme::Background()->themeObject().cloud;
return fields.id && fields.documentId;
}
void CloudThemes::install() {
using namespace Window::Theme;
const auto &fields = Background()->themeObject().cloud;
auto &themeId = IsNightMode()
? _installedNightThemeId
: _installedDayThemeId;
const auto cloudId = (fields.documentId || !fields.emoticon.isEmpty())
? fields.id
: uint64(0);
if (themeId == cloudId) {
return;
}
themeId = cloudId;
using Flag = MTPaccount_InstallTheme::Flag;
const auto flags = (IsNightMode() ? Flag::f_dark : Flag(0))
| Flag::f_format
| (themeId ? Flag::f_theme : Flag(0));
_session->api().request(MTPaccount_InstallTheme(
MTP_flags(flags),
MTP_inputTheme(MTP_long(cloudId), MTP_long(fields.accessHash)),
MTP_string(Format()),
MTPBaseTheme()
)).send();
}
void CloudThemes::reloadCurrent() {
if (!needReload()) {
const auto &cloud = Window::Theme::Background()->themeObject().cloud;
if (!cloud.emoticon.isEmpty() && !cloud.settings.empty()) {
refreshChatThemes();
}
return;
}
const auto &fields = Window::Theme::Background()->themeObject().cloud;
_session->api().request(MTPaccount_GetTheme(
MTP_string(Format()),
MTP_inputTheme(MTP_long(fields.id), MTP_long(fields.accessHash))
)).done([=](const MTPTheme &result) {
applyUpdate(result);
}).fail([=] {
_reloadCurrentTimer.callOnce(kReloadTimeout);
}).send();
}
void CloudThemes::applyUpdate(const MTPTheme &theme) {
theme.match([&](const MTPDtheme &data) {
const auto cloud = CloudTheme::Parse(_session, data, true);
const auto &object = Window::Theme::Background()->themeObject();
if (cloud.id != object.cloud.id) {
return;
} else if (cloud.documentId
&& (cloud.documentId != object.cloud.documentId)) {
applyFromDocument(cloud);
return;
} else if (cloud.settings.empty()) {
return;
}
auto updated = object;
updated.cloud = cloud;
Window::Theme::Background()->setThemeObject(updated);
if (const auto controller = ChatThemeWindow(_session)) {
Window::Theme::CheckChatThemeWallPaper(controller);
}
});
scheduleReload();
}
void CloudThemes::resolve(
not_null<Window::Controller*> controller,
const QString &slug,
const FullMsgId &clickFromMessageId) {
_session->api().request(_resolveRequestId).cancel();
_resolveRequestId = _session->api().request(MTPaccount_GetTheme(
MTP_string(Format()),
MTP_inputThemeSlug(MTP_string(slug))
)).done([=](const MTPTheme &result) {
showPreview(controller, result);
}).fail([=](const MTP::Error &error) {
if (error.type() == u"THEME_FORMAT_INVALID"_q) {
controller->show(Ui::MakeInformBox(tr::lng_theme_no_desktop()));
}
}).send();
}
void CloudThemes::showPreview(
not_null<Window::Controller*> controller,
const MTPTheme &data) {
data.match([&](const MTPDtheme &data) {
showPreview(controller, CloudTheme::Parse(_session, data, true));
});
}
void CloudThemes::showPreview(
not_null<Window::Controller*> controller,
const CloudTheme &cloud) {
if (cloud.documentId) {
previewFromDocument(controller, cloud);
} else if (cloud.createdBy == _session->userId()) {
controller->show(Box(
Window::Theme::CreateForExistingBox,
controller,
cloud));
} else if (!cloud.settings.empty()) {
const auto session = controller->sessionController();
if (!session) {
return;
}
const auto weak = base::make_weak(session);
controller->show(Ui::MakeConfirmBox({
.text = (cloud.title.isEmpty()
? tr::lng_chat_theme_apply()
: rpl::single(cloud.title)),
.confirmed = [=](Fn<void()> close) {
if (const auto strong = weak.get()) {
Window::Theme::ApplyChatTheme(
strong,
cloud,
Window::Theme::IsNightMode());
}
close();
},
.confirmText = tr::lng_chat_theme_apply(),
}));
} else {
controller->show(Ui::MakeInformBox(tr::lng_theme_no_desktop()));
}
}
void CloudThemes::applyFromDocument(const CloudTheme &cloud) {
const auto document = _session->data().document(cloud.documentId);
loadDocumentAndInvoke(_updatingFrom, cloud, document, [=](
std::shared_ptr<Data::DocumentMedia> media) {
const auto document = media->owner();
auto preview = Window::Theme::PreviewFromFile(
media->bytes(),
document->location().name(),
cloud);
if (preview) {
Window::Theme::Apply(std::move(preview));
Window::Theme::KeepApplied();
}
});
}
void CloudThemes::previewFromDocument(
not_null<Window::Controller*> controller,
const CloudTheme &cloud) {
const auto sessionController = controller->sessionController();
if (!sessionController) {
return;
}
const auto document = _session->data().document(cloud.documentId);
loadDocumentAndInvoke(_previewFrom, cloud, document, [=](
std::shared_ptr<Data::DocumentMedia> media) {
const auto document = media->owner();
using Open = Media::View::OpenRequest;
controller->openInMediaView(Open(sessionController, document, cloud));
});
}
void CloudThemes::loadDocumentAndInvoke(
LoadingDocument &value,
const CloudTheme &cloud,
not_null<DocumentData*> document,
Fn<void(std::shared_ptr<Data::DocumentMedia>)> callback) {
const auto alreadyWaiting = (value.document != nullptr);
if (alreadyWaiting) {
value.document->cancel();
}
value.document = document;
value.documentMedia = document->createMediaView();
value.document->save(
Data::FileOriginTheme(cloud.id, cloud.accessHash),
QString());
value.callback = std::move(callback);
if (value.documentMedia->loaded()) {
invokeForLoaded(value);
return;
}
if (!alreadyWaiting) {
_session->downloaderTaskFinished(
) | rpl::filter([=, &value] {
return value.documentMedia->loaded();
}) | rpl::on_next([=, &value] {
invokeForLoaded(value);
}, value.subscription);
}
}
void CloudThemes::invokeForLoaded(LoadingDocument &value) {
const auto onstack = std::move(value.callback);
auto media = std::move(value.documentMedia);
value = LoadingDocument();
onstack(std::move(media));
}
void CloudThemes::scheduleReload() {
if (needReload()) {
_reloadCurrentTimer.callOnce(kReloadTimeout);
} else {
_reloadCurrentTimer.cancel();
}
}
void CloudThemes::refresh() {
if (_refreshRequestId) {
return;
}
_refreshRequestId = _session->api().request(MTPaccount_GetThemes(
MTP_string(Format()),
MTP_long(_hash)
)).done([=](const MTPaccount_Themes &result) {
_refreshRequestId = 0;
result.match([&](const MTPDaccount_themes &data) {
_hash = data.vhash().v;
parseThemes(data.vthemes().v);
_updates.fire({});
}, [](const MTPDaccount_themesNotModified &) {
});
}).fail([=] {
_refreshRequestId = 0;
}).send();
}
void CloudThemes::parseThemes(const QVector<MTPTheme> &list) {
_list.clear();
_list.reserve(list.size());
for (const auto &theme : list) {
_list.push_back(CloudTheme::Parse(_session, theme, true));
}
checkCurrentTheme();
}
void CloudThemes::refreshChatThemes() {
if (_chatThemesRequestId) {
return;
}
_chatThemesRequestId = _session->api().request(MTPaccount_GetChatThemes(
MTP_long(_chatThemesHash)
)).done([=](const MTPaccount_Themes &result) {
_chatThemesRequestId = 0;
result.match([&](const MTPDaccount_themes &data) {
_chatThemesHash = data.vhash().v;
parseChatThemes(data.vthemes().v);
_chatThemesUpdates.fire({});
checkAppliedChatTheme();
}, [](const MTPDaccount_themesNotModified &) {
});
}).fail([=] {
_chatThemesRequestId = 0;
}).send();
}
const std::vector<CloudTheme> &CloudThemes::chatThemes() const {
return _chatThemes;
}
rpl::producer<> CloudThemes::chatThemesUpdated() const {
return _chatThemesUpdates.events();
}
std::optional<CloudTheme> CloudThemes::themeForToken(
const QString &token) const {
if (token.startsWith(u"gift:"_q)) {
const auto id = QStringView(token).mid(5).toULongLong();
const auto i = _giftThemes.find(id);
return (i != end(_giftThemes))
? i->second
: std::optional<CloudTheme>();
}
const auto emoji = Ui::Emoji::Find(token);
if (!emoji) {
return {};
}
const auto i = ranges::find(_chatThemes, emoji, [](const CloudTheme &v) {
return Ui::Emoji::Find(v.emoticon);
});
return (i != end(_chatThemes)) ? std::make_optional(*i) : std::nullopt;
}
rpl::producer<std::optional<CloudTheme>> CloudThemes::themeForTokenValue(
const QString &token) {
if (token.startsWith(u"gift:"_q)) {
return rpl::single(themeForToken(token));
}
const auto testing = TestingColors();
if (!Ui::Emoji::Find(token)) {
return rpl::single<std::optional<CloudTheme>>(std::nullopt);
} else if (auto result = themeForToken(token)) {
if (testing) {
return rpl::single(
std::move(result)
) | rpl::then(chatThemesUpdated(
) | rpl::map([=] {
return themeForToken(token);
}) | rpl::filter([](const std::optional<CloudTheme> &theme) {
return theme.has_value();
}));
}
return rpl::single(std::move(result));
}
refreshChatThemes();
const auto limit = testing ? (1 << 20) : 1;
return rpl::single<std::optional<CloudTheme>>(
std::nullopt
) | rpl::then(chatThemesUpdated(
) | rpl::map([=] {
return themeForToken(token);
}) | rpl::filter([](const std::optional<CloudTheme> &theme) {
return theme.has_value();
}) | rpl::take(limit));
}
void CloudThemes::myGiftThemesLoadMore(bool reload) {
if (reload && !_myGiftThemesTokens.empty()) {
_session->api().request(base::take(_myGiftThemesRequestId)).cancel();
}
if (_myGiftThemesRequestId || (!reload && _myGiftThemesLoaded)) {
return;
}
_myGiftThemesRequestId = _session->api().request(
MTPaccount_GetUniqueGiftChatThemes(
MTP_string(reload ? QString() : _myGiftThemesNextOffset),
MTP_int(kGiftThemesLimit),
MTP_long(_myGiftThemesHash))
).done([=](const MTPaccount_ChatThemes &result) {
_myGiftThemesRequestId = 0;
result.match([&](const MTPDaccount_chatThemes &data) {
if (reload || _myGiftThemesTokens.empty()) {
_myGiftThemesHash = data.vhash().v;
_myGiftThemesTokens.clear();
_myGiftThemesLoaded = false;
}
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
const auto &list = data.vthemes().v;
const auto got = int(list.size());
_myGiftThemesTokens.reserve(_myGiftThemesTokens.size() + got);
for (const auto &theme : list) {
theme.match([](const MTPDchatTheme &) {
}, [&](const MTPDchatThemeUniqueGift &data) {
_myGiftThemesTokens.push_back(
processGiftThemeGetToken(data));
});
}
if (const auto next = data.vnext_offset()) {
_myGiftThemesNextOffset = qs(*next);
} else {
_myGiftThemesLoaded = true;
}
_myGiftThemesUpdates.fire({});
}, [&](const MTPDaccount_chatThemesNotModified &) {
if (!reload) {
_myGiftThemesLoaded = true;
_myGiftThemesUpdates.fire({});
}
});
}).fail([=] {
_myGiftThemesRequestId = 0;
_myGiftThemesLoaded = true;
}).send();
}
const std::vector<QString> &CloudThemes::myGiftThemesTokens() const {
return _myGiftThemesTokens;
}
bool CloudThemes::myGiftThemesReady() const {
return !_myGiftThemesTokens.empty() || _myGiftThemesLoaded;
}
rpl::producer<> CloudThemes::myGiftThemesUpdated() const {
return _myGiftThemesUpdates.events();
}
QString CloudThemes::processGiftThemeGetToken(
const MTPDchatThemeUniqueGift &data) {
auto parsed = CloudTheme::Parse(_session, data, true);
if (parsed.unique) {
const auto id = parsed.unique->id;
_giftThemes[id] = std::move(parsed);
return u"gift:%1"_q.arg(id);
}
return QString();
}
void CloudThemes::refreshChatThemesFor(const QString &token) {
if (token.startsWith(u"gift:"_q)) {
return;
}
refreshChatThemes();
}
bool CloudThemes::TestingColors() {
return IsTestingColors;
}
void CloudThemes::SetTestingColors(bool testing) {
IsTestingColors = testing;
}
QString CloudThemes::prepareTestingLink(const CloudTheme &theme) const {
const auto hex = [](int value) {
return QChar((value < 10) ? ('0' + value) : ('a' + (value - 10)));
};
const auto hex2 = [&](int value) {
return QString() + hex(value / 16) + hex(value % 16);
};
const auto color = [&](const QColor &color) {
return hex2(color.red()) + hex2(color.green()) + hex2(color.blue());
};
const auto colors = [&](const std::vector<QColor> &colors) {
auto list = QStringList();
for (const auto &c : colors) {
list.push_back(color(c));
}
return list.join(",");
};
auto arguments = QStringList();
for (const auto &[type, settings] : theme.settings) {
const auto add = [&, type = type](const QString &value) {
const auto prefix = (type == CloudTheme::Type::Dark)
? u"dark_"_q
: u""_q;
arguments.push_back(prefix + value);
};
add("accent=" + color(settings.accentColor));
if (settings.paper && !settings.paper->backgroundColors().empty()) {
add("bg=" + colors(settings.paper->backgroundColors()));
}
if (settings.paper/* && settings.paper->hasShareUrl()*/) {
add("intensity="
+ QString::number(settings.paper->patternIntensity()));
//const auto url = settings.paper->shareUrl(_session);
//const auto from = url.indexOf("bg/");
//const auto till = url.indexOf("?");
//if (from > 0 && till > from) {
// add("slug=" + url.mid(from + 3, till - from - 3));
//}
}
if (settings.outgoingAccentColor) {
add("out_accent" + color(*settings.outgoingAccentColor));
}
if (!settings.outgoingMessagesColors.empty()) {
add("out_bg=" + colors(settings.outgoingMessagesColors));
}
}
return arguments.isEmpty()
? QString()
: ("tg://test_chat_theme?" + arguments.join("&"));
}
std::optional<CloudTheme> CloudThemes::updateThemeFromLink(
const QString &emoticon,
const QMap<QString, QString> ¶ms) {
const auto emoji = Ui::Emoji::Find(emoticon);
if (!TestingColors() || !emoji) {
return std::nullopt;
}
const auto i = ranges::find(_chatThemes, emoji, [](const CloudTheme &v) {
return Ui::Emoji::Find(v.emoticon);
});
if (i == end(_chatThemes)) {
return std::nullopt;
}
const auto hex = [](const QString &value) {
return (value.size() != 1)
? std::nullopt
: (value[0] >= 'a' && value[0] <= 'f')
? std::make_optional(10 + int(value[0].unicode() - 'a'))
: (value[0] >= 'A' && value[0] <= 'F')
? std::make_optional(10 + int(value[0].unicode() - 'A'))
: (value[0] >= '0' && value[0] <= '9')
? std::make_optional(int(value[0].unicode() - '0'))
: std::nullopt;
};
const auto hex2 = [&](const QString &value) {
const auto first = hex(value.mid(0, 1));
const auto second = hex(value.mid(1, 1));
return (first && second)
? std::make_optional((*first) * 16 + (*second))
: std::nullopt;
};
const auto color = [&](const QString &value) {
const auto red = hex2(value.mid(0, 2));
const auto green = hex2(value.mid(2, 2));
const auto blue = hex2(value.mid(4, 2));
return (red && green && blue)
? std::make_optional(QColor(*red, *green, *blue))
: std::nullopt;
};
const auto colors = [&](const QString &value) {
auto list = value.split(",");
auto result = std::vector<QColor>();
for (const auto &single : list) {
if (const auto c = color(single)) {
result.push_back(*c);
} else {
return std::vector<QColor>();
}
}
return (result.size() > 4) ? std::vector<QColor>() : result;
};
const auto parse = [&](CloudThemeType type, const QString &prefix = {}) {
const auto accent = color(params["accent"]);
if (!accent) {
return;
}
auto &settings = i->settings[type];
settings.accentColor = *accent;
const auto bg = colors(params["bg"]);
settings.paper = (settings.paper && !bg.empty())
? std::make_optional(settings.paper->withBackgroundColors(bg))
: settings.paper;
settings.paper = (settings.paper && params["intensity"].toInt())
? std::make_optional(
settings.paper->withPatternIntensity(
params["intensity"].toInt()))
: settings.paper;
settings.outgoingAccentColor = color(params["out_accent"]);
settings.outgoingMessagesColors = colors(params["out_bg"]);
};
if (params.contains("dark_accent")) {
parse(CloudThemeType::Dark, "dark_");
}
if (params.contains("accent")) {
parse(params["dark"].isEmpty()
? CloudThemeType::Light
: CloudThemeType::Dark);
}
_chatThemesUpdates.fire({});
return *i;
}
void CloudThemes::parseChatThemes(const QVector<MTPTheme> &list) {
_chatThemes.clear();
_chatThemes.reserve(list.size());
for (const auto &theme : list) {
_chatThemes.push_back(CloudTheme::Parse(_session, theme, true));
}
}
void CloudThemes::checkCurrentTheme() {
const auto &object = Window::Theme::Background()->themeObject();
if (!object.cloud.id || !object.cloud.documentId) {
return;
}
const auto i = ranges::find(_list, object.cloud.id, &CloudTheme::id);
if (i == end(_list)) {
install();
}
}
void CloudThemes::checkAppliedChatTheme() {
using namespace Window::Theme;
const auto &object = Background()->themeObject();
const auto &cloud = object.cloud;
if (cloud.emoticon.isEmpty() || cloud.settings.empty()) {
return;
}
const auto fresh = themeForToken(cloud.emoticon);
if (!fresh) {
return;
}
const auto controller = ChatThemeWindow(_session);
if (!controller) {
return;
}
if (!SameThemeSettings(cloud.settings, fresh->settings)) {
ApplyChatTheme(
controller,
*fresh,
IsNightMode(),
ChatThemeOwnsPaper(cloud));
return;
}
auto updated = object;
updated.cloud = *fresh;
Background()->setThemeObject(updated);
CheckChatThemeWallPaper(controller);
}
rpl::producer<> CloudThemes::updated() const {
return _updates.events();
}
const std::vector<CloudTheme> &CloudThemes::list() const {
return _list;
}
void CloudThemes::savedFromEditor(const CloudTheme &theme) {
const auto i = ranges::find(_list, theme.id, &CloudTheme::id);
if (i != end(_list)) {
*i = theme;
_updates.fire({});
} else {
_list.insert(begin(_list), theme);
_updates.fire({});
}
}
void CloudThemes::remove(uint64 cloudThemeId) {
const auto i = ranges::find(_list, cloudThemeId, &CloudTheme::id);
if (i == end(_list)) {
return;
}
_session->api().request(MTPaccount_SaveTheme(
MTP_inputTheme(
MTP_long(i->id),
MTP_long(i->accessHash)),
MTP_bool(true)
)).send();
_list.erase(i);
_updates.fire({});
}
} // namespace Data