File: notifier.cpp

package info (click to toggle)
sight 25.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 42,184 kB
  • sloc: cpp: 289,476; xml: 17,257; ansic: 9,878; python: 1,379; sh: 144; makefile: 33
file content (557 lines) | stat: -rw-r--r-- 19,142 bytes parent folder | download | duplicates (2)
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
/************************************************************************
 *
 * Copyright (C) 2020-2025 IRCAD France
 * Copyright (C) 2021 IHU Strasbourg
 *
 * This file is part of Sight.
 *
 * Sight 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, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight 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 Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "module/ui/qt/notifier.hpp"

#include <core/base.hpp>
#include <core/com/slots.hxx>
#include <core/runtime/path.hpp>

#include <service/macros.hpp>

#include <ui/__/registry.hpp>

#include <boost/range/iterator_range_core.hpp>

#include <QApplication>
#include <QAudioOutput>

namespace sight::module::ui::qt
{

static const core::com::slots::key_t POP_NOTIFICATION_SLOT   = "pop";
static const core::com::slots::key_t CLOSE_NOTIFICATION_SLOT = "close_notification";
static const core::com::slots::key_t SET_ENUM_PARAMETER_SLOT = "set_enum_parameter";

static const std::string POSITION_KEY("position");
static const std::string DURATION_KEY("duration");
static const std::string SIZE_KEY("size");
static const std::string MAX_KEY("max");
static const std::string CLOSABLE_KEY("closable");

static const std::string INFINITE("infinite");

static const std::map<service::notification::type, std::filesystem::path> SOUND_BOARD = {
    {
        service::notification::type::info,
        std::filesystem::canonical(
            sight::core::runtime::get_resource_file_path("sight::module::ui::qt/sounds/info_beep.wav")
        )
    }
    ,
    {
        service::notification::type::success,
        std::filesystem::canonical(
            sight::core::runtime::get_resource_file_path("sight::module::ui::qt/sounds/success_beep.wav")
        ),
    },
    {
        service::notification::type::failure,
        std::filesystem::canonical(
            sight::core::runtime::get_resource_file_path("sight::module::ui::qt/sounds/failure_beep.wav")
        )
    },
};

static const std::map<const std::string, const sight::ui::dialog::notification::position> POSITION_MAP = {
    {"TOP_RIGHT", service::notification::position::top_right},
    {"TOP_LEFT", service::notification::position::top_left},
    {"CENTERED_TOP", service::notification::position::centered_top},
    {"CENTERED", service::notification::position::centered},
    {"BOTTOM_RIGHT", service::notification::position::bottom_right},
    {"BOTTOM_LEFT", service::notification::position::bottom_left},
    {"CENTERED_BOTTOM", service::notification::position::centered_bottom}
};

//-----------------------------------------------------------------------------

notifier::notifier() noexcept
{
    new_slot(POP_NOTIFICATION_SLOT, &notifier::pop, this);
    new_slot(CLOSE_NOTIFICATION_SLOT, &notifier::close_notification, this);
    new_slot(SET_ENUM_PARAMETER_SLOT, &notifier::set_enum_parameter, this);
}

//-----------------------------------------------------------------------------

void notifier::configuring()
{
    const auto& config = this->get_config();

    if(const auto& channels = config.get_child_optional("channels"); channels)
    {
        for(const auto& channel : boost::make_iterator_range(channels->equal_range("channel")))
        {
            configuration channel_config {};

            // UID
            const auto& uid = channel.second.get_optional<std::string>("<xmlattr>.uid").value_or("");

            // Position
            if(const auto& position = channel.second.get_optional<std::string>("<xmlattr>." + POSITION_KEY);
               position)
            {
                if(POSITION_MAP.contains(*position))
                {
                    channel_config.position = POSITION_MAP.at(*position);
                }
                else
                {
                    SIGHT_ERROR(
                        "Position '"
                        + *position
                        + "' isn't a valid position value, accepted values are:"
                          "TOP_RIGHT, TOP_LEFT, CENTERED_TOP, CENTERED, BOTTOM_RIGHT, BOTTOM_LEFT, CENTERED_BOTTOM."
                    )
                }
            }

            // Duration
            if(const auto& duration = channel.second.get_optional<std::string>("<xmlattr>." + DURATION_KEY);
               duration)
            {
                if(*duration == INFINITE)
                {
                    channel_config.duration = std::chrono::milliseconds(0);
                }
                else
                {
                    try
                    {
                        channel_config.duration = std::chrono::milliseconds(std::stoul(*duration));
                    }
                    catch(...)
                    {
                        SIGHT_ERROR(
                            "Duration '"
                            + *duration
                            + "' is not valid. Accepted values are: '"
                            + INFINITE
                            + "' or a positive number of milliseconds."
                        )
                    }
                }
            }

            // Size
            if(const auto& size = channel.second.get_optional<std::string>("<xmlattr>." + SIZE_KEY); size)
            {
                try
                {
                    if(const auto pos = size->find_first_of('x'); pos != std::string::npos)
                    {
                        const auto width  = std::stoul(size->substr(0, pos));
                        const auto height = std::stoul(size->substr(pos + 1));

                        channel_config.size = {int(width), int(height)};
                    }
                    else
                    {
                        throw std::runtime_error("No 'x' found.");
                    }
                }
                catch(...)
                {
                    SIGHT_ERROR(
                        "Size '"
                        + *size
                        + "' is not valid. Accepted values are: `n x n` where 'n' is a positive number."
                    )
                }
            }

            // Max
            if(const auto& max = channel.second.get_optional<std::string>("<xmlattr>." + MAX_KEY); max)
            {
                try
                {
                    channel_config.max = std::stoul(*max);
                }
                catch(...)
                {
                    SIGHT_ERROR(
                        "Maximum '"
                        + *max
                        + "' is not valid. Accepted values are positive numbers."
                    )
                }
            }

            // Closable
            if(const auto& closable = channel.second.get_optional<std::string>("<xmlattr>." + CLOSABLE_KEY);
               closable)
            {
                channel_config.closable = *closable == "true";
            }

            m_channels.insert_or_assign(uid, channel_config);
        }
    }

    // Lastly, initialize sound strutures.
    m_sound = std::make_unique<QMediaPlayer>(qApp);
    auto* audio_output = new QAudioOutput(qApp);
    m_sound->setAudioOutput(audio_output);

    m_default_message     = config.get<std::string>("message", m_default_message);
    m_parent_container_id = config.get<std::string>("parent.<xmlattr>.uid", m_parent_container_id);
}

//-----------------------------------------------------------------------------

void notifier::starting()
{
    if(!m_parent_container_id.empty())
    {
        auto container = sight::ui::registry::get_sid_container(m_parent_container_id);

        if(!container)
        {
            container = sight::ui::registry::get_wid_container(m_parent_container_id);
        }

        // If we have an SID/WID set the container.
        if(container)
        {
            m_container_where_to_display_notifs = container;
        }
    }
}

//-----------------------------------------------------------------------------

void notifier::stopping()
{
    for(const auto& [position, stack] : m_stacks)
    {
        for(const auto& popup : stack.popups)
        {
            popup->close();
        }
    }

    m_stacks.clear();
}

//-----------------------------------------------------------------------------

void notifier::updating()
{
}

//-----------------------------------------------------------------------------

void notifier::set_enum_parameter(std::string _val, std::string _key)
{
    try
    {
        if(_key == POSITION_KEY)
        {
            m_channels[""].position = POSITION_MAP.at(_val);
        }
        else if(_key == DURATION_KEY)
        {
            if(_val == INFINITE)
            {
                m_channels[""].duration = std::chrono::milliseconds(0);
            }
            else
            {
                m_channels[""].duration = std::chrono::milliseconds(std::stoul(_val));
            }
        }
        else if(_key == SIZE_KEY)
        {
            if(const auto pos = _val.find_first_of('x'); pos != std::string::npos)
            {
                const auto width  = std::stoul(_val.substr(0, pos));
                const auto height = std::stoul(_val.substr(pos + 1));

                m_channels[""].size = {int(width), int(height)};
            }
        }
        else if(_key == MAX_KEY)
        {
            m_channels[""].max = std::stoul(_val);
        }
        else if(_key == CLOSABLE_KEY)
        {
            m_channels[""].closable = _val == "true";
        }
    }
    catch(...)
    {
        SIGHT_ERROR(std::string("Value '") + _val + "' is not handled for key " + _key);
    }
}

//-----------------------------------------------------------------------------

void notifier::pop(service::notification _notification)
{
    const bool channel_configured = m_channels.contains(_notification.m_channel);

    // Get channel configuration (or global configuration if there is no channel)
    const auto& channel_configuration = channel_configured
                                        ? m_channels[_notification.m_channel]
                                        : m_channels[""];

    const auto& default_configuration = m_channels[""];

    // Get the stack configuration. First try the channel, then the default, then the notification itself
    // If you want that services totally control the notification, associate them to an unconfigured notifier
    const auto& position = channel_configured && channel_configuration.position
                           ? *channel_configuration.position
                           : (channel_configured && !channel_configuration.position) || !default_configuration.position
                           ? _notification.m_position
                           : *default_configuration.position;

    const auto& duration = channel_configured && channel_configuration.duration
                           ? channel_configuration.duration
                           : (channel_configured && !channel_configuration.duration) || !default_configuration.duration
                           ? _notification.m_duration
                           : default_configuration.duration;

    const auto& size = channel_configured && channel_configuration.size
                       ? *channel_configuration.size
                       : (channel_configured && !channel_configuration.size) || !default_configuration.size
                       ? _notification.m_size
                       : *default_configuration.size;

    const auto& max = channel_configuration.max
                      ? *channel_configuration.max
                      : default_configuration.max
                      ? *default_configuration.max
                      : 0;

    const auto& closable = channel_configured && channel_configuration.closable
                           ? channel_configuration.closable
                           : (channel_configured && !channel_configuration.closable) || !default_configuration.closable
                           ? _notification.m_closable
                           : default_configuration.closable;

    // Get the wanted stack
    auto& target_stack = m_stacks[position];

    // Compute harmonized max and size
    target_stack.max = target_stack.max
                       ? std::max(*target_stack.max, max)
                       : max;

    target_stack.size = target_stack.size
                        ? std::array<int, 2>
    {
        std::max((*target_stack.size)[0], size[0]),
        std::max((*target_stack.size)[1], size[1])
    }
                        : size;

    // If the maximum number of notification is reached, remove the oldest one.
    clean_notifications(position, *target_stack.max, *target_stack.size);

    // Get or create the notification
    const auto& popup =
        [&]
        {
            // If a channel is present, try to retrieve the associated dialog
            if(!_notification.m_channel.empty())
            {
                for(auto& [old_position, stack] : m_stacks)
                {
                    for(const auto& popup : stack.popups)
                    {
                        if(popup->get_channel() == _notification.m_channel)
                        {
                            // If the position doesn't match, fix it
                            if(old_position != position)
                            {
                                // Explicit copy
                                auto copy = popup;
                                copy->set_index(static_cast<unsigned int>(target_stack.popups.size()));
                                target_stack.popups.emplace_back(copy);

                                // Remove the original
                                stack.popups.remove(popup);

                                return copy;
                            }

                            return popup;
                        }
                    }
                }
            }

            // No channel or the dialog was not found, create a new one
            auto popup = std::make_shared<sight::ui::dialog::notification>();
            popup->set_index(static_cast<unsigned int>(target_stack.popups.size()));
            target_stack.popups.emplace_back(popup);

            return popup;
        }();

    popup->set_container(m_container_where_to_display_notifs);

    const std::string& message_to_show = _notification.m_message.empty() ? m_default_message : _notification.m_message;
    popup->set_message(message_to_show);

    popup->set_type(_notification.m_type);
    popup->set_position(position);
    popup->set_duration(duration);
    popup->set_size(*target_stack.size);
    std::weak_ptr<sight::core::base_object> weak_notifier = this->shared_from_this();
    popup->set_closed_callback(
        [weak_notifier, popup](auto&& ...)
        {
            if(auto notifier = std::dynamic_pointer_cast<sight::module::ui::qt::notifier>(weak_notifier.lock());
               notifier)
            {
                notifier->on_notification_closed(popup);
            }
        });
    popup->set_channel(_notification.m_channel);
    popup->set_closable(closable);
    popup->show();

    if(_notification.m_sound.has_value() && _notification.m_sound.value())
    {
        SIGHT_ASSERT(
            "Notification sound requested with a type that isn't registered in the sound board.",
            SOUND_BOARD.contains(_notification.m_type)
        );

        m_sound->setSource(
            QUrl::fromLocalFile(
                QString::fromStdString(SOUND_BOARD.at(_notification.m_type).string())
            )
        );
        m_sound->play();
    }
}

//------------------------------------------------------------------------------

void notifier::close_notification(std::string _channel)
{
    bool found = false;

    for(const auto& [position, stack] : m_stacks)
    {
        for(const auto& popup : stack.popups)
        {
            if(popup->get_channel() == _channel)
            {
                found = true;
                popup->close();
            }
        }
    }

    SIGHT_WARN_IF("Notification on channel '" << _channel << "' is already closed.", !found);
}

//------------------------------------------------------------------------------

void notifier::on_notification_closed(const sight::ui::dialog::notification::sptr& _notif)
{
    // If the notification still exist
    for(auto& [position, stack] : m_stacks)
    {
        if(auto it = std::ranges::find(stack.popups.begin(), stack.popups.end(), _notif); it != stack.popups.end())
        {
            erase_notification(position, it);
        }
    }
}

//------------------------------------------------------------------------------

std::list<sight::ui::dialog::notification::sptr>::iterator notifier::erase_notification(
    const enum service::notification::position& _position,
    const std::list<sight::ui::dialog::notification::sptr>::iterator& _it
)
{
    // Remove the notification from the container
    auto& stack        = m_stacks[_position];
    const auto next_it = stack.popups.erase(_it);
    auto remaining_it  = next_it;

    // Move all the remaining notifications one index lower
    while(remaining_it != stack.popups.end())
    {
        (*remaining_it)->move_down();
        ++remaining_it;
    }

    // Return the it pointing after the erased one
    return next_it;
}

//------------------------------------------------------------------------------

void notifier::clean_notifications(
    const enum service::notification::position& _position,
    std::size_t _max,
    std::array<int, 2> _size,
    bool _skip_permanent
)
{
    // Get the correct "stack"
    auto& stack = m_stacks[_position];

    std::size_t removable_popups = 0;

    // Count how many popups that can be removed there are
    for(const auto& popup : stack.popups)
    {
        if(!_skip_permanent || popup->get_duration())
        {
            ++removable_popups;
        }
    }

    for(auto it = stack.popups.begin() ; removable_popups >= _max && it != stack.popups.end() ; )
    {
        // If the popup is removable
        if(const auto& duration = (*it)->get_duration(); !_skip_permanent || (duration && duration->count() > 0))
        {
            // Remove it
            (*it)->close();
            it = erase_notification(_position, it);
            --removable_popups;
        }
        else
        {
            ++it;
        }
    }

    // Adjust sizes
    for(const auto& popup : stack.popups)
    {
        popup->set_size(_size);
    }
}

//-----------------------------------------------------------------------------

} // namespace sight::module::ui::qt