summaryrefslogtreecommitdiff
path: root/indra/llui/llnotifications.h
blob: 46286457cfb4c3ca09e31955cfc441329411d43c (plain)
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
/**
* @file llnotifications.h
* @brief Non-UI manager and support for keeping a prioritized list of notifications
* @author Q (with assistance from Richard and Coco)
*
* $LicenseInfo:firstyear=2008&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
* $/LicenseInfo$
*/

#ifndef LL_LLNOTIFICATIONS_H
#define LL_LLNOTIFICATIONS_H

/**
 * This system is intended to provide a singleton mechanism for adding
 * notifications to one of an arbitrary set of event channels.
 *
 * Controlling JIRA: DEV-9061
 *
 * Every notification has (see code for full list):
 *  - a textual name, which is used to look up its template in the XML files
 *  - a payload, which is a block of LLSD
 *  - a channel, which is normally extracted from the XML files but
 *    can be overridden.
 *  - a timestamp, used to order the notifications
 *  - expiration time -- if nonzero, specifies a time after which the
 *    notification will no longer be valid.
 *  - a callback name and a couple of status bits related to callbacks (see below)
 *
 * There is a management class called LLNotifications, which is an LLSingleton.
 * The class maintains a collection of all of the notifications received
 * or processed during this session, and also manages the persistence
 * of those notifications that must be persisted.
 *
 * We also have Channels. A channel is a view on a collection of notifications;
 * The collection is defined by a filter function that controls which
 * notifications are in the channel, and its ordering is controlled by
 * a comparator.
 *
 * There is a hierarchy of channels; notifications flow down from
 * the management class (LLNotifications, which itself inherits from
 * The channel base class) to the individual channels.
 * Any change to notifications (add, delete, modify) is
 * automatically propagated through the channel hierarchy.
 *
 * We provide methods for adding a new notification, for removing
 * one, and for managing channels. Channels are relatively cheap to construct
 * and maintain, so in general, human interfaces should use channels to
 * select and manage their lists of notifications.
 *
 * We also maintain a collection of templates that are loaded from the
 * XML file of template translations. The system supports substitution
 * of named variables from the payload into the XML file.
 *
 * By default, only the "unknown message" template is built into the system.
 * It is not an error to add a notification that's not found in the
 * template system, but it is logged.
 *
 */

#include <string>
#include <list>
#include <vector>
#include <map>
#include <set>
#include <iomanip>
#include <sstream>

#include <boost/utility.hpp>
#include <boost/type_traits.hpp>
#include <boost/signals2.hpp>
#include <boost/range.hpp>
#include <boost/intrusive_ptr.hpp>

#include "llevents.h"
#include "llfunctorregistry.h"
#include "llinitparam.h"
#include "llinstancetracker.h"
#include "llmortician.h"
#include "llnotificationptr.h"
#include "llpointer.h"
#include "llrefcount.h"
#include "llsdparam.h"

#include "llnotificationslistener.h"

class LLAvatarName;
typedef enum e_notification_priority
{
    NOTIFICATION_PRIORITY_UNSPECIFIED,
    NOTIFICATION_PRIORITY_LOW,
    NOTIFICATION_PRIORITY_NORMAL,
    NOTIFICATION_PRIORITY_HIGH,
    NOTIFICATION_PRIORITY_CRITICAL
} ENotificationPriority;

struct NotificationPriorityValues : public LLInitParam::TypeValuesHelper<ENotificationPriority, NotificationPriorityValues>
{
    static void declareValues();
};

class LLNotificationResponderInterface
{
public:
    LLNotificationResponderInterface(){};
    virtual ~LLNotificationResponderInterface(){};

    virtual void handleRespond(const LLSD& notification, const LLSD& response) = 0;

    virtual LLSD asLLSD() = 0;

    virtual void fromLLSD(const LLSD& params) = 0;
};

typedef boost::function<void (const LLSD&, const LLSD&)> LLNotificationResponder;

typedef std::shared_ptr<LLNotificationResponderInterface> LLNotificationResponderPtr;

typedef LLFunctorRegistry<LLNotificationResponder> LLNotificationFunctorRegistry;
typedef LLFunctorRegistration<LLNotificationResponder> LLNotificationFunctorRegistration;

// context data that can be looked up via a notification's payload by the display logic
// derive from this class to implement specific contexts
class LLNotificationContext : public LLInstanceTracker<LLNotificationContext, LLUUID>
{
public:

    LLNotificationContext() : LLInstanceTracker<LLNotificationContext, LLUUID>(LLUUID::generateNewID())
    {
    }

    virtual ~LLNotificationContext() {}

    LLSD asLLSD() const
    {
        return getKey();
    }

private:

};

// Contains notification form data, such as buttons and text fields along with
// manipulator functions
class LLNotificationForm
{
    LOG_CLASS(LLNotificationForm);

public:
    struct FormElementBase : public LLInitParam::Block<FormElementBase>
    {
        Optional<std::string>   name;
        Optional<bool>          enabled;

        FormElementBase();
    };

    struct FormIgnore : public LLInitParam::Block<FormIgnore, FormElementBase>
    {
        Optional<std::string>   text;
        Optional<bool>          save_option;
        Optional<std::string>   control;
        Optional<bool>          invert_control;
        Optional<bool>          session_only;
        Optional<bool>          checkbox_only;

        FormIgnore();
    };

    struct FormButton : public LLInitParam::Block<FormButton, FormElementBase>
    {
        Mandatory<S32>          index;
        Mandatory<std::string>  text;
        Optional<std::string>   ignore;
        Optional<bool>          is_default;
        Optional<S32>           width;

        Mandatory<std::string>  type;

        FormButton();
    };

    struct FormInput : public LLInitParam::Block<FormInput, FormElementBase>
    {
        Mandatory<std::string>  type;
        Optional<S32>           width;
        Optional<S32>           max_length_chars;
        Optional<bool>          allow_emoji;
        Optional<std::string>   text;

        Optional<std::string>   value;
        FormInput();
    };

    struct FormElement : public LLInitParam::ChoiceBlock<FormElement>
    {
        Alternative<FormButton> button;
        Alternative<FormInput>  input;

        FormElement();
    };

    struct FormElements : public LLInitParam::Block<FormElements>
    {
        Multiple<FormElement> elements;
        FormElements();
    };

    struct Params : public LLInitParam::Block<Params>
    {
        Optional<std::string>   name;
        Optional<FormIgnore>    ignore;
        Optional<FormElements>  form_elements;

        Params();
    };

    typedef enum e_ignore_type
    {
        IGNORE_CHECKBOX_ONLY = -1, // ignore won't be handled, will set value/checkbox only
        IGNORE_NO = 0,
        IGNORE_WITH_DEFAULT_RESPONSE,
        IGNORE_WITH_DEFAULT_RESPONSE_SESSION_ONLY,
        IGNORE_WITH_LAST_RESPONSE,
        IGNORE_SHOW_AGAIN
    } EIgnoreType;

    LLNotificationForm();
    LLNotificationForm(const LLNotificationForm&);
    LLNotificationForm(const LLSD& sd);
    LLNotificationForm(const std::string& name, const Params& p);

    void fromLLSD(const LLSD& sd);
    LLSD asLLSD() const;

    S32 getNumElements() { return static_cast<S32>(mFormData.size()); }
    LLSD getElement(S32 index) { return mFormData.get(index); }
    LLSD getElement(std::string_view element_name);
    void getElements(LLSD& elements, S32 offset = 0);
    bool hasElement(std::string_view element_name) const;
    bool getElementEnabled(std::string_view element_name) const;
    void setElementEnabled(std::string_view element_name, bool enabled);
    void addElement(const std::string& type, const std::string& name, const LLSD& value = LLSD(), bool enabled = true);
    void formatElements(const LLSD& substitutions);
    // appends form elements from another form serialized as LLSD
    void append(const LLSD& sub_form);
    std::string getDefaultOption();
    LLPointer<class LLControlVariable> getIgnoreSetting();
    bool getIgnored();
    void setIgnored(bool ignored);

    EIgnoreType getIgnoreType() { return mIgnore; }
    std::string getIgnoreMessage() { return mIgnoreMsg; }

private:
    LLSD                                mFormData;
    EIgnoreType                         mIgnore;
    std::string                         mIgnoreMsg;
    LLPointer<class LLControlVariable>  mIgnoreSetting;
    bool                                mInvertSetting;
};

typedef std::shared_ptr<LLNotificationForm> LLNotificationFormPtr;


struct LLNotificationTemplate;

// we want to keep a map of these by name, and it's best to manage them
// with smart pointers
typedef std::shared_ptr<LLNotificationTemplate> LLNotificationTemplatePtr;


struct LLNotificationVisibilityRule;

typedef std::shared_ptr<LLNotificationVisibilityRule> LLNotificationVisibilityRulePtr;

/**
 * @class LLNotification
 * @brief The object that expresses the details of a notification
 *
 * We make this noncopyable because
 * we want to manage these through LLNotificationPtr, and only
 * ever create one instance of any given notification.
 *
 * The enable_shared_from_this flag ensures that if we construct
 * a smart pointer from a notification, we'll always get the same
 * shared pointer.
 */
class LLNotification  :
    boost::noncopyable,
    public std::enable_shared_from_this<LLNotification>
{
LOG_CLASS(LLNotification);
friend class LLNotifications;

public:

    // parameter object used to instantiate a new notification
    struct Params : public LLInitParam::Block<Params>
    {
        friend class LLNotification;

        Mandatory<std::string>                  name;
        Optional<LLUUID>                        id;
        Optional<LLSD>                          substitutions,
                                                form_elements,
                                                payload;
        Optional<ENotificationPriority, NotificationPriorityValues> priority;
        Optional<LLDate>                        time_stamp,
                                                expiry;
        Optional<LLNotificationContext*>        context;
        Optional<void*>                         responder;
        Optional<bool>                          offer_from_agent;
        Optional<bool>                          is_dnd;

        struct Functor : public LLInitParam::ChoiceBlock<Functor>
        {
            Alternative<std::string>                                        name;
            Alternative<LLNotificationFunctorRegistry::ResponseFunctor> function;
            Alternative<LLNotificationResponderPtr>                     responder;
            Alternative<LLSD>                                           responder_sd;

            Functor()
            :   name("responseFunctor"),
                function("functor"),
                responder("responder"),
                responder_sd("responder_sd")
            {}
        };
        Optional<Functor>                       functor;

        Params()
        :   name("name"),
            id("id"),
            priority("priority", NOTIFICATION_PRIORITY_UNSPECIFIED),
            time_stamp("time"),
            payload("payload"),
            form_elements("form"),
            substitutions("substitutions"),
            expiry("expiry"),
            offer_from_agent("offer_from_agent", false),
            is_dnd("is_dnd", false)
        {
            time_stamp = LLDate::now();
            responder = NULL;
        }

        Params(const std::string& _name)
        :   name("name"),
            priority("priority", NOTIFICATION_PRIORITY_UNSPECIFIED),
            time_stamp("time"),
            payload("payload"),
            form_elements("form"),
            substitutions("substitutions"),
            expiry("expiry"),
            offer_from_agent("offer_from_agent", false),
            is_dnd("is_dnd", false)
        {
            functor.name = _name;
            name = _name;
            time_stamp = LLDate::now();
            responder = NULL;
        }
    };

    LLNotificationResponderPtr getResponderPtr() { return mResponder; }

private:

    const LLUUID mId;
    LLSD mPayload;
    LLSD mSubstitutions;
    LLDate mTimestamp;
    LLDate mExpiresAt;
    bool mCancelled;
    bool mRespondedTo;  // once the notification has been responded to, this becomes true
    LLSD mResponse;
    bool mIgnored;
    ENotificationPriority mPriority;
    LLNotificationFormPtr mForm;
    void* mResponderObj; // TODO - refactor/remove this field
    LLNotificationResponderPtr mResponder;
    bool mOfferFromAgent;
    bool mIsDND;

    // a reference to the template
    LLNotificationTemplatePtr mTemplatep;

    /*
     We want to be able to store and reload notifications so that they can survive
     a shutdown/restart of the client. So we can't simply pass in callbacks;
     we have to specify a callback mechanism that can be used by name rather than
     by some arbitrary pointer -- and then people have to initialize callbacks
     in some useful location. So we use LLNotificationFunctorRegistry to manage them.
     */
     std::string mResponseFunctorName;

    /*
     In cases where we want to specify an explict, non-persisted callback,
     we store that in the callback registry under a dynamically generated
     key, and store the key in the notification, so we can still look it up
     using the same mechanism.
     */
    bool mTemporaryResponder;

    // keep track of other notifications combined with COMBINE_WITH_NEW
    std::vector<LLNotificationPtr> mCombinedNotifications;

    void init(const std::string& template_name, const LLSD& form_elements);

    void cancel();

public:
    LLNotification(const LLSDParamAdapter<Params>& p);

    void setResponseFunctor(std::string const &responseFunctorName);

    void setResponseFunctor(const LLNotificationFunctorRegistry::ResponseFunctor& cb);

    void setResponseFunctor(const LLNotificationResponderPtr& responder);

    typedef enum e_response_template_type
    {
        WITHOUT_DEFAULT_BUTTON,
        WITH_DEFAULT_BUTTON
    } EResponseTemplateType;

    // return response LLSD filled in with default form contents and (optionally) the default button selected
    LLSD getResponseTemplate(EResponseTemplateType type = WITHOUT_DEFAULT_BUTTON);

    // returns index of first button with value==true
    // usually this the button the user clicked on
    // returns -1 if no button clicked (e.g. form has not been displayed)
    static S32 getSelectedOption(const LLSD& notification, const LLSD& response);
    // returns name of first button with value==true
    static std::string getSelectedOptionName(const LLSD& notification);

    // after someone responds to a notification (usually by clicking a button,
    // but sometimes by filling out a little form and THEN clicking a button),
    // the result of the response (the name and value of the button clicked,
    // plus any other data) should be packaged up as LLSD, then passed as a
    // parameter to the notification's respond() method here. This will look up
    // and call the appropriate responder.
    //
    // response is notification serialized as LLSD:
    // ["name"] = notification name
    // ["form"] = LLSD tree that includes form description and any prefilled form data
    // ["response"] = form data filled in by user
    // (including, but not limited to which button they clicked on)
    // ["payload"] = transaction specific data, such as ["source_id"] (originator of notification),
    //              ["item_id"] (attached inventory item), etc.
    // ["substitutions"] = string substitutions used to generate notification message
    // from the template
    // ["time"] = time at which notification was generated;
    // ["expiry"] = time at which notification expires;
    // ["responseFunctor"] = name of registered functor that handles responses to notification;
    LLSD asLLSD(bool excludeTemplateElements = false);

    const LLNotificationFormPtr getForm();
    void updateForm(const LLNotificationFormPtr& form);

    void repost();

    void respond(const LLSD& sd);
    void respondWithDefault();

    void* getResponder() { return mResponderObj; }

    void setResponder(void* responder) { mResponderObj = responder; }

    void setIgnored(bool ignore);

    bool isCancelled() const
    {
        return mCancelled;
    }

    bool isRespondedTo() const
    {
        return mRespondedTo;
    }

    bool isActive() const
    {
        return !isRespondedTo()
            && !isCancelled()
            && !isExpired();
    }

    const LLSD& getResponse() { return mResponse; }

    bool isIgnored() const
    {
        return mIgnored;
    }

    const std::string& getName() const;

    const std::string& getIcon() const;

    bool isPersistent() const;

    const LLUUID& id() const
    {
        return mId;
    }

    const LLSD& getPayload() const
    {
        return mPayload;
    }

    const LLSD& getSubstitutions() const
    {
        return mSubstitutions;
    }

    const LLDate& getDate() const
    {
        return mTimestamp;
    }

    bool getOfferFromAgent() const
    {
        return mOfferFromAgent;
    }

    bool isDND() const
    {
        return mIsDND;
    }

    void setDND(const bool flag)
    {
        mIsDND = flag;
    }

    std::string getType() const;
    std::string getMessage() const;
    std::string getFooter() const;
    std::string getLabel() const;
    std::string getURL() const;
    S32 getURLOption() const;
    S32 getURLOpenExternally() const; //for url responce option
    bool getForceUrlsExternal() const;
    bool canLogToChat() const;
    bool canLogToIM() const;
    bool canShowToast() const;
    bool canFadeToast() const;
    bool hasFormElements() const;
    void playSound();

    typedef enum e_combine_behavior
    {
        REPLACE_WITH_NEW,
        COMBINE_WITH_NEW,
        KEEP_OLD,
        CANCEL_OLD

    } ECombineBehavior;

    ECombineBehavior getCombineBehavior() const;

    const LLDate getExpiration() const
    {
        return mExpiresAt;
    }

    ENotificationPriority getPriority() const
    {
        return mPriority;
    }

    const LLUUID getID() const
    {
        return mId;
    }

    // comparing two notifications normally means comparing them by UUID (so we can look them
    // up quickly this way)
    bool operator<(const LLNotification& rhs) const
    {
        return mId < rhs.mId;
    }

    bool operator==(const LLNotification& rhs) const
    {
        return mId == rhs.mId;
    }

    bool operator!=(const LLNotification& rhs) const
    {
        return !operator==(rhs);
    }

    bool isSameObjectAs(const LLNotification* rhs) const
    {
        return this == rhs;
    }

    // this object has been updated, so tell all our clients
    void update();

    void updateFrom(LLNotificationPtr other);

    // A fuzzy equals comparator.
    // true only if both notifications have the same template and
    //     1) flagged as unique (there can be only one of these) OR
    //     2) all required payload fields of each also exist in the other.
    bool isEquivalentTo(LLNotificationPtr that) const;

    // if the current time is greater than the expiration, the notification is expired
    bool isExpired() const
    {
        if (mExpiresAt.secondsSinceEpoch() == 0)
        {
            return false;
        }

        LLDate rightnow = LLDate::now();
        return rightnow > mExpiresAt;
    }

    std::string summarize() const;

    bool hasUniquenessConstraints() const;

    bool matchesTag(std::string_view tag);

    virtual ~LLNotification() {}
};

std::ostream& operator<<(std::ostream& s, const LLNotification& notification);

namespace LLNotificationFilters
{
    // a sample filter
    bool includeEverything(LLNotificationPtr p);

    typedef enum e_comparison
    {
        EQUAL,
        LESS,
        GREATER,
        LESS_EQUAL,
        GREATER_EQUAL
    } EComparison;

    // generic filter functor that takes method or member variable reference
    template<typename T>
    struct filterBy
    {
        typedef boost::function<T (LLNotificationPtr)>  field_t;
        typedef typename boost::remove_reference<T>::type       value_t;

        filterBy(field_t field, value_t value, EComparison comparison = EQUAL)
            :   mField(field),
                mFilterValue(value),
                mComparison(comparison)
        {
        }

        bool operator()(LLNotificationPtr p)
        {
            switch(mComparison)
            {
            case EQUAL:
                return mField(p) == mFilterValue;
            case LESS:
                return mField(p) < mFilterValue;
            case GREATER:
                return mField(p) > mFilterValue;
            case LESS_EQUAL:
                return mField(p) <= mFilterValue;
            case GREATER_EQUAL:
                return mField(p) >= mFilterValue;
            default:
                return false;
            }
        }

        field_t mField;
        value_t mFilterValue;
        EComparison mComparison;
    };
};

namespace LLNotificationComparators
{
    struct orderByUUID
    {
        bool operator()(LLNotificationPtr lhs, LLNotificationPtr rhs) const
        {
            return lhs->id() < rhs->id();
        }
    };
};

typedef boost::function<bool (LLNotificationPtr)> LLNotificationFilter;
typedef std::set<LLNotificationPtr, LLNotificationComparators::orderByUUID> LLNotificationSet;
typedef std::multimap<std::string, LLNotificationPtr> LLNotificationMap;

// ========================================================
// Abstract base class (interface) for a channel; also used for the master container.
// This lets us arrange channels into a call hierarchy.

// We maintain a hierarchy of notification channels; events are always started at the top
// and propagated through the hierarchy only if they pass a filter.
// Any channel can be created with a parent. A null parent (empty string) means it's
// tied to the root of the tree (the LLNotifications class itself).
// The default hierarchy looks like this:
//
// LLNotifications --+-- Expiration --+-- Mute --+-- Ignore --+-- Visible --+-- History
//                                                                          +-- Alerts
//                                                                          +-- Notifications
//
// In general, new channels that want to only see notifications that pass through
// all of the built-in tests should attach to the "Visible" channel
//
class LLNotificationChannelBase :
    public LLEventTrackable,
    public LLRefCount
{
    LOG_CLASS(LLNotificationChannelBase);
public:
    LLNotificationChannelBase(LLNotificationFilter filter)
    : mFilter(filter)
    , mItems()
    , mItemsMutex()
    {}

    virtual ~LLNotificationChannelBase()
    {
        // explicit cleanup for easier issue detection
        mChanged.disconnect_all_slots();
        mPassedFilter.disconnect_all_slots();
        mFailedFilter.disconnect_all_slots();
        LLMutexLock lock(&mItemsMutex);
        mItems.clear();
    }
    // you can also connect to a Channel, so you can be notified of
    // changes to this channel
    LLBoundListener connectChanged(const LLEventListener& slot)
    {
        // Call this->connectChangedImpl() to actually connect it.
        return connectChangedImpl(slot);
    }
    LLBoundListener connectAtFrontChanged(const LLEventListener& slot)
    {
        return connectAtFrontChangedImpl(slot);
    }
    LLBoundListener connectPassedFilter(const LLEventListener& slot)
    {
        // see comments in connectChanged()
        return connectPassedFilterImpl(slot);
    }
    LLBoundListener connectFailedFilter(const LLEventListener& slot)
    {
        // see comments in connectChanged()
        return connectFailedFilterImpl(slot);
    }

    // use this when items change or to add a new one
    bool updateItem(const LLSD& payload);
    const LLNotificationFilter& getFilter() { return mFilter; }

protected:
    LLBoundListener connectChangedImpl(const LLEventListener& slot);
    LLBoundListener connectAtFrontChangedImpl(const LLEventListener& slot);
    LLBoundListener connectPassedFilterImpl(const LLEventListener& slot);
    LLBoundListener connectFailedFilterImpl(const LLEventListener& slot);

    LLNotificationSet mItems;
    LLStandardSignal mChanged;
    LLStandardSignal mPassedFilter;
    LLStandardSignal mFailedFilter;
    LLMutex mItemsMutex;

    // these are action methods that subclasses can override to take action
    // on specific types of changes; the management of the mItems list is
    // still handled by the generic handler.
    virtual void onLoad(LLNotificationPtr p) {}
    virtual void onAdd(LLNotificationPtr p) {}
    virtual void onDelete(LLNotificationPtr p) {}
    virtual void onChange(LLNotificationPtr p) {}

    virtual void onFilterPass(LLNotificationPtr p) {}
    virtual void onFilterFail(LLNotificationPtr p) {}

    bool updateItem(const LLSD& payload, LLNotificationPtr pNotification);
    LLNotificationFilter mFilter;
};

// The type of the pointers that we're going to manage in the NotificationQueue system
// Because LLNotifications is a singleton, we don't actually expect to ever
// destroy it, but if it becomes necessary to do so, the shared_ptr model
// will ensure that we don't leak resources.
class LLNotificationChannel;
typedef boost::intrusive_ptr<LLNotificationChannel> LLNotificationChannelPtr;

// manages a list of notifications
// Note that if this is ever copied around, we might find ourselves with multiple copies
// of a queue with notifications being added to different nonequivalent copies. So we
// make it inherit from boost::noncopyable, and then create a map of LLPointer to manage it.
//
class LLNotificationChannel :
    boost::noncopyable,
    public LLNotificationChannelBase,
    public LLInstanceTracker<LLNotificationChannel, std::string>
{
    LOG_CLASS(LLNotificationChannel);

public:
    // Notification Channels have a filter, which determines which notifications
    // will be added to this channel.
    // Channel filters cannot change.
    struct Params : public LLInitParam::Block<Params>
    {
        Mandatory<std::string>              name;
        Optional<LLNotificationFilter>      filter;
        Multiple<std::string>               sources;
    };

    LLNotificationChannel(const Params& p = Params());
    LLNotificationChannel(const std::string& name, const std::string& parent, LLNotificationFilter filter);

    virtual ~LLNotificationChannel();
    typedef LLNotificationSet::iterator Iterator;

    std::string getName() const { return mName; }
    typedef std::vector<std::string>::const_iterator parents_iter;
    boost::iterator_range<parents_iter> getParents() const
    {
        return boost::iterator_range<parents_iter>(mParents);
    }

    bool isEmpty() const;
    S32 size() const;
    size_t size();

    typedef boost::function<void(LLNotificationPtr)> NotificationProcess;
    void forEachNotification(NotificationProcess process);

    std::string summarize();

protected:
    void connectToChannel(const std::string& channel_name);

private:
    std::string mName;
    std::vector<std::string> mParents;
    std::vector<LLBoundListener> mListeners;
};

// An interface class to provide a clean linker seam to the LLNotifications class.
// Extend this interface as needed for your use of LLNotifications.
class LLNotificationsInterface
{
public:
    virtual LLNotificationPtr add(const std::string& name,
                        const LLSD& substitutions,
                        const LLSD& payload,
                        LLNotificationFunctorRegistry::ResponseFunctor functor) = 0;
};

class LLNotifications :
    public LLNotificationsInterface,
    public LLSingleton<LLNotifications>,
    public LLNotificationChannelBase
{
    LLSINGLETON(LLNotifications);
    LOG_CLASS(LLNotifications);
    virtual ~LLNotifications() {}

public:

    // Needed to clear up RefCounted things prior to actual destruction
    // as the singleton nature of the class makes them do "bad things"
    // on at least Mac, if not all 3 platforms
    //
    void clear();

    // load all notification descriptions from file
    // calling more than once will overwrite existing templates
    // but never delete a template
    bool loadTemplates();

    // load visibility rules from file;
    // OK to call more than once because it will reload
    bool loadVisibilityRules();

    // Add a simple notification (from XUI)
    void addFromCallback(const LLSD& name);

    // *NOTE: To add simple notifications, #include "llnotificationsutil.h"
    // and use LLNotificationsUtil::add("MyNote") or add("MyNote", args)
    LLNotificationPtr add(const std::string& name,
                        const LLSD& substitutions,
                        const LLSD& payload);
    LLNotificationPtr add(const std::string& name,
                        const LLSD& substitutions,
                        const LLSD& payload,
                        const std::string& functor_name);
    /* virtual */ LLNotificationPtr add(const std::string& name,
                        const LLSD& substitutions,
                        const LLSD& payload,
                        LLNotificationFunctorRegistry::ResponseFunctor functor) override;
    LLNotificationPtr add(const LLNotification::Params& p);

    void add(const LLNotificationPtr pNotif);
    void load(const LLNotificationPtr pNotif);
    void cancel(LLNotificationPtr pNotif);
    void cancelByName(std::string_view name);
    void cancelByOwner(const LLUUID ownerId);
    void update(const LLNotificationPtr pNotif);

    LLNotificationPtr find(LLUUID uuid);

    // This is all stuff for managing the templates
    // take your template out
    LLNotificationTemplatePtr getTemplate(std::string_view name);

    // get the whole collection
    typedef std::vector<std::string> TemplateNames;
    TemplateNames getTemplateNames() const;  // returns a list of notification names

    typedef std::map<std::string, LLNotificationTemplatePtr, std::less<>> TemplateMap;

    TemplateMap::const_iterator templatesBegin() { return mTemplates.begin(); }
    TemplateMap::const_iterator templatesEnd() { return mTemplates.end(); }

    // test for existence
    bool templateExists(std::string_view name);

    typedef std::list<LLNotificationVisibilityRulePtr> VisibilityRuleList;

    void forceResponse(const LLNotification::Params& params, S32 option);

    void createDefaultChannels();

    LLNotificationChannelPtr getChannel(const std::string& channelName);

    std::string getGlobalString(std::string_view key) const;

    void setIgnoreAllNotifications(bool ignore);
    bool getIgnoreAllNotifications();

    void setIgnored(std::string_view name, bool ignored);
    bool getIgnored(std::string_view name);

    bool isVisibleByRules(LLNotificationPtr pNotification);

private:
    /*virtual*/ void initSingleton() override;
    /*virtual*/ void cleanupSingleton() override;

    void loadPersistentNotifications();

    bool expirationFilter(LLNotificationPtr pNotification);
    bool expirationHandler(const LLSD& payload);
    bool uniqueFilter(LLNotificationPtr pNotification);
    bool uniqueHandler(const LLSD& payload);
    bool failedUniquenessTest(const LLSD& payload);
    LLNotificationChannelPtr pHistoryChannel;
    LLNotificationChannelPtr pExpirationChannel;

    TemplateMap mTemplates;

    VisibilityRuleList mVisibilityRules;

    std::string mFileName;

    LLNotificationMap mUniqueNotifications;

    typedef std::map<std::string, std::string, std::less<>> GlobalStringMap;
    GlobalStringMap mGlobalStrings;

    bool mIgnoreAllNotifications;

    std::unique_ptr<LLNotificationsListener> mListener;

    std::vector<LLNotificationChannelPtr> mDefaultChannels;
};

/**
 * Abstract class for postponed notifications.
 * Provides possibility to add notification after specified by id avatar or group will be
 * received from cache name. The object of this type automatically well be deleted
 * by cleanup method after respond will be received from cache name.
 *
 * To add custom postponed notification to the notification system client should:
 *  1 create class derived from LLPostponedNotification;
 *  2 call LLPostponedNotification::add method;
 */
class LLPostponedNotification : public LLMortician
{
public:
    /**
     * Performs hooking cache name callback which will add notification to notifications system.
     * Type of added notification should be specified by template parameter T
     * and non-private derived from LLPostponedNotification class,
     * otherwise compilation error will occur.
     */
    template<class T>
    static void add(const LLNotification::Params& params,
            const LLUUID& id, bool is_group)
    {
        // upcast T to the base type to restrict T derivation from LLPostponedNotification
        LLPostponedNotification* thiz = new T();
        thiz->mParams = params;

        // Avoid header file dependency on llcachename.h
        thiz->lookupName(id, is_group);
    }

private:
    void lookupName(const LLUUID& id, bool is_group);
    // only used for groups
    void onGroupNameCache(const LLUUID& id, const std::string& full_name, bool is_group);
    // only used for avatars
    void fetchAvatarName(const LLUUID& id);
    void onAvatarNameCache(const LLUUID& agent_id, const LLAvatarName& av_name);
    // used for both group and avatar names
    void finalizeName(const std::string& name);

    void cleanup()
    {
        die();
    }

protected:
    LLPostponedNotification()
        : mParams(),
        mName(),
        mAvatarNameCacheConnection()
    {}

    virtual ~LLPostponedNotification()
    {
        if (mAvatarNameCacheConnection.connected())
        {
            mAvatarNameCacheConnection.disconnect();
        }
    }

    /**
     * Abstract method provides possibility to modify notification parameters and
     * will be called after cache name retrieve information about avatar or group
     * and before notification will be added to the notification system.
     */
    virtual void modifyNotificationParams() = 0;

    LLNotification::Params mParams;
    std::string mName;
    boost::signals2::connection mAvatarNameCacheConnection;
};

// Stores only persistent notifications.
// Class users can use connectChanged() to process persistent notifications
// (see LLPersistentNotificationStorage for example).
class LLPersistentNotificationChannel : public LLNotificationChannel
{
    LOG_CLASS(LLPersistentNotificationChannel);
public:
    LLPersistentNotificationChannel()
        :   LLNotificationChannel("Persistent", "Visible", &notificationFilter)
    {}

    virtual ~LLPersistentNotificationChannel()
    {
        mHistory.clear();
    }

    typedef std::vector<LLNotificationPtr> history_list_t;
    history_list_t::iterator beginHistory() { sortHistory(); return mHistory.begin(); }
    history_list_t::iterator endHistory() { return mHistory.end(); }

private:
    struct sortByTime
    {
        S32 operator ()(const LLNotificationPtr& a, const LLNotificationPtr& b)
        {
            return a->getDate() < b->getDate();
        }
    };

    void sortHistory()
    {
        std::sort(mHistory.begin(), mHistory.end(), sortByTime());
    }

    // The channel gets all persistent notifications except those that have been canceled
    static bool notificationFilter(LLNotificationPtr pNotification)
    {
        bool handle_notification = false;

        handle_notification = pNotification->isPersistent()
            && !pNotification->isCancelled();

        return handle_notification;
    }

    void onAdd(LLNotificationPtr p)
    {
        mHistory.push_back(p);
    }

    void onLoad(LLNotificationPtr p)
    {
        mHistory.push_back(p);
    }

    std::vector<LLNotificationPtr> mHistory;
};

#endif//LL_LLNOTIFICATIONS_H