File: settings_chat.cpp

package info (click to toggle)
telegram-desktop 4.6.5%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 53,300 kB
  • sloc: cpp: 605,857; python: 3,978; ansic: 1,636; sh: 965; makefile: 841; objc: 652; javascript: 187; xml: 165
file content (1730 lines) | stat: -rw-r--r-- 48,342 bytes parent folder | download
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
/*
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 "settings/settings_chat.h"

#include "settings/settings_common.h"
#include "settings/settings_advanced.h"
#include "boxes/connection_box.h"
#include "boxes/auto_download_box.h"
#include "boxes/reactions_settings_box.h"
#include "boxes/stickers_box.h"
#include "ui/boxes/confirm_box.h"
#include "boxes/background_box.h"
#include "boxes/background_preview_box.h"
#include "boxes/download_path_box.h"
#include "boxes/local_storage_box.h"
#include "ui/wrap/vertical_layout.h"
#include "ui/wrap/slide_wrap.h"
#include "ui/widgets/input_fields.h"
#include "ui/widgets/checkbox.h"
#include "ui/widgets/color_editor.h"
#include "ui/widgets/buttons.h"
#include "ui/widgets/labels.h"
#include "ui/chat/attach/attach_extensions.h"
#include "ui/chat/chat_theme.h"
#include "ui/layers/generic_box.h"
#include "ui/effects/radial_animation.h"
#include "ui/style/style_palette_colorizer.h"
#include "ui/toast/toast.h"
#include "ui/image/image.h"
#include "ui/painter.h"
#include "ui/ui_utility.h"
#include "history/view/history_view_quick_action.h"
#include "lang/lang_keys.h"
#include "export/export_manager.h"
#include "window/themes/window_theme.h"
#include "window/themes/window_themes_embedded.h"
#include "window/themes/window_theme_editor_box.h"
#include "window/themes/window_themes_cloud_list.h"
#include "window/window_adaptive.h"
#include "window/window_session_controller.h"
#include "window/window_controller.h"
#include "info/downloads/info_downloads_widget.h"
#include "info/info_memento.h"
#include "storage/localstorage.h"
#include "core/file_utilities.h"
#include "core/application.h"
#include "data/data_session.h"
#include "data/data_cloud_themes.h"
#include "data/data_file_origin.h"
#include "data/data_message_reactions.h"
#include "data/data_peer_values.h"
#include "chat_helpers/emoji_sets_manager.h"
#include "base/platform/base_platform_info.h"
#include "platform/platform_specific.h"
#include "base/call_delayed.h"
#include "support/support_common.h"
#include "support/support_templates.h"
#include "main/main_session.h"
#include "main/main_session_settings.h"
#include "mainwidget.h"
#include "mainwindow.h"
#include "styles/style_chat_helpers.h" // stickersRemove
#include "styles/style_settings.h"
#include "styles/style_layers.h"
#include "styles/style_window.h"

namespace Settings {
namespace {

const auto kSchemesList = Window::Theme::EmbeddedThemes();
constexpr auto kCustomColorButtonParts = 7;

class ColorsPalette final {
public:
	using Type = Window::Theme::EmbeddedType;
	using Scheme = Window::Theme::EmbeddedScheme;

	explicit ColorsPalette(not_null<Ui::VerticalLayout*> container);

	void show(Type type);

	rpl::producer<QColor> selected() const;

private:
	class Button {
	public:
		Button(
			not_null<QWidget*> parent,
			std::vector<QColor> &&colors,
			bool selected);

		void moveToLeft(int x, int y);
		void update(std::vector<QColor> &&colors, bool selected);
		rpl::producer<> clicks() const;
		bool selected() const;
		QColor color() const;

	private:
		void paint();

		Ui::AbstractButton _widget;
		std::vector<QColor> _colors;
		Ui::Animations::Simple _selectedAnimation;
		bool _selected = false;

	};

	void show(
		not_null<const Scheme*> scheme,
		std::vector<QColor> &&colors,
		int selected);
	void selectCustom(not_null<const Scheme*> scheme);
	void updateInnerGeometry();

	not_null<Ui::SlideWrap<>*> _outer;
	std::vector<std::unique_ptr<Button>> _buttons;

	rpl::event_stream<QColor> _selected;

};

void PaintCustomButton(QPainter &p, const std::vector<QColor> &colors) {
	Expects(colors.size() >= kCustomColorButtonParts);

	p.setPen(Qt::NoPen);

	const auto size = st::settingsAccentColorSize;
	const auto smallSize = size / 8.;
	const auto drawAround = [&](QPointF center, int index) {
		const auto where = QPointF{
			size * (1. + center.x()) / 2,
			size * (1. + center.y()) / 2
		};
		p.setBrush(colors[index]);
		p.drawEllipse(
			where.x() - smallSize,
			where.y() - smallSize,
			2 * smallSize,
			2 * smallSize);
	};
	drawAround(QPointF(), 0);
	for (auto i = 0; i != 6; ++i) {
		const auto angle = i * M_PI / 3.;
		const auto point = QPointF{ cos(angle), sin(angle) };
		const auto adjusted = point * (1. - (2 * smallSize / size));
		drawAround(adjusted, i + 1);
	}

}

ColorsPalette::Button::Button(
	not_null<QWidget*> parent,
	std::vector<QColor> &&colors,
	bool selected)
: _widget(parent.get())
, _colors(std::move(colors))
, _selected(selected) {
	_widget.show();
	_widget.resize(st::settingsAccentColorSize, st::settingsAccentColorSize);
	_widget.paintRequest(
	) | rpl::start_with_next([=] {
		paint();
	}, _widget.lifetime());
}

void ColorsPalette::Button::moveToLeft(int x, int y) {
	_widget.moveToLeft(x, y);
}

void ColorsPalette::Button::update(
		std::vector<QColor> &&colors,
		bool selected) {
	if (_colors != colors) {
		_colors = std::move(colors);
		_widget.update();
	}
	if (_selected != selected) {
		_selected = selected;
		_selectedAnimation.start(
			[=] { _widget.update(); },
			_selected ? 0. : 1.,
			_selected ? 1. : 0.,
			st::defaultRadio.duration * 2);
	}
}

rpl::producer<> ColorsPalette::Button::clicks() const {
	return _widget.clicks() | rpl::to_empty;
}

bool ColorsPalette::Button::selected() const {
	return _selected;
}

QColor ColorsPalette::Button::color() const {
	Expects(_colors.size() == 1);

	return _colors.front();
}

void ColorsPalette::Button::paint() {
	auto p = QPainter(&_widget);
	PainterHighQualityEnabler hq(p);

	if (_colors.size() == 1) {
		PaintRoundColorButton(
			p,
			st::settingsAccentColorSize,
			_colors.front(),
			_selectedAnimation.value(_selected ? 1. : 0.));
	} else if (_colors.size() >= kCustomColorButtonParts) {
		PaintCustomButton(p, _colors);
	}
}

ColorsPalette::ColorsPalette(not_null<Ui::VerticalLayout*> container)
: _outer(container->add(
	object_ptr<Ui::SlideWrap<>>(
		container,
		object_ptr<Ui::RpWidget>(container)))) {
	_outer->hide(anim::type::instant);

	const auto inner = _outer->entity();
	inner->widthValue(
	) | rpl::start_with_next([=] {
		updateInnerGeometry();
	}, inner->lifetime());
}

void ColorsPalette::show(Type type) {
	const auto scheme = ranges::find(kSchemesList, type, &Scheme::type);
	if (scheme == end(kSchemesList)) {
		_outer->hide(anim::type::instant);
		return;
	}
	auto list = Window::Theme::DefaultAccentColors(type);
	if (list.empty()) {
		_outer->hide(anim::type::instant);
		return;
	}
	list.insert(list.begin(), scheme->accentColor);
	const auto color = Core::App().settings().themesAccentColors().get(type);
	const auto current = color.value_or(scheme->accentColor);
	const auto i = ranges::find(list, current);
	if (i == end(list)) {
		list.back() = current;
	}
	const auto selected = std::clamp(
		int(i - begin(list)),
		0,
		int(list.size()) - 1);

	_outer->show(anim::type::instant);

	show(&*scheme, std::move(list), selected);

	const auto inner = _outer->entity();
	inner->resize(_outer->width(), inner->height());
	updateInnerGeometry();
}

void ColorsPalette::show(
		not_null<const Scheme*> scheme,
		std::vector<QColor> &&colors,
		int selected) {
	Expects(selected >= 0 && selected < colors.size());

	while (_buttons.size() > colors.size()) {
		_buttons.pop_back();
	}

	auto index = 0;
	const auto inner = _outer->entity();
	const auto pushButton = [&](std::vector<QColor> &&colors) {
		auto result = rpl::producer<>();
		const auto chosen = (index == selected);
		if (_buttons.size() > index) {
			_buttons[index]->update(std::move(colors), chosen);
		} else {
			_buttons.push_back(std::make_unique<Button>(
				inner,
				std::move(colors),
				chosen));
			result = _buttons.back()->clicks();
		}
		++index;
		return result;
	};
	for (const auto &color : colors) {
		auto clicks = pushButton({ color });
		if (clicks) {
			std::move(
				clicks
			) | rpl::map([=] {
				return _buttons[index - 1]->color();
			}) | rpl::start_with_next([=](QColor color) {
				_selected.fire_copy(color);
			}, inner->lifetime());
		}
	}

	auto clicks = pushButton(std::move(colors));
	if (clicks) {
		std::move(
			clicks
		) | rpl::start_with_next([=] {
			selectCustom(scheme);
		}, inner->lifetime());
	}
}

void ColorsPalette::selectCustom(not_null<const Scheme*> scheme) {
	const auto selected = ranges::find(_buttons, true, &Button::selected);
	Assert(selected != end(_buttons));

	const auto colorizer = Window::Theme::ColorizerFrom(
		*scheme,
		scheme->accentColor);
	Ui::show(Box([=](not_null<Ui::GenericBox*> box) {
		const auto editor = box->addRow(object_ptr<ColorEditor>(
			box,
			ColorEditor::Mode::HSL,
			(*selected)->color()));

		const auto save = crl::guard(_outer, [=] {
			_selected.fire_copy(editor->color());
			box->closeBox();
		});
		editor->submitRequests(
		) | rpl::start_with_next(save, editor->lifetime());
		editor->setLightnessLimits(
			colorizer.lightnessMin,
			colorizer.lightnessMax);

		box->setFocusCallback([=] {
			editor->setInnerFocus();
		});
		box->addButton(tr::lng_settings_save(), save);
		box->addButton(tr::lng_cancel(), [=] { box->closeBox(); });
		box->setTitle(tr::lng_settings_theme_accent_title());
		box->setWidth(editor->width());
	}));
}

rpl::producer<QColor> ColorsPalette::selected() const {
	return _selected.events();
}

void ColorsPalette::updateInnerGeometry() {
	if (_buttons.size() < 2) {
		return;
	}
	const auto inner = _outer->entity();
	const auto size = st::settingsAccentColorSize;
	const auto padding = st::settingsButtonNoIcon.padding;
	const auto width = inner->width() - padding.left() - padding.right();
	const auto skip = (width - size * _buttons.size())
		/ float64(_buttons.size() - 1);
	const auto y = st::settingsSectionSkip * 2;
	auto x = float64(padding.left());
	for (const auto &button : _buttons) {
		button->moveToLeft(int(base::SafeRound(x)), y);
		x += size + skip;
	}
	inner->resize(inner->width(), y + size);
}

} // namespace

void PaintRoundColorButton(
		QPainter &p,
		int size,
		QBrush brush,
		float64 selected) {
	const auto rect = QRect(0, 0, size, size);

	p.setBrush(brush);
	p.setPen(Qt::NoPen);
	p.drawEllipse(rect);

	if (selected > 0.) {
		const auto startSkip = -st::settingsAccentColorLine / 2.;
		const auto endSkip = float64(st::settingsAccentColorSkip);
		const auto skip = startSkip + (endSkip - startSkip) * selected;
		auto pen = st::boxBg->p;
		pen.setWidth(st::settingsAccentColorLine);
		p.setBrush(Qt::NoBrush);
		p.setPen(pen);
		p.setOpacity(selected);
		p.drawEllipse(QRectF(rect).marginsRemoved({ skip, skip, skip, skip }));
	}
}

class BackgroundRow : public Ui::RpWidget {
public:
	BackgroundRow(
		QWidget *parent,
		not_null<Window::SessionController*> controller);

protected:
	void paintEvent(QPaintEvent *e) override;

	int resizeGetHeight(int newWidth) override;

private:
	void updateImage();

	float64 radialProgress() const;
	bool radialLoading() const;
	QRect radialRect() const;
	void radialStart();
	crl::time radialTimeShift() const;
	void radialAnimationCallback(crl::time now);

	const not_null<Window::SessionController*> _controller;
	QPixmap _background;
	object_ptr<Ui::LinkButton> _chooseFromGallery;
	object_ptr<Ui::LinkButton> _chooseFromFile;

	Ui::RadialAnimation _radial;

};

void ChooseFromFile(
	not_null<Window::SessionController*> controller,
	not_null<QWidget*> parent);

BackgroundRow::BackgroundRow(
	QWidget *parent,
	not_null<Window::SessionController*> controller)
: RpWidget(parent)
, _controller(controller)
, _chooseFromGallery(
	this,
	tr::lng_settings_bg_from_gallery(tr::now),
	st::settingsLink)
, _chooseFromFile(this, tr::lng_settings_bg_from_file(tr::now), st::settingsLink)
, _radial([=](crl::time now) { radialAnimationCallback(now); }) {
	updateImage();

	_chooseFromGallery->addClickHandler([=] {
		controller->show(Box<BackgroundBox>(controller));
	});
	_chooseFromFile->addClickHandler([=] {
		ChooseFromFile(controller, this);
	});

	using Update = const Window::Theme::BackgroundUpdate;
	Window::Theme::Background()->updates(
	) | rpl::filter([](const Update &update) {
		return (update.type == Update::Type::New
			|| update.type == Update::Type::Start
			|| update.type == Update::Type::Changed);
	}) | rpl::start_with_next([=] {
		updateImage();
	}, lifetime());
}

void BackgroundRow::paintEvent(QPaintEvent *e) {
	auto p = QPainter(this);

	const auto radial = _radial.animating();
	const auto radialOpacity = radial ? _radial.opacity() : 0.;
	if (radial) {
		const auto backThumb = _controller->content()->newBackgroundThumb();
		if (!backThumb) {
			p.drawPixmap(0, 0, _background);
		} else {
			const auto &pix = backThumb->pix(
				st::settingsBackgroundThumb,
				{ .options = Images::Option::Blur });
			const auto factor = cIntRetinaFactor();
			p.drawPixmap(
				0,
				0,
				st::settingsBackgroundThumb,
				st::settingsBackgroundThumb,
				pix,
				0,
				(pix.height() - st::settingsBackgroundThumb * factor) / 2,
				st::settingsBackgroundThumb * factor,
				st::settingsBackgroundThumb * factor);
		}

		const auto outer = radialRect();
		const auto inner = QRect(
			QPoint(
				outer.x() + (outer.width() - st::radialSize.width()) / 2,
				outer.y() + (outer.height() - st::radialSize.height()) / 2),
			st::radialSize);
		p.setPen(Qt::NoPen);
		p.setOpacity(radialOpacity);
		p.setBrush(st::radialBg);

		{
			PainterHighQualityEnabler hq(p);
			p.drawEllipse(inner);
		}

		p.setOpacity(1);
		const auto arc = inner.marginsRemoved(QMargins(
			st::radialLine,
			st::radialLine,
			st::radialLine,
			st::radialLine));
		_radial.draw(p, arc, st::radialLine, st::radialFg);
	} else {
		p.drawPixmap(0, 0, _background);
	}
}

int BackgroundRow::resizeGetHeight(int newWidth) {
	auto linkTop = st::settingsFromGalleryTop;
	auto linkLeft = st::settingsBackgroundThumb + st::settingsThumbSkip;
	auto linkWidth = newWidth - linkLeft;
	_chooseFromGallery->resizeToWidth(
		qMin(linkWidth, _chooseFromGallery->naturalWidth()));
	_chooseFromFile->resizeToWidth(
		qMin(linkWidth, _chooseFromFile->naturalWidth()));
	_chooseFromGallery->moveToLeft(linkLeft, linkTop, newWidth);
	linkTop += _chooseFromGallery->height() + st::settingsFromFileTop;
	_chooseFromFile->moveToLeft(linkLeft, linkTop, newWidth);
	return st::settingsBackgroundThumb;
}

float64 BackgroundRow::radialProgress() const {
	return _controller->content()->chatBackgroundProgress();
}

bool BackgroundRow::radialLoading() const {
	const auto widget = _controller->content();
	if (widget->chatBackgroundLoading()) {
		widget->checkChatBackground();
		if (widget->chatBackgroundLoading()) {
			return true;
		} else {
			const_cast<BackgroundRow*>(this)->updateImage();
		}
	}
	return false;
}

QRect BackgroundRow::radialRect() const {
	return QRect(
		0,
		0,
		st::settingsBackgroundThumb,
		st::settingsBackgroundThumb);
}

void BackgroundRow::radialStart() {
	if (radialLoading() && !_radial.animating()) {
		_radial.start(radialProgress());
		if (const auto shift = radialTimeShift()) {
			_radial.update(
				radialProgress(),
				!radialLoading(),
				crl::now() + shift);
		}
	}
}

crl::time BackgroundRow::radialTimeShift() const {
	return st::radialDuration;
}

void BackgroundRow::radialAnimationCallback(crl::time now) {
	const auto updated = _radial.update(
		radialProgress(),
		!radialLoading(),
		now + radialTimeShift());
	if (!anim::Disabled() || updated) {
		rtlupdate(radialRect());
	}
}

void BackgroundRow::updateImage() {
	const auto size = st::settingsBackgroundThumb;
	const auto fullsize = size * cIntRetinaFactor();

	const auto &background = *Window::Theme::Background();
	const auto &paper = background.paper();
	const auto &prepared = background.prepared();
	const auto preparePattern = [&] {
		const auto paintPattern = [&](QPainter &p, bool inverted) {
			if (prepared.isNull()) {
				return;
			}
			const auto w = prepared.width();
			const auto h = prepared.height();
			const auto s = [&] {
				const auto scaledw = w * st::windowMinHeight / h;
				const auto result = (w * size) / scaledw;
				return std::min({ result, w, h });
			}();
			auto small = prepared.copy((w - s) / 2, (h - s) / 2, s, s);
			if (inverted) {
				small = Ui::InvertPatternImage(std::move(small));
			}
			p.drawImage(QRect(0, 0, fullsize, fullsize), small);
		};
		return Ui::GenerateBackgroundImage(
			{ fullsize, fullsize },
			paper.backgroundColors(),
			paper.gradientRotation(),
			paper.patternOpacity(),
			paintPattern);
	};
	const auto prepareNormal = [&] {
		auto result = QImage(
			QSize{ fullsize, fullsize },
			QImage::Format_ARGB32_Premultiplied);
		result.setDevicePixelRatio(cRetinaFactor());
		if (const auto color = background.colorForFill()) {
			result.fill(*color);
			return result;
		} else if (prepared.isNull()) {
			result.fill(Qt::transparent);
			return result;
		}
		auto p = QPainter(&result);
		PainterHighQualityEnabler hq(p);
		const auto w = prepared.width();
		const auto h = prepared.height();
		const auto s = std::min(w, h);
		p.drawImage(
			QRect(0, 0, size, size),
			prepared,
			QRect((w - s) / 2, (h - s) / 2, s, s));
		p.end();
		return result;
	};
	auto back = (paper.isPattern() || !background.gradientForFill().isNull())
		? preparePattern()
		: prepareNormal();
	_background = Ui::PixmapFromImage(
		Images::Round(std::move(back), ImageRoundRadius::Small));
	_background.setDevicePixelRatio(cRetinaFactor());

	rtlupdate(radialRect());

	if (radialLoading()) {
		radialStart();
	}
}

void ChooseFromFile(
		not_null<Window::SessionController*> controller,
		not_null<QWidget*> parent) {
	auto filters = QStringList(
		u"Theme files (*.tdesktop-theme *.tdesktop-palette *"_q
		+ Ui::ImageExtensions().join(u" *"_q)
		+ u")"_q);
	filters.push_back(FileDialog::AllFilesFilter());
	const auto callback = crl::guard(controller, [=](
			const FileDialog::OpenResult &result) {
		if (result.paths.isEmpty() && result.remoteContent.isEmpty()) {
			return;
		}

		if (!result.paths.isEmpty()) {
			const auto filePath = result.paths.front();
			const auto hasExtension = [&](QLatin1String extension) {
				return filePath.endsWith(extension, Qt::CaseInsensitive);
			};
			if (hasExtension(qstr(".tdesktop-theme"))
				|| hasExtension(qstr(".tdesktop-palette"))) {
				Window::Theme::Apply(filePath);
				return;
			}
		}

		auto image = Images::Read({
			.path = result.paths.isEmpty() ? QString() : result.paths.front(),
			.content = result.remoteContent,
			.forceOpaque = true,
		}).image;
		if (image.isNull() || image.width() <= 0 || image.height() <= 0) {
			return;
		}
		auto local = Data::CustomWallPaper();
		local.setLocalImageAsThumbnail(std::make_shared<Image>(
			std::move(image)));
		controller->show(Box<BackgroundPreviewBox>(controller, local));
	});
	FileDialog::GetOpenPath(
		parent.get(),
		tr::lng_choose_image(tr::now),
		filters.join(u";;"_q),
		crl::guard(parent, callback));
}

void SetupStickersEmoji(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	AddDivider(container);
	AddSkip(container);

	AddSubsectionTitle(container, tr::lng_settings_stickers_emoji());

	const auto session = &controller->session();

	auto wrap = object_ptr<Ui::VerticalLayout>(container);
	const auto inner = wrap.data();
	container->add(object_ptr<Ui::OverrideMargins>(
		container,
		std::move(wrap),
		QMargins(0, 0, 0, st::settingsCheckbox.margin.bottom())));

	const auto checkbox = [&](const QString &label, bool checked) {
		return object_ptr<Ui::Checkbox>(
			container,
			label,
			checked,
			st::settingsCheckbox);
	};
	const auto add = [&](const QString &label, bool checked, auto &&handle) {
		inner->add(
			checkbox(label, checked),
			st::settingsCheckboxPadding
		)->checkedChanges(
		) | rpl::start_with_next(
			std::move(handle),
			inner->lifetime());
	};
	const auto addSliding = [&](
			const QString &label,
			bool checked,
			auto &&handle,
			rpl::producer<bool> shown) {
		inner->add(
			object_ptr<Ui::SlideWrap<Ui::Checkbox>>(
				inner,
				checkbox(label, checked),
				st::settingsCheckboxPadding)
		)->setDuration(0)->toggleOn(std::move(shown))->entity()->checkedChanges(
		) | rpl::start_with_next(
			std::move(handle),
			inner->lifetime());
	};

	add(
		tr::lng_settings_large_emoji(tr::now),
		Core::App().settings().largeEmoji(),
		[=](bool checked) {
			Core::App().settings().setLargeEmoji(checked);
			Core::App().saveSettingsDelayed();
		});

	add(
		tr::lng_settings_replace_emojis(tr::now),
		Core::App().settings().replaceEmoji(),
		[=](bool checked) {
			Core::App().settings().setReplaceEmoji(checked);
			Core::App().saveSettingsDelayed();
		});

	const auto suggestEmoji = inner->lifetime().make_state<
		rpl::variable<bool>
	>(Core::App().settings().suggestEmoji());
	add(
		tr::lng_settings_suggest_emoji(tr::now),
		Core::App().settings().suggestEmoji(),
		[=](bool checked) {
			*suggestEmoji = checked;
			Core::App().settings().setSuggestEmoji(checked);
			Core::App().saveSettingsDelayed();
		});

	using namespace rpl::mappers;
	addSliding(
		tr::lng_settings_suggest_animated_emoji(tr::now),
		Core::App().settings().suggestAnimatedEmoji(),
		[=](bool checked) {
			Core::App().settings().setSuggestAnimatedEmoji(checked);
			Core::App().saveSettingsDelayed();
		},
		rpl::combine(
			Data::AmPremiumValue(session),
			suggestEmoji->value(),
			_1 && _2));

	add(
		tr::lng_settings_suggest_by_emoji(tr::now),
		Core::App().settings().suggestStickersByEmoji(),
		[=](bool checked) {
			Core::App().settings().setSuggestStickersByEmoji(checked);
			Core::App().saveSettingsDelayed();
		});

	add(
		tr::lng_settings_loop_stickers(tr::now),
		Core::App().settings().loopAnimatedStickers(),
		[=](bool checked) {
			Core::App().settings().setLoopAnimatedStickers(checked);
			Core::App().saveSettingsDelayed();
		});

	AddButton(
		container,
		tr::lng_stickers_you_have(),
		st::settingsButton,
		{ &st::settingsIconStickers, kIconLightOrange }
	)->addClickHandler([=] {
		controller->show(
			Box<StickersBox>(controller, StickersBox::Section::Installed));
	});

	AddButton(
		container,
		tr::lng_emoji_manage_sets(),
		st::settingsButton,
		{ &st::settingsIconEmoji, kIconDarkOrange }
	)->addClickHandler([=] {
		controller->show(Box<Ui::Emoji::ManageSetsBox>(session));
	});

	AddSkip(container, st::settingsCheckboxesSkip);
}

void SetupMessages(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	AddDivider(container);
	AddSkip(container);

	AddSubsectionTitle(container, tr::lng_settings_messages());

	AddSkip(container, st::settingsSendTypeSkip);

	using SendByType = Ui::InputSubmitSettings;
	using Quick = HistoryView::DoubleClickQuickAction;

	const auto skip = st::settingsSendTypeSkip;
	auto wrap = object_ptr<Ui::VerticalLayout>(container);
	const auto inner = wrap.data();
	container->add(
		object_ptr<Ui::OverrideMargins>(
			container,
			std::move(wrap),
			QMargins(0, skip, 0, skip)));

	const auto groupSend = std::make_shared<Ui::RadioenumGroup<SendByType>>(
		Core::App().settings().sendSubmitWay());
	const auto addSend = [&](SendByType value, const QString &text) {
		inner->add(
			object_ptr<Ui::Radioenum<SendByType>>(
				inner,
				groupSend,
				value,
				text,
				st::settingsSendType),
			st::settingsSendTypePadding);
	};
	addSend(SendByType::Enter, tr::lng_settings_send_enter(tr::now));
	addSend(
		SendByType::CtrlEnter,
		(Platform::IsMac()
			? tr::lng_settings_send_cmdenter(tr::now)
			: tr::lng_settings_send_ctrlenter(tr::now)));

	groupSend->setChangedCallback([=](SendByType value) {
		Core::App().settings().setSendSubmitWay(value);
		Core::App().saveSettingsDelayed();
		controller->content()->ctrlEnterSubmitUpdated();
	});

	AddSkip(inner, st::settingsCheckboxesSkip);

	const auto groupQuick = std::make_shared<Ui::RadioenumGroup<Quick>>(
		Core::App().settings().chatQuickAction());
	const auto addQuick = [&](Quick value, const QString &text) {
		return inner->add(
			object_ptr<Ui::Radioenum<Quick>>(
				inner,
				groupQuick,
				value,
				text,
				st::settingsSendType),
			st::settingsSendTypePadding);
	};
	addQuick(Quick::Reply, tr::lng_settings_chat_quick_action_reply(tr::now));
	const auto react = addQuick(
		Quick::React,
		tr::lng_settings_chat_quick_action_react(tr::now));

	class EmptyButton final : public Ui::IconButton {
	public:
		EmptyButton(not_null<Ui::RpWidget*> p, const style::IconButton &st)
		: Ui::IconButton(p, st)
		, _rippleAreaPosition(st.rippleAreaPosition) {
		}
	protected:
		void paintEvent(QPaintEvent *e) override {
			auto p = QPainter(this);

			paintRipple(p, _rippleAreaPosition, nullptr);
		}
	private:
		const QPoint _rippleAreaPosition;
	};
	const auto buttonRight = Ui::CreateChild<EmptyButton>(
		inner,
		st::stickersRemove);
	const auto toggleButtonRight = [=](bool value) {
		buttonRight->setAttribute(Qt::WA_TransparentForMouseEvents, !value);
	};
	toggleButtonRight(false);

	struct State {
		struct {
			std::vector<rpl::lifetime> lifetimes;
			bool flag = false;
		} icons;
	};
	const auto state = buttonRight->lifetime().make_state<State>();
	state->icons.lifetimes = std::vector<rpl::lifetime>(2);

	const auto &reactions = controller->session().data().reactions();
	auto idValue = rpl::single(
		reactions.favoriteId()
	) | rpl::then(
		reactions.favoriteUpdates() | rpl::map([=] {
			return controller->session().data().reactions().favoriteId();
		})
	) | rpl::filter([](const Data::ReactionId &id) {
		return !id.empty();
	});
	auto selected = rpl::duplicate(idValue);
	std::move(
		selected
	) | rpl::start_with_next([=, idValue = std::move(idValue)](
			const Data::ReactionId &id) {
		const auto index = state->icons.flag ? 1 : 0;
		const auto iconSize = st::settingsReactionRightIcon;
		const auto &reactions = controller->session().data().reactions();
		const auto &list = reactions.list(Data::Reactions::Type::All);
		const auto i = ranges::find(list, id, &Data::Reaction::id);
		state->icons.lifetimes[index] = rpl::lifetime();
		if (i != end(list)) {
			AddReactionAnimatedIcon(
				inner,
				buttonRight->geometryValue(
				) | rpl::map([=](const QRect &r) {
					return QPoint(
						r.left() + (r.width() - iconSize) / 2,
						r.top() + (r.height() - iconSize) / 2);
				}),
				iconSize,
				*i,
				buttonRight->events(
				) | rpl::filter([=](not_null<QEvent*> event) {
					return event->type() == QEvent::Enter;
				}) | rpl::to_empty,
				rpl::duplicate(idValue) | rpl::skip(1) | rpl::to_empty,
				&state->icons.lifetimes[index]);
		} else if (const auto customId = id.custom()) {
			AddReactionCustomIcon(
				inner,
				buttonRight->geometryValue(
				) | rpl::map([=](const QRect &r) {
					return QPoint(
						r.left() + (r.width() - iconSize) / 2,
						r.top() + (r.height() - iconSize) / 2);
				}),
				iconSize,
				controller,
				customId,
				rpl::duplicate(idValue) | rpl::skip(1) | rpl::to_empty,
				&state->icons.lifetimes[index]);
		}
		state->icons.flag = !state->icons.flag;
		toggleButtonRight(true);
	}, buttonRight->lifetime());

	react->geometryValue(
	) | rpl::start_with_next([=](const QRect &r) {
		const auto rightSize = buttonRight->size();
		buttonRight->moveToRight(
			st::settingsButtonRightSkip,
			r.y() + (r.height() - rightSize.height()) / 2);
	}, buttonRight->lifetime());

	groupQuick->setChangedCallback([=](Quick value) {
		Core::App().settings().setChatQuickAction(value);
		Core::App().saveSettingsDelayed();
	});

	buttonRight->setClickedCallback([=, show = Window::Show(controller)] {
		show.showBox(Box(ReactionsSettingsBox, controller));
	});

	AddSkip(inner, st::settingsSendTypeSkip);

	inner->add(
		object_ptr<Ui::Checkbox>(
			inner,
			tr::lng_settings_chat_corner_reaction(tr::now),
			Core::App().settings().cornerReaction(),
			st::settingsCheckbox),
		st::settingsCheckboxPadding
	)->checkedChanges(
	) | rpl::start_with_next([=](bool checked) {
		Core::App().settings().setCornerReaction(checked);
		Core::App().saveSettingsDelayed();
	}, inner->lifetime());

	AddSkip(inner, st::settingsCheckboxesSkip);
}

void SetupExport(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	AddButton(
		container,
		tr::lng_settings_export_data(),
		st::settingsButtonNoIcon
	)->addClickHandler([=] {
		const auto session = &controller->session();
		controller->window().hideSettingsAndLayer();
		base::call_delayed(
			st::boxDuration,
			session,
			[=] { Core::App().exportManager().start(session); });
	});
}

void SetupLocalStorage(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	AddButton(
		container,
		tr::lng_settings_manage_local_storage(),
		st::settingsButton,
		{ &st::settingsIconGeneral, kIconLightOrange }
	)->addClickHandler([=] {
		LocalStorageBox::Show(&controller->session());
	});
}

void SetupDataStorage(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	using namespace rpl::mappers;

	AddSkip(container);

	AddSubsectionTitle(container, tr::lng_settings_data_storage());

	SetupConnectionType(
		&controller->window(),
		&controller->session().account(),
		container);

#ifndef OS_WIN_STORE
	const auto showpath = container->lifetime(
	).make_state<rpl::event_stream<bool>>();

	const auto path = container->add(
		object_ptr<Ui::SlideWrap<Button>>(
			container,
			CreateButton(
				container,
				tr::lng_download_path(),
				st::settingsButton,
				{ &st::settingsIconFolders, kIconLightBlue })));
	auto pathtext = Core::App().settings().downloadPathValue(
	) | rpl::map([](const QString &text) {
		if (text.isEmpty()) {
			return Core::App().canReadDefaultDownloadPath(true)
				? tr::lng_download_path_default(tr::now)
				: tr::lng_download_path_temp(tr::now);
		} else if (text == FileDialog::Tmp()) {
			return tr::lng_download_path_temp(tr::now);
		}
		return QDir::toNativeSeparators(text);
	});
	CreateRightLabel(
		path->entity(),
		std::move(pathtext),
		st::settingsButton,
		tr::lng_download_path());
	path->entity()->addClickHandler([=] {
		controller->show(Box<DownloadPathBox>(controller));
	});
#endif // OS_WIN_STORE

	SetupLocalStorage(controller, container);

	AddButton(
		container,
		tr::lng_downloads_section(),
		st::settingsButton,
		{ &st::settingsIconDownload, kIconPurple }
	)->setClickedCallback([=] {
		controller->showSection(
			Info::Downloads::Make(controller->session().user()));
	});

	const auto ask = AddButton(
		container,
		tr::lng_download_path_ask(),
		st::settingsButtonNoIcon
	)->toggleOn(rpl::single(Core::App().settings().askDownloadPath()));

	ask->toggledValue(
	) | rpl::filter([](bool checked) {
		return (checked != Core::App().settings().askDownloadPath());
	}) | rpl::start_with_next([=](bool checked) {
		Core::App().settings().setAskDownloadPath(checked);
		Core::App().saveSettingsDelayed();

#ifndef OS_WIN_STORE
		showpath->fire_copy(!checked);
#endif // OS_WIN_STORE

	}, ask->lifetime());

#ifndef OS_WIN_STORE
	path->toggleOn(ask->toggledValue() | rpl::map(!_1));
#endif // OS_WIN_STORE

	AddSkip(container, st::settingsCheckboxesSkip);
}

void SetupAutoDownload(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	AddDivider(container);
	AddSkip(container);

	AddSubsectionTitle(container, tr::lng_media_auto_settings());

	using Source = Data::AutoDownload::Source;
	const auto add = [&](
		rpl::producer<QString> label,
		Source source,
		IconDescriptor &&descriptor) {
		AddButton(
			container,
			std::move(label),
			st::settingsButton,
			std::move(descriptor)
		)->addClickHandler([=] {
			controller->show(
				Box<AutoDownloadBox>(&controller->session(), source));
		});
	};
	add(
		tr::lng_media_auto_in_private(),
		Source::User,
		{ &st::settingsIconUser, kIconLightBlue });
	add(
		tr::lng_media_auto_in_groups(),
		Source::Group,
		{ &st::settingsIconGroup, kIconGreen });
	add(
		tr::lng_media_auto_in_channels(),
		Source::Channel,
		{ &st::settingsIconChannel, kIconLightOrange });

	AddSkip(container, st::settingsCheckboxesSkip);
}

void SetupChatBackground(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	AddDivider(container);
	AddSkip(container);

	AddSubsectionTitle(container, tr::lng_settings_section_background());

	container->add(
		object_ptr<BackgroundRow>(container, controller),
		st::settingsBackgroundPadding);

	const auto skipTop = st::settingsCheckbox.margin.top();
	const auto skipBottom = st::settingsCheckbox.margin.bottom();
	auto wrap = object_ptr<Ui::VerticalLayout>(container);
	const auto inner = wrap.data();
	container->add(
		object_ptr<Ui::OverrideMargins>(
			container,
			std::move(wrap),
			QMargins(0, skipTop, 0, skipBottom)));

	AddSkip(container, st::settingsTileSkip);

	const auto background = Window::Theme::Background();
	const auto tile = inner->add(
		object_ptr<Ui::SlideWrap<Ui::Checkbox>>(
			inner,
			object_ptr<Ui::Checkbox>(
				inner,
				tr::lng_settings_bg_tile(tr::now),
				background->tile(),
				st::settingsCheckbox),
			st::settingsSendTypePadding));
	const auto adaptive = inner->add(
		object_ptr<Ui::SlideWrap<Ui::Checkbox>>(
			inner,
			object_ptr<Ui::Checkbox>(
				inner,
				tr::lng_settings_adaptive_wide(tr::now),
				Core::App().settings().adaptiveForWide(),
				st::settingsCheckbox),
			st::settingsSendTypePadding));

	tile->entity()->checkedChanges(
	) | rpl::start_with_next([=](bool checked) {
		background->setTile(checked);
	}, tile->lifetime());

	const auto shown = [=] {
		return !background->paper().isPattern()
			&& !background->colorForFill();
	};
	tile->toggle(shown(), anim::type::instant);

	using Update = const Window::Theme::BackgroundUpdate;
	background->updates(
	) | rpl::filter([](const Update &update) {
		return (update.type == Update::Type::Changed)
			|| (update.type == Update::Type::New);
	}) | rpl::start_with_next([=] {
		tile->entity()->setChecked(background->tile());
		tile->toggle(shown(), anim::type::instant);
	}, tile->lifetime());

	adaptive->toggleOn(controller->adaptive().chatLayoutValue(
	) | rpl::map([](Window::Adaptive::ChatLayout layout) {
		return (layout == Window::Adaptive::ChatLayout::Wide);
	}));

	adaptive->entity()->checkedChanges(
	) | rpl::start_with_next([=](bool checked) {
		Core::App().settings().setAdaptiveForWide(checked);
		Core::App().saveSettingsDelayed();
	}, adaptive->lifetime());
}

void SetupDefaultThemes(
		not_null<Window::Controller*> window,
		not_null<Ui::VerticalLayout*> container) {
	using Type = Window::Theme::EmbeddedType;
	using Scheme = Window::Theme::EmbeddedScheme;
	using Check = Window::Theme::CloudListCheck;
	using namespace Window::Theme;

	const auto block = container->add(object_ptr<Ui::FixedHeightWidget>(
		container));
	const auto palette = Ui::CreateChild<ColorsPalette>(
		container.get(),
		container.get());

	const auto chosen = [] {
		const auto &object = Background()->themeObject();
		if (object.cloud.id) {
			return Type(-1);
		}
		for (const auto &scheme : kSchemesList) {
			if (object.pathAbsolute == scheme.path) {
				return scheme.type;
			}
		}
		return Type(-1);
	};
	const auto group = std::make_shared<Ui::RadioenumGroup<Type>>(chosen());

	const auto apply = [=](const Scheme &scheme) {
		const auto isNight = [](const Scheme &scheme) {
			const auto type = scheme.type;
			return (type != Type::DayBlue) && (type != Type::Default);
		};
		const auto currentlyIsCustom = (chosen() == Type(-1))
			&& !Background()->themeObject().cloud.id;
		const auto keep = [=] {
			if (!currentlyIsCustom) {
				KeepApplied();
			}
		};
		if (IsNightMode() == isNight(scheme)) {
			ApplyDefaultWithPath(scheme.path);
			keep();
		} else {
			Window::Theme::ToggleNightModeWithConfirmation(
				window,
				[=, path = scheme.path] { ToggleNightMode(path); keep();});
		}
	};
	const auto schemeClicked = [=](
			const Scheme &scheme,
			Qt::KeyboardModifiers modifiers) {
		apply(scheme);
	};

	auto checks = base::flat_map<Type,not_null<Check*>>();
	auto buttons = ranges::views::all(
		kSchemesList
	) | ranges::views::transform([&](const Scheme &scheme) {
		auto check = std::make_unique<Check>(
			ColorsFromScheme(scheme),
			false);
		const auto weak = check.get();
		const auto result = Ui::CreateChild<Ui::Radioenum<Type>>(
			block,
			group,
			scheme.type,
			scheme.name(tr::now),
			st::settingsTheme,
			std::move(check));
		scheme.name(
		) | rpl::start_with_next([=](const auto &themeName) {
			result->setText(themeName);
		}, result->lifetime());
		result->addClickHandler([=] {
			schemeClicked(scheme, result->clickModifiers());
		});
		weak->setUpdateCallback([=] { result->update(); });
		checks.emplace(scheme.type, weak);
		return result;
	}) | ranges::to_vector;

	const auto refreshColorizer = [=](Type type) {
		if (type == chosen()) {
			palette->show(type);
		}

		const auto &colors = Core::App().settings().themesAccentColors();
		const auto i = checks.find(type);
		const auto scheme = ranges::find(kSchemesList, type, &Scheme::type);
		if (scheme == end(kSchemesList)) {
			return;
		}
		if (i != end(checks)) {
			if (const auto color = colors.get(type)) {
				const auto colorizer = ColorizerFrom(*scheme, *color);
				i->second->setColors(ColorsFromScheme(*scheme, colorizer));
			} else {
				i->second->setColors(ColorsFromScheme(*scheme));
			}
		}
	};
	group->setChangedCallback([=](Type type) {
		group->setValue(chosen());
	});
	for (const auto &scheme : kSchemesList) {
		refreshColorizer(scheme.type);
	}

	Background()->updates(
	) | rpl::filter([](const BackgroundUpdate &update) {
		return (update.type == BackgroundUpdate::Type::ApplyingTheme);
	}) | rpl::map([=] {
		return chosen();
	}) | rpl::start_with_next([=](Type type) {
		refreshColorizer(type);
		group->setValue(type);
	}, container->lifetime());

	for (const auto button : buttons) {
		button->setCheckAlignment(style::al_top);
		button->resizeToWidth(button->width());
	}
	block->resize(block->width(), buttons[0]->height());
	block->widthValue(
	) | rpl::start_with_next([buttons = std::move(buttons)](int width) {
		Expects(!buttons.empty());

		const auto padding = st::settingsButtonNoIcon.padding;
		width -= padding.left() + padding.right();
		const auto desired = st::settingsThemePreviewSize.width();
		const auto count = int(buttons.size());
		const auto skips = count - 1;
		const auto minSkip = st::settingsThemeMinSkip;
		const auto single = [&] {
			if (width >= skips * minSkip + count * desired) {
				return desired;
			}
			return (width - skips * minSkip) / count;
		}();
		if (single <= 0) {
			return;
		}
		const auto fullSkips = width - count * single;
		const auto skip = fullSkips / float64(skips);
		auto left = padding.left() + 0.;
		for (const auto button : buttons) {
			button->resizeToWidth(single);
			button->moveToLeft(int(base::SafeRound(left)), 0);
			left += button->width() + skip;
		}
	}, block->lifetime());

	palette->selected(
	) | rpl::start_with_next([=](QColor color) {
		if (Background()->editingTheme()) {
			// We don't remember old accent color to revert it properly
			// in Window::Theme::Revert which is called by Editor.
			//
			// So we check here, before we change the saved accent color.
			window->show(Ui::MakeInformBox(
				tr::lng_theme_editor_cant_change_theme()));
			return;
		}
		const auto type = chosen();
		const auto scheme = ranges::find(kSchemesList, type, &Scheme::type);
		if (scheme == end(kSchemesList)) {
			return;
		}
		auto &colors = Core::App().settings().themesAccentColors();
		if (colors.get(type) != color) {
			colors.set(type, color);
			Local::writeSettings();
		}
		apply(*scheme);
	}, container->lifetime());

	AddSkip(container);
}

void SetupThemeOptions(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	using namespace Window::Theme;

	AddSkip(container, st::settingsPrivacySkip);

	AddSubsectionTitle(container, tr::lng_settings_themes());

	AddSkip(container, st::settingsThemesTopSkip);
	SetupDefaultThemes(&controller->window(), container);
	AddSkip(container);
}

void SetupCloudThemes(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	using namespace Window::Theme;
	using namespace rpl::mappers;

	const auto wrap = container->add(
		object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
			container,
			object_ptr<Ui::VerticalLayout>(container))
	)->setDuration(0);
	const auto inner = wrap->entity();

	AddDivider(inner);
	AddSkip(inner, st::settingsPrivacySkip);

	const auto title = AddSubsectionTitle(
		inner,
		tr::lng_settings_bg_cloud_themes());
	const auto showAll = Ui::CreateChild<Ui::LinkButton>(
		inner,
		tr::lng_settings_bg_show_all(tr::now));

	rpl::combine(
		title->topValue(),
		inner->widthValue(),
		showAll->widthValue()
	) | rpl::start_with_next([=](int top, int outerWidth, int width) {
		showAll->moveToRight(
			st::settingsSubsectionTitlePadding.left(),
			top,
			outerWidth);
	}, showAll->lifetime());

	AddSkip(inner, st::settingsThemesTopSkip);

	const auto list = inner->lifetime().make_state<CloudList>(
		inner,
		controller);
	inner->add(
		list->takeWidget(),
		style::margins(
			st::settingsButtonNoIcon.padding.left(),
			0,
			st::settingsButtonNoIcon.padding.right(),
			0));

	list->allShown(
	) | rpl::start_with_next([=](bool shown) {
		showAll->setVisible(!shown);
	}, showAll->lifetime());

	showAll->addClickHandler([=] {
		list->showAll();
	});

	const auto editWrap = inner->add(
		object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
			inner,
			object_ptr<Ui::VerticalLayout>(inner))
	)->setDuration(0);
	const auto edit = editWrap->entity();

	AddSkip(edit, st::settingsThemesBottomSkip);
	AddButton(
		edit,
		tr::lng_settings_bg_theme_edit(),
		st::settingsButton,
		{ &st::settingsIconThemes, kIconGreen }
	)->addClickHandler([=] {
		StartEditor(
			&controller->window(),
			Background()->themeObject().cloud);
	});

	editWrap->toggleOn(rpl::single(BackgroundUpdate(
		BackgroundUpdate::Type::ApplyingTheme,
		Background()->tile()
	)) | rpl::then(
		Background()->updates()
	) | rpl::filter([](const BackgroundUpdate &update) {
		return (update.type == BackgroundUpdate::Type::ApplyingTheme);
	}) | rpl::map([=] {
		const auto userId = controller->session().userId();
		return (Background()->themeObject().cloud.createdBy == userId);
	}));

	AddSkip(inner, 2 * st::settingsSectionSkip);

	wrap->setDuration(0)->toggleOn(list->empty() | rpl::map(!_1));
}

void SetupAutoNightMode(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	if (!Platform::IsDarkModeSupported()) {
		return;
	}

	AddDivider(container);
	AddSkip(container, st::settingsPrivacySkip);

	AddSubsectionTitle(container, tr::lng_settings_auto_night_mode());

	auto wrap = object_ptr<Ui::VerticalLayout>(container);
	const auto autoNight = wrap->add(
		object_ptr<Ui::Checkbox>(
			wrap,
			tr::lng_settings_auto_night_enabled(tr::now),
			Core::App().settings().systemDarkModeEnabled(),
			st::settingsCheckbox),
		st::settingsCheckboxPadding);

	autoNight->checkedChanges(
	) | rpl::filter([=](bool checked) {
		return (checked != Core::App().settings().systemDarkModeEnabled());
	}) | rpl::start_with_next([=](bool checked) {
		if (checked && Window::Theme::Background()->editingTheme()) {
			autoNight->setChecked(false);
			controller->show(Ui::MakeInformBox(
				tr::lng_theme_editor_cant_change_theme()));
		} else {
			Core::App().settings().setSystemDarkModeEnabled(checked);
			Core::App().saveSettingsDelayed();
		}
	}, autoNight->lifetime());

	Core::App().settings().systemDarkModeEnabledChanges(
	) | rpl::filter([=](bool value) {
		return (value != autoNight->checked());
	}) | rpl::start_with_next([=](bool value) {
		autoNight->setChecked(value);
	}, autoNight->lifetime());

	container->add(object_ptr<Ui::OverrideMargins>(
		container,
		std::move(wrap)));

	AddSkip(container, st::settingsCheckboxesSkip);
}

void SetupSupportSwitchSettings(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	using SwitchType = Support::SwitchSettings;
	const auto group = std::make_shared<Ui::RadioenumGroup<SwitchType>>(
		controller->session().settings().supportSwitch());
	const auto add = [&](SwitchType value, const QString &label) {
		container->add(
			object_ptr<Ui::Radioenum<SwitchType>>(
				container,
				group,
				value,
				label,
				st::settingsSendType),
			st::settingsSendTypePadding);
	};
	add(SwitchType::None, "Just send the reply");
	add(SwitchType::Next, "Send and switch to next");
	add(SwitchType::Previous, "Send and switch to previous");
	group->setChangedCallback([=](SwitchType value) {
		controller->session().settings().setSupportSwitch(value);
		controller->session().saveSettingsDelayed();
	});
}

void SetupSupportChatsLimitSlice(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	constexpr auto kDayDuration = 24 * 60 * 60;
	struct Option {
		int days = 0;
		QString label;
	};
	const auto options = std::vector<Option>{
		{ 1, "1 day" },
		{ 7, "1 week" },
		{ 30, "1 month" },
		{ 365, "1 year" },
		{ 0, "All of them" },
	};
	const auto current = controller->session().settings().supportChatsTimeSlice();
	const auto days = current / kDayDuration;
	const auto best = ranges::min_element(
		options,
		std::less<>(),
		[&](const Option &option) { return std::abs(option.days - days); });

	const auto group = std::make_shared<Ui::RadiobuttonGroup>(best->days);
	for (const auto &option : options) {
		container->add(
			object_ptr<Ui::Radiobutton>(
				container,
				group,
				option.days,
				option.label,
				st::settingsSendType),
			st::settingsSendTypePadding);
	}
	group->setChangedCallback([=](int days) {
		controller->session().settings().setSupportChatsTimeSlice(
			days * kDayDuration);
		controller->session().saveSettingsDelayed();
	});
}

void SetupSupport(
		not_null<Window::SessionController*> controller,
		not_null<Ui::VerticalLayout*> container) {
	AddSkip(container);

	AddSubsectionTitle(container, rpl::single(u"Support settings"_q));

	AddSkip(container, st::settingsSendTypeSkip);

	const auto skip = st::settingsSendTypeSkip;
	auto wrap = object_ptr<Ui::VerticalLayout>(container);
	const auto inner = wrap.data();
	container->add(
		object_ptr<Ui::OverrideMargins>(
			container,
			std::move(wrap),
			QMargins(0, skip, 0, skip)));

	SetupSupportSwitchSettings(controller, inner);

	AddSkip(inner, st::settingsCheckboxesSkip);

	inner->add(
		object_ptr<Ui::Checkbox>(
			inner,
			"Enable templates autocomplete",
			controller->session().settings().supportTemplatesAutocomplete(),
			st::settingsCheckbox),
		st::settingsSendTypePadding
	)->checkedChanges(
	) | rpl::start_with_next([=](bool checked) {
		controller->session().settings().setSupportTemplatesAutocomplete(
			checked);
		controller->session().saveSettingsDelayed();
	}, inner->lifetime());

	inner->add(
		object_ptr<Ui::Checkbox>(
			inner,
			"Send all messages without sound",
			controller->session().settings().supportAllSilent(),
			st::settingsCheckbox),
		st::settingsSendTypePadding
	)->checkedChanges(
	) | rpl::start_with_next([=](bool checked) {
		controller->session().settings().setSupportAllSilent(
			checked);
		controller->session().saveSettingsDelayed();
	}, inner->lifetime());

	AddSkip(inner, st::settingsCheckboxesSkip);

	AddSubsectionTitle(inner, rpl::single(u"Load chats for a period"_q));

	SetupSupportChatsLimitSlice(controller, inner);

	AddSkip(inner, st::settingsCheckboxesSkip);

	AddSkip(inner);
}

Chat::Chat(QWidget *parent, not_null<Window::SessionController*> controller)
: Section(parent) {
	setupContent(controller);
}

rpl::producer<QString> Chat::title() {
	return tr::lng_settings_section_chat_settings();
}

void Chat::setupContent(not_null<Window::SessionController*> controller) {
	const auto content = Ui::CreateChild<Ui::VerticalLayout>(this);

	SetupThemeOptions(controller, content);
	SetupAutoNightMode(controller, content);
	SetupCloudThemes(controller, content);
	SetupChatBackground(controller, content);
	SetupStickersEmoji(controller, content);
	SetupMessages(controller, content);

	Ui::ResizeFitChild(this, content);
}

} // namespace Settings