-
Notifications
You must be signed in to change notification settings - Fork 5k
/
notifications_manager_linux.cpp
1137 lines (957 loc) · 28.6 KB
/
notifications_manager_linux.cpp
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
/*
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 "platform/linux/notifications_manager_linux.h"
#include "window/notifications_utilities.h"
#include "base/platform/base_platform_info.h"
#include "base/platform/linux/base_linux_glibmm_helper.h"
#include "base/platform/linux/base_linux_dbus_utilities.h"
#include "platform/linux/specific_linux.h"
#include "core/application.h"
#include "core/core_settings.h"
#include "history/history.h"
#include "history/history_item.h"
#include "main/main_session.h"
#include "lang/lang_keys.h"
#include "base/weak_ptr.h"
#include <QtCore/QVersionNumber>
#include <QtGui/QGuiApplication>
#include <glibmm.h>
#include <giomm.h>
namespace Platform {
namespace Notifications {
namespace {
constexpr auto kService = "org.freedesktop.Notifications"_cs;
constexpr auto kObjectPath = "/org/freedesktop/Notifications"_cs;
constexpr auto kInterface = kService;
constexpr auto kPropertiesInterface = "org.freedesktop.DBus.Properties"_cs;
using namespace base::Platform;
struct ServerInformation {
QString name;
QString vendor;
QVersionNumber version;
QVersionNumber specVersion;
};
bool ServiceRegistered = false;
bool InhibitionSupported = false;
std::optional<ServerInformation> CurrentServerInformation;
QStringList CurrentCapabilities;
std::unique_ptr<base::Platform::DBus::ServiceWatcher> CreateServiceWatcher() {
try {
const auto connection = Gio::DBus::Connection::get_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION);
const auto activatable = [&] {
try {
return ranges::contains(
base::Platform::DBus::ListActivatableNames(connection),
Glib::ustring(std::string(kService)));
} catch (...) {
// avoid service restart loop in sandboxed environments
return true;
}
}();
return std::make_unique<base::Platform::DBus::ServiceWatcher>(
connection,
std::string(kService),
[=](
const Glib::ustring &service,
const Glib::ustring &oldOwner,
const Glib::ustring &newOwner) {
if (activatable && newOwner.empty()) {
crl::on_main([] {
Core::App().notifications().clearAll();
});
return;
}
crl::on_main([] {
Core::App().notifications().createManager();
});
});
} catch (...) {
}
return nullptr;
}
void StartServiceAsync(Fn<void()> callback) {
try {
const auto connection = Gio::DBus::Connection::get_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION);
DBus::StartServiceByNameAsync(
connection,
std::string(kService),
[=](Fn<DBus::StartReply()> result) {
try {
result(); // get the error if any
} catch (const Glib::Error &e) {
static const auto NotSupportedErrors = {
"org.freedesktop.DBus.Error.ServiceUnknown",
};
const auto errorName =
Gio::DBus::ErrorUtils::get_remote_error(e);
if (!ranges::contains(NotSupportedErrors, errorName)) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
} catch (const std::exception &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
crl::on_main(callback);
});
return;
} catch (...) {
}
crl::on_main(callback);
}
bool GetServiceRegistered() {
try {
const auto connection = Gio::DBus::Connection::get_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION);
const auto hasOwner = [&] {
try {
return DBus::NameHasOwner(
connection,
std::string(kService));
} catch (...) {
return false;
}
}();
static const auto activatable = [&] {
try {
return ranges::contains(
DBus::ListActivatableNames(connection),
Glib::ustring(std::string(kService)));
} catch (...) {
return false;
}
}();
return hasOwner || activatable;
} catch (...) {
}
return false;
}
void GetServerInformation(
Fn<void(const std::optional<ServerInformation> &)> callback) {
try {
const auto connection = Gio::DBus::Connection::get_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION);
connection->call(
std::string(kObjectPath),
std::string(kInterface),
"GetServerInformation",
{},
[=](const Glib::RefPtr<Gio::AsyncResult> &result) {
try {
auto reply = connection->call_finish(result);
const auto name = GlibVariantCast<Glib::ustring>(
reply.get_child(0));
const auto vendor = GlibVariantCast<Glib::ustring>(
reply.get_child(1));
const auto version = GlibVariantCast<Glib::ustring>(
reply.get_child(2));
const auto specVersion = GlibVariantCast<Glib::ustring>(
reply.get_child(3));
crl::on_main([=] {
callback(ServerInformation{
QString::fromStdString(name),
QString::fromStdString(vendor),
QVersionNumber::fromString(
QString::fromStdString(version)),
QVersionNumber::fromString(
QString::fromStdString(specVersion)),
});
});
return;
} catch (const Glib::Error &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
} catch (const std::exception &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
crl::on_main([=] { callback(std::nullopt); });
},
std::string(kService));
return;
} catch (const Glib::Error &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
crl::on_main([=] { callback(std::nullopt); });
}
void GetCapabilities(Fn<void(const QStringList &)> callback) {
try {
const auto connection = Gio::DBus::Connection::get_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION);
connection->call(
std::string(kObjectPath),
std::string(kInterface),
"GetCapabilities",
{},
[=](const Glib::RefPtr<Gio::AsyncResult> &result) {
try {
auto reply = connection->call_finish(result);
QStringList value;
ranges::transform(
GlibVariantCast<std::vector<Glib::ustring>>(
reply.get_child(0)),
ranges::back_inserter(value),
QString::fromStdString);
crl::on_main([=] {
callback(value);
});
return;
} catch (const Glib::Error &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
} catch (const std::exception &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
crl::on_main([=] { callback({}); });
},
std::string(kService));
return;
} catch (const Glib::Error &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
crl::on_main([=] { callback({}); });
}
void GetInhibitionSupported(Fn<void(bool)> callback) {
try {
const auto connection = Gio::DBus::Connection::get_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION);
connection->call(
std::string(kObjectPath),
std::string(kPropertiesInterface),
"Get",
MakeGlibVariant(std::tuple{
Glib::ustring(std::string(kInterface)),
Glib::ustring("Inhibited"),
}),
[=](const Glib::RefPtr<Gio::AsyncResult> &result) {
try {
connection->call_finish(result);
crl::on_main([=] {
callback(true);
});
return;
} catch (const Glib::Error &e) {
static const auto DontLogErrors = {
"org.freedesktop.DBus.Error.InvalidArgs",
"org.freedesktop.DBus.Error.UnknownMethod",
};
const auto errorName = Gio::DBus::ErrorUtils::get_remote_error(e);
if (!ranges::contains(DontLogErrors, errorName)) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
}
crl::on_main([=] { callback(false); });
},
std::string(kService));
return;
} catch (const Glib::Error &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
crl::on_main([=] { callback(false); });
}
bool Inhibited() {
if (!Supported()
|| !CurrentCapabilities.contains(qsl("inhibitions"))
|| !InhibitionSupported) {
return false;
}
try {
const auto connection = Gio::DBus::Connection::get_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION);
// a hack for snap's activation restriction
DBus::StartServiceByName(
connection,
std::string(kService));
auto reply = connection->call_sync(
std::string(kObjectPath),
std::string(kPropertiesInterface),
"Get",
MakeGlibVariant(std::tuple{
Glib::ustring(std::string(kInterface)),
Glib::ustring("Inhibited"),
}),
std::string(kService));
return GlibVariantCast<bool>(
GlibVariantCast<Glib::VariantBase>(reply.get_child(0)));
} catch (const Glib::Error &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
} catch (const std::exception &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
return false;
}
bool IsQualifiedDaemon() {
// A list of capabilities that offer feature parity
// with custom notifications
static const auto NeededCapabilities = {
// To show message content
qsl("body"),
// To make the sender name bold
qsl("body-markup"),
// To have buttons on notifications
qsl("actions"),
// To have quick reply
qsl("inline-reply"),
// To not to play sound with Don't Disturb activated
// (no, using sound capability is not a way)
qsl("inhibitions"),
};
return ranges::all_of(NeededCapabilities, [&](const auto &capability) {
return CurrentCapabilities.contains(capability);
}) && InhibitionSupported;
}
ServerInformation CurrentServerInformationValue() {
return CurrentServerInformation.value_or(ServerInformation{});
}
Glib::ustring GetImageKey(const QVersionNumber &specificationVersion) {
const auto normalizedVersion = specificationVersion.normalized();
if (normalizedVersion.isNull()) {
LOG(("Native Notification Error: specification version is null"));
return {};
}
if (normalizedVersion >= QVersionNumber(1, 2)) {
return "image-data";
} else if (normalizedVersion == QVersionNumber(1, 1)) {
return "image_data";
}
return "icon_data";
}
class NotificationData final : public base::has_weak_ptr {
public:
using NotificationId = Window::Notifications::Manager::NotificationId;
NotificationData(
not_null<Manager*> manager,
NotificationId id);
[[nodiscard]] bool init(
const QString &title,
const QString &subtitle,
const QString &msg,
Window::Notifications::Manager::DisplayOptions options);
NotificationData(const NotificationData &other) = delete;
NotificationData &operator=(const NotificationData &other) = delete;
NotificationData(NotificationData &&other) = delete;
NotificationData &operator=(NotificationData &&other) = delete;
~NotificationData();
void show();
void close();
void setImage(const QString &imagePath);
private:
const not_null<Manager*> _manager;
NotificationId _id;
Glib::RefPtr<Gio::DBus::Connection> _dbusConnection;
Glib::ustring _title;
Glib::ustring _body;
std::vector<Glib::ustring> _actions;
std::map<Glib::ustring, Glib::VariantBase> _hints;
Glib::ustring _imageKey;
uint _notificationId = 0;
uint _actionInvokedSignalId = 0;
uint _activationTokenSignalId = 0;
uint _notificationRepliedSignalId = 0;
uint _notificationClosedSignalId = 0;
void notificationClosed(uint id, uint reason);
void actionInvoked(uint id, const Glib::ustring &actionName);
void activationToken(uint id, const Glib::ustring &token);
void notificationReplied(uint id, const Glib::ustring &text);
};
using Notification = std::unique_ptr<NotificationData>;
NotificationData::NotificationData(
not_null<Manager*> manager,
NotificationId id)
: _manager(manager)
, _id(id) {
}
bool NotificationData::init(
const QString &title,
const QString &subtitle,
const QString &msg,
Window::Notifications::Manager::DisplayOptions options) {
try {
_dbusConnection = Gio::DBus::Connection::get_sync(
Gio::DBus::BusType::BUS_TYPE_SESSION);
} catch (const Glib::Error &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
return false;
}
const auto weak = base::make_weak(this);
const auto capabilities = CurrentCapabilities;
const auto signalEmitted = [=](
const Glib::RefPtr<Gio::DBus::Connection> &connection,
const Glib::ustring &sender_name,
const Glib::ustring &object_path,
const Glib::ustring &interface_name,
const Glib::ustring &signal_name,
Glib::VariantContainerBase parameters) {
try {
if (signal_name == "ActionInvoked") {
const auto id = GlibVariantCast<uint>(
parameters.get_child(0));
const auto actionName = GlibVariantCast<Glib::ustring>(
parameters.get_child(1));
crl::on_main(weak, [=] { actionInvoked(id, actionName); });
} else if (signal_name == "ActivationToken") {
const auto id = GlibVariantCast<uint>(
parameters.get_child(0));
const auto token = GlibVariantCast<Glib::ustring>(
parameters.get_child(1));
crl::on_main(weak, [=] { activationToken(id, token); });
} else if (signal_name == "NotificationReplied") {
const auto id = GlibVariantCast<uint>(
parameters.get_child(0));
const auto text = GlibVariantCast<Glib::ustring>(
parameters.get_child(1));
crl::on_main(weak, [=] { notificationReplied(id, text); });
} else if (signal_name == "NotificationClosed") {
const auto id = GlibVariantCast<uint>(
parameters.get_child(0));
const auto reason = GlibVariantCast<uint>(
parameters.get_child(1));
crl::on_main(weak, [=] { notificationClosed(id, reason); });
}
} catch (const std::exception &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
};
_title = title.toStdString();
_imageKey = GetImageKey(CurrentServerInformationValue().specVersion);
if (capabilities.contains(qsl("body-markup"))) {
_body = subtitle.isEmpty()
? msg.toHtmlEscaped().toStdString()
: qsl("<b>%1</b>\n%2").arg(
subtitle.toHtmlEscaped(),
msg.toHtmlEscaped()).toStdString();
} else {
_body = subtitle.isEmpty()
? msg.toStdString()
: qsl("%1\n%2").arg(subtitle, msg).toStdString();
}
if (capabilities.contains("actions")) {
_actions.push_back("default");
_actions.push_back({});
if (!options.hideMarkAsRead) {
_actions.push_back("mail-mark-read");
_actions.push_back(
tr::lng_context_mark_read(tr::now).toStdString());
}
if (capabilities.contains("inline-reply") && !options.hideReplyButton) {
_actions.push_back("inline-reply");
_actions.push_back(
tr::lng_notification_reply(tr::now).toStdString());
_notificationRepliedSignalId = _dbusConnection->signal_subscribe(
signalEmitted,
std::string(kService),
std::string(kInterface),
"NotificationReplied",
std::string(kObjectPath));
} else {
// icon name according to https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
_actions.push_back("mail-reply-sender");
_actions.push_back(
tr::lng_notification_reply(tr::now).toStdString());
}
_actionInvokedSignalId = _dbusConnection->signal_subscribe(
signalEmitted,
std::string(kService),
std::string(kInterface),
"ActionInvoked",
std::string(kObjectPath));
_activationTokenSignalId = _dbusConnection->signal_subscribe(
signalEmitted,
std::string(kService),
std::string(kInterface),
"ActivationToken",
std::string(kObjectPath));
}
if (capabilities.contains("action-icons")) {
_hints["action-icons"] = Glib::Variant<bool>::create(true);
}
// suppress system sound if telegram sound activated,
// otherwise use system sound
if (capabilities.contains("sound")) {
if (Core::App().settings().soundNotify()) {
_hints["suppress-sound"] = Glib::Variant<bool>::create(true);
} else {
// sound name according to http://0pointer.de/public/sound-naming-spec.html
_hints["sound-name"] = Glib::Variant<Glib::ustring>::create(
"message-new-instant");
}
}
if (capabilities.contains("x-canonical-append")) {
_hints["x-canonical-append"] = Glib::Variant<Glib::ustring>::create(
"true");
}
_hints["category"] = Glib::Variant<Glib::ustring>::create("im.received");
_hints["desktop-entry"] = Glib::Variant<Glib::ustring>::create(
QGuiApplication::desktopFileName().chopped(8).toStdString());
_notificationClosedSignalId = _dbusConnection->signal_subscribe(
signalEmitted,
std::string(kService),
std::string(kInterface),
"NotificationClosed",
std::string(kObjectPath));
return true;
}
NotificationData::~NotificationData() {
if (_dbusConnection) {
if (_actionInvokedSignalId != 0) {
_dbusConnection->signal_unsubscribe(_actionInvokedSignalId);
}
if (_activationTokenSignalId != 0) {
_dbusConnection->signal_unsubscribe(_activationTokenSignalId);
}
if (_notificationRepliedSignalId != 0) {
_dbusConnection->signal_unsubscribe(_notificationRepliedSignalId);
}
if (_notificationClosedSignalId != 0) {
_dbusConnection->signal_unsubscribe(_notificationClosedSignalId);
}
}
}
void NotificationData::show() {
// a hack for snap's activation restriction
const auto weak = base::make_weak(this);
StartServiceAsync(crl::guard(weak, [=] {
const auto iconName = _imageKey.empty()
|| _hints.find(_imageKey) == end(_hints)
? Glib::ustring(GetIconName().toStdString())
: Glib::ustring();
const auto connection = _dbusConnection;
connection->call(
std::string(kObjectPath),
std::string(kInterface),
"Notify",
MakeGlibVariant(std::tuple{
Glib::ustring(std::string(AppName)),
uint(0),
iconName,
_title,
_body,
_actions,
_hints,
-1,
}),
[=](const Glib::RefPtr<Gio::AsyncResult> &result) {
try {
auto reply = connection->call_finish(result);
const auto notificationId = GlibVariantCast<uint>(
reply.get_child(0));
crl::on_main(weak, [=] {
_notificationId = notificationId;
});
return;
} catch (const Glib::Error &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
} catch (const std::exception &e) {
LOG(("Native Notification Error: %1").arg(
QString::fromStdString(e.what())));
}
crl::on_main(weak, [=] {
_manager->clearNotification(_id);
});
},
std::string(kService));
}));
}
void NotificationData::close() {
_dbusConnection->call(
std::string(kObjectPath),
std::string(kInterface),
"CloseNotification",
MakeGlibVariant(std::tuple{
_notificationId,
}),
{},
std::string(kService),
-1,
Gio::DBus::CALL_FLAGS_NO_AUTO_START);
_manager->clearNotification(_id);
}
void NotificationData::setImage(const QString &imagePath) {
if (imagePath.isEmpty() || _imageKey.empty()) {
return;
}
const auto image = [&] {
const auto original = QImage(imagePath);
return original.hasAlphaChannel()
? original.convertToFormat(QImage::Format_RGBA8888)
: original.convertToFormat(QImage::Format_RGB888);
}();
if (image.isNull()) {
return;
}
_hints[_imageKey] = MakeGlibVariant(std::tuple{
image.width(),
image.height(),
int(image.bytesPerLine()),
image.hasAlphaChannel(),
8,
image.hasAlphaChannel() ? 4 : 3,
std::vector<uchar>(
image.constBits(),
image.constBits() + image.sizeInBytes()),
});
}
void NotificationData::notificationClosed(uint id, uint reason) {
/*
* From: https://specifications.freedesktop.org/notification-spec/latest/ar01s09.html
* The reason the notification was closed
* 1 - The notification expired.
* 2 - The notification was dismissed by the user.
* 3 - The notification was closed by a call to CloseNotification.
* 4 - Undefined/reserved reasons.
*
* If the notification was dismissed by the user (reason == 2), the notification is not kept in notification history.
* We do not need to send a "CloseNotification" call later to clear it from history.
* Therefore we can drop the notification reference now.
* In all other cases we keep the notification reference so that we may clear the notification later from history,
* if the message for that notification is read (e.g. chat is opened or read from another device).
*/
if (id == _notificationId && reason == 2) {
_manager->clearNotification(_id);
}
}
void NotificationData::actionInvoked(
uint id,
const Glib::ustring &actionName) {
if (id != _notificationId) {
return;
}
if (actionName == "default"
|| actionName == "mail-reply-sender") {
_manager->notificationActivated(_id);
} else if (actionName == "mail-mark-read") {
_manager->notificationReplied(_id, {});
}
}
void NotificationData::activationToken(uint id, const Glib::ustring &token) {
if (id == _notificationId) {
qputenv("XDG_ACTIVATION_TOKEN", QByteArray::fromStdString(token));
}
}
void NotificationData::notificationReplied(
uint id,
const Glib::ustring &text) {
if (id == _notificationId) {
_manager->notificationReplied(
_id,
{ QString::fromStdString(text), {} });
}
}
} // namespace
bool SkipAudioForCustom() {
return false;
}
bool SkipToastForCustom() {
return false;
}
bool SkipFlashBounceForCustom() {
return false;
}
bool Supported() {
return ServiceRegistered;
}
bool Enforced() {
// Wayland doesn't support positioning
// and custom notifications don't work here
return IsWayland();
}
bool ByDefault() {
return IsQualifiedDaemon();
}
void Create(Window::Notifications::System *system) {
static const auto ServiceWatcher = CreateServiceWatcher();
const auto managerSetter = [=] {
using ManagerType = Window::Notifications::ManagerType;
if ((Core::App().settings().nativeNotifications() && Supported())
|| Enforced()) {
if (!system->managerType().has_value()
|| *system->managerType() != ManagerType::Native) {
system->setManager(std::make_unique<Manager>(system));
}
} else if (!system->managerType().has_value()
|| *system->managerType() != ManagerType::Default) {
system->setManager(nullptr);
}
};
const auto counter = std::make_shared<int>(3);
const auto oneReady = [=] {
if (!--*counter) {
managerSetter();
}
};
const auto serviceActivated = [=] {
ServiceRegistered = GetServiceRegistered();
if (!ServiceRegistered) {
CurrentServerInformation = std::nullopt;
CurrentCapabilities = QStringList{};
InhibitionSupported = false;
managerSetter();
return;
}
GetServerInformation([=](const std::optional<ServerInformation> &result) {
CurrentServerInformation = result;
oneReady();
});
GetCapabilities([=](const QStringList &result) {
CurrentCapabilities = result;
oneReady();
});
GetInhibitionSupported([=](bool result) {
InhibitionSupported = result;
oneReady();
});
};
// There are some asserts that manager is not nullptr,
// avoid crashes until some real manager is created
if (!system->managerType().has_value()) {
using DummyManager = Window::Notifications::DummyManager;
system->setManager(std::make_unique<DummyManager>(system));
}
// snap doesn't allow access when the daemon is not running :(
StartServiceAsync(serviceActivated);
}
class Manager::Private {
public:
using Type = Window::Notifications::CachedUserpics::Type;
explicit Private(not_null<Manager*> manager, Type type);
void showNotification(
not_null<PeerData*> peer,
std::shared_ptr<Data::CloudImageView> &userpicView,
MsgId msgId,
const QString &title,
const QString &subtitle,
const QString &msg,
DisplayOptions options);
void clearAll();
void clearFromItem(not_null<HistoryItem*> item);
void clearFromHistory(not_null<History*> history);
void clearFromSession(not_null<Main::Session*> session);
void clearNotification(NotificationId id);
~Private();
private:
const not_null<Manager*> _manager;
base::flat_map<
FullPeer,
base::flat_map<MsgId, Notification>> _notifications;
Window::Notifications::CachedUserpics _cachedUserpics;
};
Manager::Private::Private(not_null<Manager*> manager, Type type)
: _manager(manager)
, _cachedUserpics(type) {
if (!Supported()) {
return;
}
const auto serverInformation = CurrentServerInformation;
const auto capabilities = CurrentCapabilities;
if (serverInformation.has_value()) {
LOG(("Notification daemon product name: %1")
.arg(serverInformation->name));
LOG(("Notification daemon vendor name: %1")
.arg(serverInformation->vendor));
LOG(("Notification daemon version: %1")
.arg(serverInformation->version.toString()));
LOG(("Notification daemon specification version: %1")
.arg(serverInformation->specVersion.toString()));
}
if (!capabilities.isEmpty()) {
LOG(("Notification daemon capabilities: %1")
.arg(capabilities.join(", ")));
}
}
void Manager::Private::showNotification(
not_null<PeerData*> peer,
std::shared_ptr<Data::CloudImageView> &userpicView,
MsgId msgId,
const QString &title,
const QString &subtitle,
const QString &msg,
DisplayOptions options) {
if (!Supported()) {
return;
}
const auto key = FullPeer{
.sessionId = peer->session().uniqueId(),
.peerId = peer->id
};
const auto notificationId = NotificationId{ .full = key, .msgId = msgId };
auto notification = std::make_unique<NotificationData>(
_manager,
notificationId);
const auto inited = notification->init(
title,
subtitle,
msg,
options);
if (!inited) {
return;
}
if (!options.hideNameAndPhoto) {
const auto userpicKey = peer->userpicUniqueKey(userpicView);
notification->setImage(
_cachedUserpics.get(userpicKey, peer, userpicView));
}
auto i = _notifications.find(key);
if (i != end(_notifications)) {
auto j = i->second.find(msgId);
if (j != end(i->second)) {
auto oldNotification = std::move(j->second);
i->second.erase(j);
oldNotification->close();
i = _notifications.find(key);
}
}
if (i == end(_notifications)) {
i = _notifications.emplace(
key,
base::flat_map<MsgId, Notification>()).first;
}
const auto j = i->second.emplace(
msgId,
std::move(notification)).first;
j->second->show();
}
void Manager::Private::clearAll() {
if (!Supported()) {
return;
}
for (const auto &[key, notifications] : base::take(_notifications)) {
for (const auto &[msgId, notification] : notifications) {
notification->close();
}
}
}
void Manager::Private::clearFromItem(not_null<HistoryItem*> item) {
if (!Supported()) {
return;