Debian Codegraph @

src/Gui/NotificationArea.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2022 Abdullah Tahiri <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QAction>
25 #include <QActionEvent>
26 #include <QApplication>
27 #include <QEvent>
28 #include <QHBoxLayout>
29 #include <QHeaderView>
30 #include <QMenu>
31 #include <QMessageBox>
32 #include <QStringList>
33 #include <QTextDocument>
34 #include <QThread>
35 #include <QTimer>
36 #include <QTreeWidget>
37 #include <QWidgetAction>
38 #include <memory>
39 #include <mutex>
40
41
42 #include <App/Application.h>
43 #include <Base/Console.h>
44
45 #include "Application.h"
46 #include "BitmapFactory.h"
47 #include "MDIView.h"
48 #include "MainWindow.h"
49 #include "NotificationBox.h"
50
51 #include "NotificationArea.h"
52
53 using namespace Gui;
54
55 using Connection = boost::signals2::connection;
56
57 namespace sp = std::placeholders;
58
59 using std::lock_guard;
60
61 class NotificationAreaObserver;
62
63 namespace Gui
64 {
65 /** PImpl idiom structure having all data necessary for the notification area */
66 struct NotificationAreaP
67 {
68 // Structure holding all variables necessary for the Notification Area.
69 // Preference parameters are updated by NotificationArea::ParameterObserver
70
71 // NOLINTBEGIN
72 /** @name Non-intrusive notifications parameters */
73 //@{
74 /// Parameter controlled
75 int maxOpenNotifications = 15;
76 /// Parameter controlled
77 unsigned int notificationExpirationTime = 10000;
78 /// minimum time that the notification will remain unclosed
79 unsigned int minimumOnScreenTime = 5000;
80 /// Parameter controlled
81 bool notificationsDisabled = false;
82 /// Control of confirmation mechanism (for Critical Messages)
83 bool requireConfirmationCriticalMessageDuringRestoring = true;
84 /// Width of the non-intrusive notification
85 int notificationWidth = 800;
86 /// Any open non-intrusive notifications will disappear when another window is activated
87 bool hideNonIntrusiveNotificationsWhenWindowDeactivated = true;
88 /// Prevent non-intrusive notifications from appearing when the FreeCAD Window is not the active
89 /// window
90 bool preventNonIntrusiveNotificationsWhenWindowNotActive = true;
91 //@}
92
93 /** @name Widget parameters */
94 //@{
95 /// Parameter controlled - maximum number of message allowed in the notification area widget (0
96 /// means no limit)
97 int maxWidgetMessages = 1000;
98 /// User notifications get automatically removed from the Widget after the non-intrusive
99 /// notification expiration time
100 bool autoRemoveUserNotifications = false;
101 //@}
102
103 /** @name Notification rate control */
104 //@{
105 /* Control rate of updates of non-intrusive messages (avoids visual artifacts when messages are
106 * constantly being received) */
107 // Timer to delay notification until a minimum time between two consecutive messages have lapsed
108 QTimer inhibitTimer;
109 // The time between two consecutive messages forced by the inhibitTimer
110 const unsigned int inhibitNotificationTime = 250;
111 //@}
112
113 /** @name Data source control */
114 //@{
115 /* Controls whether debug warnings and errors intended for developers should be processed or not
116 */
117 bool developerErrorSubscriptionEnabled = false;
118 bool developerWarningSubscriptionEnabled = false;
119 //@}
120
121 bool missedNotifications = false;
122
123 // Access control
124 std::mutex mutexNotification;
125
126 // Pointers to widgets (no ownership)
127 QMenu* menu = nullptr;
128 QWidgetAction* notificationaction = nullptr;
129
130 /** @name Resources */
131 //@{
132 /// Base::Console Message observer
133 std::unique_ptr<NotificationAreaObserver> observer;
134 Connection finishRestoreDocumentConnection;
135 /// Preference Parameter observer
136 std::unique_ptr<NotificationArea::ParameterObserver> parameterObserver;
137 //@}
138
139 // NOLINTEND
140 };
141
142 } // namespace Gui
143
144
145 /******************* Resource Management *****************************************/
146
147 /** Simple class to manage Notification Area Resources*/
148 class ResourceManager
149 {
150
151 private:
152 ResourceManager()
153 {
154 // NOLINTBEGIN
155 error = BitmapFactory().pixmapFromSvg(":/icons/edit_Cancel.svg", QSize(16, 16));
156 warning = BitmapFactory().pixmapFromSvg(":/icons/Warning.svg", QSize(16, 16));
157 critical = BitmapFactory().pixmapFromSvg(":/icons/critical-info.svg", QSize(16, 16));
158 info = BitmapFactory().pixmapFromSvg(":/icons/info.svg", QSize(16, 16));
159 // NOLINTEND
160 notificationArea = QIcon(QStringLiteral(":/icons/InTray.svg"));
161 notificationAreaMissedNotifications = QIcon(
162 QStringLiteral(":/icons/InTray_missed_notifications.svg")
163 );
164 }
165
166 inline static const auto& getResourceManager()
167 {
168 static ResourceManager manager;
169
170 return manager;
171 }
172
173 public:
174 inline static auto ErrorPixmap()
175 {
176 auto rm = getResourceManager();
177 return rm.error;
178 }
179
180 inline static auto WarningPixmap()
181 {
182 auto rm = getResourceManager();
183 return rm.warning;
184 }
185
186 inline static auto CriticalPixmap()
187 {
188 auto rm = getResourceManager();
189 return rm.critical;
190 }
191
192 inline static auto InfoPixmap()
193 {
194 auto rm = getResourceManager();
195 return rm.info;
196 }
197
198 inline static auto NotificationAreaIcon()
199 {
200 auto rm = getResourceManager();
201 return rm.notificationArea;
202 }
203
204 inline static auto notificationAreaMissedNotificationsIcon()
205 {
206 auto rm = getResourceManager();
207 return rm.notificationAreaMissedNotifications;
208 }
209
210 private:
211 QPixmap error;
212 QPixmap warning;
213 QPixmap critical;
214 QPixmap info;
215 QIcon notificationArea;
216 QIcon notificationAreaMissedNotifications;
217 };
218
219 /******************** Console Messages Observer (Console Interface) ************************/
220
221 /** This class listens to all messages sent via the console interface and
222 feeds the non-intrusive notification system and the notifications widget */
223 class NotificationAreaObserver: public Base::ILogger
224 {
225 public:
226 NotificationAreaObserver(NotificationArea* notificationarea);
227 ~NotificationAreaObserver() override;
228
229 NotificationAreaObserver(const NotificationAreaObserver&) = delete;
230 NotificationAreaObserver(NotificationAreaObserver&&) = delete;
231 NotificationAreaObserver& operator=(const NotificationAreaObserver&) = delete;
232 NotificationAreaObserver& operator=(NotificationAreaObserver&&) = delete;
233
234 /// Function that is called by the console interface for this observer with the message
235 /// information
236 void sendLog(
237 const std::string& notifiername,
238 const std::string& msg,
239 Base::LogStyle level,
240 Base::IntendedRecipient recipient,
241 Base::ContentType content
242 ) override;
243
244 /// Name of the observer
245 const char* name() override
246 {
247 return "NotificationAreaObserver";
248 }
249
250 private:
251 NotificationArea* notificationArea;
252 };
253
254 NotificationAreaObserver::NotificationAreaObserver(NotificationArea* notificationarea)
255 : notificationArea(notificationarea)
256 {
257 Base::Console().attachObserver(this);
258 bLog = false; // ignore log messages
259 bMsg = false; // ignore messages
260 bNotification = true; // activate user notifications
261 }
262
263 NotificationAreaObserver::~NotificationAreaObserver()
264 {
265 Base::Console().detachObserver(this);
266 }
267
268 void NotificationAreaObserver::sendLog(
269 const std::string& notifiername,
270 const std::string& msg,
271 Base::LogStyle level,
272 Base::IntendedRecipient recipient,
273 Base::ContentType content
274 )
275 {
276 // 1. As notification system is shared with report view and others, the expectation is that any
277 // individual error and warning message will end in "\n". This means the string must be stripped
278 // of this character for representation in the notification area.
279 // 2. However, any message marked with the QT_TRANSLATE_NOOT macro with the "Notifications"
280 // context, shall not include
281 // "\n", as this generates problems with the translation system. Then the string must be
282 // stripped of "\n" before translation.
283
284 bool violatesBasicPolicy
285 = (recipient == Base::IntendedRecipient::Developer
286 || content == Base::ContentType::Untranslatable);
287
288 // We allow derogations for debug purposes according to user preferences
289 bool meetsDerogationCriteria = false;
290
291 if (violatesBasicPolicy) {
292 meetsDerogationCriteria = (level == Base::LogStyle::Warning
293 && notificationArea->areDeveloperWarningsActive())
294 || (level == Base::LogStyle::Error && notificationArea->areDeveloperErrorsActive());
295 }
296
297 if (violatesBasicPolicy && !meetsDerogationCriteria) {
298 return;
299 }
300
301 auto simplifiedstring = QString::fromStdString(msg).trimmed(); // remove any leading and trailing
302 // whitespace character ('\n')
303
304 // avoid processing empty strings
305 if (simplifiedstring.isEmpty()) {
306 return;
307 }
308
309 if (content == Base::ContentType::Translated) {
310 notificationArea->pushNotification(QString::fromStdString(notifiername), simplifiedstring, level);
311 }
312 else {
313 notificationArea->pushNotification(
314 QString::fromStdString(notifiername),
315 QCoreApplication::translate("Notifications", simplifiedstring.toUtf8()),
316 level
317 );
318 }
319 }
320
321
322 /******************* Notification Widget *******************************************************/
323
324 /** Specialised Item class for the Widget notifications/errors/warnings
325 It holds all item specific data, including visualisation data and controls how
326 the item should appear in the widget.
327 */
328 class NotificationItem: public QTreeWidgetItem
329 {
330 public:
331 NotificationItem(Base::LogStyle notificationtype, QString notifiername, QString message)
332 : notificationType(notificationtype)
333 , notifierName(std::move(notifiername))
334 , msg(std::move(message))
335 {}
336
337 QVariant data(int column, int role) const override
338 {
339 // strings that will be displayed for each column of the widget
340 if (role == Qt::DisplayRole) {
341 switch (column) {
342 case 1:
343 return notifierName;
344 break;
345 case 2:
346 return getMessage();
347 break;
348 }
349 }
350 else if (column == 0 && role == Qt::DecorationRole) {
351 // Icons to be displayed for the first row
352 if (notificationType == Base::LogStyle::Error) {
353 return std::move(ResourceManager::ErrorPixmap());
354 }
355 else if (notificationType == Base::LogStyle::Warning) {
356 return std::move(ResourceManager::WarningPixmap());
357 }
358 else if (notificationType == Base::LogStyle::Critical) {
359 return std::move(ResourceManager::CriticalPixmap());
360 }
361 else {
362 return std::move(ResourceManager::InfoPixmap());
363 }
364 }
365 else if (role == Qt::FontRole) {
366 // Visualisation control of unread messages
367 static QFont font;
368 static QFont boldFont(font.family(), font.pointSize(), QFont::Bold);
369
370 if (unread) {
371 return boldFont;
372 }
373
374 return font;
375 }
376
377 return {};
378 }
379
380 void addRepetition()
381 {
382 unread = true;
383 notifying = true;
384 shown = false;
385 repetitions++;
386 }
387
388 bool isRepeated(Base::LogStyle notificationtype, const QString& notifiername, const QString& message) const
389 {
390 return (notificationType == notificationtype && notifierName == notifiername && msg == message);
391 }
392
393 bool isType(Base::LogStyle notificationtype) const
394 {
395 return notificationType == notificationtype;
396 }
397
398 bool isUnread() const
399 {
400 return unread;
401 }
402
403 bool isNotifying() const
404 {
405 return notifying;
406 }
407
408 bool isShown() const
409 {
410 return shown;
411 }
412
413 int getRepetitions() const
414 {
415 return repetitions;
416 }
417
418 void setNotified()
419 {
420 notifying = false;
421 }
422
423 void resetNotified()
424 {
425 notifying = true;
426 }
427
428 void setShown()
429 {
430 shown = true;
431 }
432
433 void resetShown()
434 {
435 shown = false;
436 }
437
438 void setRead()
439 {
440 unread = false;
441 }
442
443 void setUnread()
444 {
445 unread = true;
446 }
447
448 QString getMessage() const
449 {
450 if (repetitions == 0) {
451 return msg;
452 }
453 else {
454 return msg + QObject::tr(" (%1 times)").arg(repetitions + 1);
455 }
456 }
457
458 const QString& getNotifier()
459 {
460 return notifierName;
461 }
462
463 private:
464 Base::LogStyle notificationType;
465 QString notifierName;
466 QString msg;
467
468 bool unread = true; // item is unread in the Notification Area Widget
469 bool notifying = true; // item is to be notified or being notified as non-intrusive message
470 bool shown = false; // item is already being notified (it is onScreen)
471 int repetitions = 0; // message appears n times in a row.
472 };
473
474 /** Drop menu Action containing the notifications widget.
475 * It stores all the notification item information in the form
476 * of NotificationItems (QTreeWidgetItem). This information is used
477 * by the Widget and by the non-intrusive messages.
478 * It owns the notification resources and is responsible for the release
479 * of the memory resources, either directly for the intermediate fast cache
480 * or indirectly via QT for the case of the QTreeWidgetItems.
481 */
482 class NotificationsAction: public QWidgetAction
483 {
484 public:
485 NotificationsAction(QWidget* parent)
486 : QWidgetAction(parent)
487 {}
488
489 NotificationsAction(const NotificationsAction&) = delete;
490 NotificationsAction(NotificationsAction&&) = delete;
491 NotificationsAction& operator=(const NotificationsAction&) = delete;
492 NotificationsAction& operator=(NotificationsAction&&) = delete;
493
494 ~NotificationsAction() override
495 {
496 for (auto* item : std::as_const(pushedItems)) {
497 if (item) {
498 delete item; // NOLINT
499 }
500 }
501 }
502
503 public:
504 /// deletes only notifications (messages of type Notification)
505 void deleteNotifications()
506 {
507 if (tableWidget) {
508 for (int i = tableWidget->topLevelItemCount() - 1; i >= 0; i--) {
509 // NOLINTNEXTLINE
510 auto* item = static_cast<NotificationItem*>(tableWidget->topLevelItem(i));
511 if (item->isType(Base::LogStyle::Notification)) {
512 delete item; // NOLINT
513 }
514 }
515 }
516 for (int i = pushedItems.size() - 1; i >= 0; i--) {
517 // NOLINTNEXTLINE
518 auto* item = static_cast<NotificationItem*>(pushedItems.at(i));
519 if (item->isType(Base::LogStyle::Notification)) {
520 delete pushedItems.takeAt(i); // NOLINT
521 }
522 }
523 }
524
525 /// deletes all notifications, errors and warnings
526 void deleteAll()
527 {
528 if (tableWidget) {
529 tableWidget->clear(); // the parent will delete the items.
530 }
531 while (!pushedItems.isEmpty()) {
532 delete pushedItems.takeFirst();
533 }
534 }
535
536 /// returns the amount of unread notifications, errors and warnings
537 inline int getUnreadCount() const
538 {
539 return getCurrently([](auto* item) { return item->isUnread(); });
540 }
541
542 /// returns the amount of notifications, errors and warnings currently being notified
543 inline int getCurrentlyNotifyingCount() const
544 {
545 return getCurrently([](auto* item) { return item->isNotifying(); });
546 }
547
548 /// returns the amount of notifications, errors and warnings currently being shown as
549 /// non-intrusive messages (on-screen)
550 inline int getShownCount() const
551 {
552 return getCurrently([](auto* item) { return item->isShown(); });
553 }
554
555 /// marks all notifications, errors and warnings as read
556 void clearUnreadFlag()
557 {
558 for (auto i = 0; i < tableWidget->topLevelItemCount();
559 i++) { // all messages were read, so clear the unread flag
560 // NOLINTNEXTLINE
561 auto* item = static_cast<NotificationItem*>(tableWidget->topLevelItem(i));
562 item->setRead();
563 }
564 }
565
566 /// pushes all Notification Items to the Widget, so that they can be shown
567 void synchroniseWidget()
568 {
569 tableWidget->insertTopLevelItems(0, pushedItems);
570 pushedItems.clear();
571 }
572
573 /** pushes all Notification Items to the fast cache (this also prevents all unnecessary
574 * signaling from parents) and allows one to accelerate insertions and deletions
575 */
576 void shiftToCache()
577 {
578 tableWidget->blockSignals(true);
579 tableWidget->clearSelection();
580 while (tableWidget->topLevelItemCount() > 0) {
581 auto* item = tableWidget->takeTopLevelItem(0);
582 pushedItems.push_back(item);
583 }
584 tableWidget->blockSignals(false);
585 }
586
587 /// returns if there are no notifications, errors and warnings at all
588 bool isEmpty() const
589 {
590 return tableWidget->topLevelItemCount() == 0 && pushedItems.isEmpty();
591 }
592
593 /// returns the total amount of notifications, errors and warnings currently stored
594 auto count() const
595 {
596 return tableWidget->topLevelItemCount() + pushedItems.count();
597 }
598
599 /// retrieves a pointer to a given notification from storage.
600 auto getItem(int index) const
601 {
602 if (index < pushedItems.count()) {
603 return pushedItems.at(index);
604 }
605 else {
606 return tableWidget->topLevelItem(index - pushedItems.count());
607 }
608 }
609
610 /// deletes a given notification, errors or warnings by index
611 void deleteItem(int index)
612 {
613 if (index < pushedItems.count()) {
614 delete pushedItems.takeAt(index); // NOLINT
615 }
616 else {
617 delete tableWidget->topLevelItem(index - pushedItems.count()); // NOLINT
618 }
619 }
620
621 /// deletes a given notification, errors or warnings by pointer
622 void deleteItem(NotificationItem* item)
623 {
624 for (int i = 0; i < count(); i++) {
625 if (getItem(i) == item) {
626 deleteItem(i);
627 return;
628 }
629 }
630 }
631
632 /// deletes the last Notification Item
633 void deleteLastItem()
634 {
635 deleteItem(count() - 1);
636 }
637
638 /// checks if last notification is the same
639 bool isSameNotification(const QString& notifiername, const QString& message, Base::LogStyle level) const
640 {
641 if (count() > 0) { // if not empty
642 // NOLINTNEXTLINE
643 auto item = static_cast<NotificationItem*>(getItem(0));
644 return item->isRepeated(level, notifiername, message);
645 }
646
647 return false;
648 }
649
650 void resetLastNotificationStatus()
651 {
652 // NOLINTNEXTLINE
653 auto item = static_cast<NotificationItem*>(getItem(0));
654 item->addRepetition();
655 }
656
657 /// pushes a notification item to the front
658 auto push_front(std::unique_ptr<NotificationItem> item)
659 {
660 auto it = item.release();
661 pushedItems.push_front(it);
662 return it;
663 }
664
665 QSize size()
666 {
667 return tableWidget->size();
668 }
669
670 protected:
671 /// creates the Notifications Widget
672 QWidget* createWidget(QWidget* parent) override
673 {
674 // NOLINTBEGIN
675 QWidget* notificationsWidget = new QWidget(parent);
676
677 QHBoxLayout* layout = new QHBoxLayout(notificationsWidget);
678 notificationsWidget->setLayout(layout);
679
680 tableWidget = new QTreeWidget(parent);
681 tableWidget->setColumnCount(3);
682
683 QStringList headers;
684 headers << QObject::tr("Type") << QObject::tr("Notifier") << QObject::tr("Message");
685 tableWidget->setHeaderLabels(headers);
686
687 layout->addWidget(tableWidget);
688
689 tableWidget->setMaximumSize(1200, 600);
690 tableWidget->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
691 tableWidget->header()->setStretchLastSection(false);
692 tableWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
693
694 tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
695 tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
696
697
698 // context menu on any item (row) of the widget
699 QObject::connect(tableWidget, &QTreeWidget::customContextMenuRequested, [&](const QPoint& pos) {
700 auto selectedItems = tableWidget->selectedItems();
701
702 QMenu menu;
703
704 QAction* del = menu.addAction(tr("Delete"), this, [&]() {
705 for (auto it : std::as_const(selectedItems)) {
706 delete it;
707 }
708 });
709
710 del->setEnabled(!selectedItems.isEmpty());
711
712 menu.addSeparator();
713
714 QAction* delnotifications = menu.addAction(
715 tr("Delete User Notifications"),
716 this,
717 &NotificationsAction::deleteNotifications
718 );
719
720 delnotifications->setEnabled(tableWidget->topLevelItemCount() > 0);
721
722 QAction* delall = menu.addAction(tr("Delete All"), this, &NotificationsAction::deleteAll);
723
724 delall->setEnabled(tableWidget->topLevelItemCount() > 0);
725
726 menu.setDefaultAction(del);
727
728 menu.exec(tableWidget->mapToGlobal(pos));
729 });
730 // NOLINTEND
731
732 return notificationsWidget;
733 }
734
735 private:
736 /// utility function to return the number of Notification Items meeting the functor/lambda
737 /// criteria
738 int getCurrently(std::function<bool(const NotificationItem*)> F) const
739 {
740 int instate = 0;
741 for (auto i = 0; i < tableWidget->topLevelItemCount(); i++) {
742 // NOLINTNEXTLINE
743 auto* item = static_cast<NotificationItem*>(tableWidget->topLevelItem(i));
744 if (F(item)) {
745 instate++;
746 }
747 }
748 for (auto i = 0; i < pushedItems.count(); i++) {
749 // NOLINTNEXTLINE
750 auto* item = static_cast<NotificationItem*>(pushedItems.at(i));
751 if (F(item)) {
752 instate++;
753 }
754 }
755 return instate;
756 }
757
758 private:
759 QTreeWidget* tableWidget = nullptr;
760 // Intermediate storage
761 // Note: QTreeWidget is helplessly slow to single insertions, QTreeWidget is actually only
762 // necessary when showing the widget. A single QList insertion into a QTreeWidget is actually
763 // not that slow. The use of this intermediate storage substantially accelerates non-intrusive
764 // notifications.
765 QList<QTreeWidgetItem*> pushedItems;
766 };
767
768 /************ Parameter Observer (preferences) **************************************/
769
770 NotificationArea::ParameterObserver::ParameterObserver(NotificationArea* notificationarea)
771 : notificationArea(notificationarea)
772 {
773 hGrp = App::GetApplication().GetParameterGroupByPath(
774 "User parameter:BaseApp/Preferences/NotificationArea"
775 );
776
777 // NOLINTBEGIN
778 parameterMap = {
779 {"NotificationAreaEnabled",
780 [this](const std::string& string) {
781 auto enabled = hGrp->GetBool(string.c_str(), true);
782 if (!enabled) {
783 notificationArea->deleteLater();
784 }
785 }},
786 {"NonIntrusiveNotificationsEnabled",
787 [this](const std::string& string) {
788 auto enabled = hGrp->GetBool(string.c_str(), true);
789 notificationArea->pImp->notificationsDisabled = !enabled;
790 }},
791 {"NotificationTime",
792 [this](const std::string& string) {
793 auto time = hGrp->GetInt(string.c_str(), 20) * 1000;
794 if (time < 0) {
795 time = 0;
796 }
797 notificationArea->pImp->notificationExpirationTime = static_cast<unsigned int>(time);
798 }},
799 {"MinimumOnScreenTime",
800 [this](const std::string& string) {
801 auto time = hGrp->GetInt(string.c_str(), 5) * 1000;
802 if (time < 0) {
803 time = 0;
804 }
805 notificationArea->pImp->minimumOnScreenTime = static_cast<unsigned int>(time);
806 }},
807 {"MaxOpenNotifications",
808 [this](const std::string& string) {
809 auto limit = hGrp->GetInt(string.c_str(), 15);
810 if (limit < 0) {
811 limit = 0;
812 }
813 notificationArea->pImp->maxOpenNotifications = static_cast<unsigned int>(limit);
814 }},
815 {"MaxWidgetMessages",
816 [this](const std::string& string) {
817 auto limit = hGrp->GetInt(string.c_str(), 1000);
818 if (limit < 0) {
819 limit = 0;
820 }
821 notificationArea->pImp->maxWidgetMessages = static_cast<unsigned int>(limit);
822 }},
823 {"AutoRemoveUserNotifications",
824 [this](const std::string& string) {
825 auto enabled = hGrp->GetBool(string.c_str(), true);
826 notificationArea->pImp->autoRemoveUserNotifications = enabled;
827 }},
828 {"NotificiationWidth",
829 [this](const std::string& string) {
830 auto width = hGrp->GetInt(string.c_str(), 800);
831 if (width < 300) {
832 width = 300;
833 }
834 notificationArea->pImp->notificationWidth = width;
835 }},
836 {"HideNonIntrusiveNotificationsWhenWindowDeactivated",
837 [this](const std::string& string) {
838 auto enabled = hGrp->GetBool(string.c_str(), true);
839 notificationArea->pImp->hideNonIntrusiveNotificationsWhenWindowDeactivated = enabled;
840 }},
841 {"PreventNonIntrusiveNotificationsWhenWindowNotActive",
842 [this](const std::string& string) {
843 auto enabled = hGrp->GetBool(string.c_str(), true);
844 notificationArea->pImp->preventNonIntrusiveNotificationsWhenWindowNotActive = enabled;
845 }},
846 {"DeveloperErrorSubscriptionEnabled",
847 [this](const std::string& string) {
848 auto enabled = hGrp->GetBool(string.c_str(), false);
849 notificationArea->pImp->developerErrorSubscriptionEnabled = enabled;
850 }},
851 {"DeveloperWarningSubscriptionEnabled", [this](const std::string& string) {
852 auto enabled = hGrp->GetBool(string.c_str(), false);
853 notificationArea->pImp->developerWarningSubscriptionEnabled = enabled;
854 }},
855 };
856 // NOLINTEND
857
858 for (auto& val : parameterMap) {
859 auto string = val.first;
860 auto update = val.second;
861
862 update(string);
863 }
864
865 hGrp->Attach(this);
866 }
867
868 NotificationArea::ParameterObserver::~ParameterObserver()
869 {
870 hGrp->Detach(this);
871 }
872
873 void NotificationArea::ParameterObserver::OnChange(Base::Subject<const char*>& rCaller, const char* sReason)
874 {
875 (void)rCaller;
876
877 auto key = parameterMap.find(sReason);
878
879 if (key != parameterMap.end()) {
880 auto string = key->first;
881 auto update = key->second;
882
883 update(string);
884 }
885 }
886
887 /************************* Notification Area *****************************************/
888
889 NotificationArea::NotificationArea(QWidget* parent)
890 : QPushButton(parent)
891 {
892 // QPushButton appearance
893 setText(QString());
894 setFlat(true);
895
896 // Initialisation of pImpl structure
897 pImp = std::make_unique<NotificationAreaP>();
898
899 pImp->observer = std::make_unique<NotificationAreaObserver>(this);
900 pImp->parameterObserver = std::make_unique<NotificationArea::ParameterObserver>(this);
901
902 pImp->menu = new QMenu(parent); // NOLINT
903 setMenu(pImp->menu);
904
905 auto na = new NotificationsAction(pImp->menu); // NOLINT
906
907 pImp->menu->addAction(na);
908
909 pImp->notificationaction = na;
910
911 // NOLINTBEGIN
912 // Signals for synchronisation of storage before showing/hiding the widget
913 QObject::connect(pImp->menu, &QMenu::aboutToHide, [&]() {
914 lock_guard<std::mutex> g(pImp->mutexNotification);
915 static_cast<NotificationsAction*>(pImp->notificationaction)->clearUnreadFlag();
916 static_cast<NotificationsAction*>(pImp->notificationaction)->shiftToCache();
917 });
918
919 QObject::connect(pImp->menu, &QMenu::aboutToShow, [this]() {
920 // guard to avoid modifying the notification list and indices while creating the tooltip
921 lock_guard<std::mutex> g(pImp->mutexNotification);
922 setText(QString::number(0)); // no unread notifications
923 if (pImp->missedNotifications) {
924 setIcon(TrayIcon::Normal);
925 pImp->missedNotifications = false;
926 }
927 static_cast<NotificationsAction*>(pImp->notificationaction)->synchroniseWidget();
928
929
930 // There is a Qt bug in not respecting a QMenu size when size changes in aboutToShow.
931 //
932 // https://bugreports.qt.io/browse/QTBUG-54421
933 // https://forum.qt.io/topic/68765/how-to-update-geometry-on-qaction-visibility-change-in-qmenu-abouttoshow/3
934 //
935 // None of this works
936 // pImp->menu->updateGeometry();
937 // pImp->menu->adjustSize();
938 // pImp->menu->ensurePolished();
939 // this->updateGeometry();
940 // this->adjustSize();
941 // this->ensurePolished();
942
943 // This does correct the size
944 QSize size = static_cast<NotificationsAction*>(pImp->notificationaction)->size();
945 QResizeEvent re(size, size);
946 qApp->sendEvent(pImp->menu, &re);
947
948 // This corrects the position of the menu
949 QTimer::singleShot(0, [&] {
950 QWidget* statusbar = static_cast<QWidget*>(this->parent());
951 QPoint statusbar_top_right = statusbar->mapToGlobal(statusbar->rect().topRight());
952 QSize menusize = pImp->menu->size();
953 QWidget* w = this;
954 QPoint button_pos = w->mapToGlobal(w->rect().topLeft());
955 QPoint widget_pos;
956 if ((statusbar_top_right.x() - menusize.width()) > button_pos.x()) {
957 widget_pos = QPoint(button_pos.x(), statusbar_top_right.y() - menusize.height());
958 }
959 else {
960 widget_pos = QPoint(
961 statusbar_top_right.x() - menusize.width(),
962 statusbar_top_right.y() - menusize.height()
963 );
964 }
965 pImp->menu->move(widget_pos);
966 });
967 });
968
969 // Connection to the finish restore signal to rearm Critical messages modal mode when action is
970 // user initiated
971 pImp->finishRestoreDocumentConnection = App::GetApplication().signalFinishRestoreDocument.connect(
972 std::bind(&Gui::NotificationArea::slotRestoreFinished, this, sp::_1)
973 );
974 // NOLINTEND
975
976 // Initialisation of the timer to inhibit continuous updates of the notification system in case
977 // clusters of messages arrive (so as to delay the actual notification until the whole cluster
978 // has arrived)
979 pImp->inhibitTimer.setSingleShot(true);
980
981 pImp->inhibitTimer.callOnTimeout([this, na]() {
982 setText(QString::number(na->getUnreadCount()));
983 showInNotificationArea();
984 });
985
986 setIcon(TrayIcon::Normal);
987 }
988
989 NotificationArea::~NotificationArea()
990 {
991 pImp->finishRestoreDocumentConnection.disconnect();
992 }
993
994 void NotificationArea::mousePressEvent(QMouseEvent* e)
995 {
996 // Contextual menu (e.g. to delete Notifications or all messages (Notifications, Errors,
997 // Warnings and Critical messages)
998 if (e->button() == Qt::RightButton && hitButton(e->pos())) {
999 QMenu menu;
1000
1001 // NOLINTBEGIN
1002 NotificationsAction* na = static_cast<NotificationsAction*>(pImp->notificationaction);
1003
1004 QAction* delnotifications = menu.addAction(tr("Delete User Notifications"), [&]() {
1005 // guard to avoid modifying the notification list and indices while creating the tooltip
1006 lock_guard<std::mutex> g(pImp->mutexNotification);
1007 na->deleteNotifications();
1008 setText(QString::number(na->getUnreadCount()));
1009 });
1010
1011 delnotifications->setEnabled(!na->isEmpty());
1012
1013 QAction* delall = menu.addAction(tr("Delete All"), [&]() {
1014 // guard to avoid modifying the notification list and indices while creating the tooltip
1015 lock_guard<std::mutex> g(pImp->mutexNotification);
1016 na->deleteAll();
1017 setText(QString::number(0));
1018 });
1019 // NOLINTEND
1020
1021 delall->setEnabled(!na->isEmpty());
1022
1023 menu.setDefaultAction(delall);
1024
1025 menu.exec(this->mapToGlobal(e->pos()));
1026 }
1027 QPushButton::mousePressEvent(e);
1028 }
1029
1030 bool NotificationArea::areDeveloperWarningsActive() const
1031 {
1032 return pImp->developerWarningSubscriptionEnabled;
1033 }
1034
1035 bool NotificationArea::areDeveloperErrorsActive() const
1036 {
1037 return pImp->developerErrorSubscriptionEnabled;
1038 }
1039
1040 void NotificationArea::pushNotification(
1041 const QString& notifiername,
1042 const QString& message,
1043 Base::LogStyle level
1044 )
1045 {
1046 auto confirmation = confirmationRequired(level);
1047
1048 if (confirmation) {
1049 showConfirmationDialog(notifiername, message);
1050 }
1051 // guard to avoid modifying the notification list and indices while creating the tooltip
1052 lock_guard<std::mutex> g(pImp->mutexNotification);
1053
1054 // NOLINTNEXTLINE
1055 NotificationsAction* na = static_cast<NotificationsAction*>(pImp->notificationaction);
1056
1057 // Limit the maximum number of messages stored in the widget (0 means no limit)
1058 if (pImp->maxWidgetMessages != 0 && na->count() > pImp->maxWidgetMessages) {
1059 na->deleteLastItem();
1060 }
1061
1062 auto repeated = na->isSameNotification(notifiername, message, level);
1063
1064 if (!repeated) {
1065 auto itemptr = std::make_unique<NotificationItem>(level, notifiername, message);
1066
1067 auto item = na->push_front(std::move(itemptr));
1068
1069 // If the non-intrusive notifications are disabled then stop here (messages added to the
1070 // widget only)
1071 if (pImp->notificationsDisabled) {
1072 item->setNotified(); // avoid mass of old notifications if feature is activated afterwards
1073 // NOLINTBEGIN
1074 setText(
1075 QString::number(
1076 static_cast<NotificationsAction*>(pImp->notificationaction)->getUnreadCount()
1077 )
1078 );
1079 return;
1080 // NOLINTEND
1081 }
1082 }
1083 else {
1084 na->resetLastNotificationStatus();
1085 }
1086
1087 // start or restart rate control (the timer is rearmed if not yet expired, expiration triggers
1088 // showing of the notification messages)
1089 //
1090 // NOTE: The inhibition timer is created in the main thread and cannot be restarted from another
1091 // QThread. A QTimer can be moved to another QThread (from the QThread in which it is). However,
1092 // it can only be create in a QThread, not in any other thread.
1093 //
1094 // For this reason, the timer is only triggered if this QThread is the QTimer thread.
1095 //
1096 // But I want my message from my thread to appear in the notification area. Fine, then configure
1097 // Console not to use the direct connection mode, but the Queued one:
1098 // Base::Console().setConnectionMode(ConnectionMode::Queued);
1099
1100 auto timer_thread = pImp->inhibitTimer.thread();
1101 auto current_thread = QThread::currentThread();
1102
1103 if (timer_thread == current_thread) {
1104 pImp->inhibitTimer.start(static_cast<int>(pImp->inhibitNotificationTime));
1105 }
1106 }
1107
1108 bool NotificationArea::confirmationRequired(Base::LogStyle level)
1109 {
1110 auto userInitiatedRestore = Application::Instance->testStatus(
1111 Gui::Application::UserInitiatedOpenDocument
1112 );
1113
1114 return (
1115 level == Base::LogStyle::Critical && userInitiatedRestore
1116 && pImp->requireConfirmationCriticalMessageDuringRestoring
1117 );
1118 }
1119
1120 void NotificationArea::showConfirmationDialog(const QString& notifiername, const QString& message)
1121 {
1122 auto confirmMsg = QObject::tr("Notifier:") + QStringLiteral(" ") + notifiername
1123 + QStringLiteral("\n\n") + message + QStringLiteral("\n\n")
1124 + QObject::tr("Skip confirmation of further critical message notifications "
1125 "while loading the file?");
1126
1127 auto button = QMessageBox::critical(
1128 getMainWindow()->activeWindow(),
1129 QObject::tr("Critical message"),
1130 confirmMsg,
1131 QMessageBox::Yes | QMessageBox::No,
1132 QMessageBox::No
1133 );
1134
1135 if (button == QMessageBox::Yes) {
1136 pImp->requireConfirmationCriticalMessageDuringRestoring = false;
1137 }
1138 }
1139
1140 void NotificationArea::showInNotificationArea()
1141 {
1142 // guard to avoid modifying the notification list and indices while creating the tooltip
1143 lock_guard<std::mutex> g(pImp->mutexNotification);
1144
1145 // NOLINTNEXTLINE
1146 NotificationsAction* na = static_cast<NotificationsAction*>(pImp->notificationaction);
1147
1148 if (!NotificationBox::isVisible()) {
1149 // The Notification Box may have been closed (by the user by popping it out or by left mouse
1150 // button) ensure that old notifications are not shown again, even if the timer has not
1151 // lapsed
1152 int i = 0;
1153 // NOLINTNEXTLINE
1154 while (i < na->count() && static_cast<NotificationItem*>(na->getItem(i))->isNotifying()) {
1155 // NOLINTNEXTLINE
1156 NotificationItem* item = static_cast<NotificationItem*>(na->getItem(i));
1157
1158 if (item->isShown()) {
1159 item->setNotified();
1160 item->resetShown();
1161 }
1162
1163 i++;
1164 }
1165 }
1166
1167 auto currentlyshown = na->getShownCount();
1168
1169 // If we cannot show more messages, we do no need to update the non-intrusive notification
1170 if (currentlyshown < pImp->maxOpenNotifications) {
1171 // There is space for at least one more notification
1172 // We update the message with the most recent up to maxOpenNotifications
1173
1174 QString msgw
1175 = QStringLiteral(
1176 "<style>p { margin: 0 0 0 0 } td { padding: 0 15px }</style> \
1177 <p style='white-space:normal'> \
1178 <table> \
1179 <tr> \
1180 <th><small>%1</small></th> \
1181 <th><small>%2</small></th> \
1182 <th><small>%3</small></th> \
1183 </tr>"
1184 )
1185 .arg(QObject::tr("Type"), QObject::tr("Notifier"), QObject::tr("Message"));
1186
1187 auto currentlynotifying = na->getCurrentlyNotifyingCount();
1188
1189 if (currentlynotifying > pImp->maxOpenNotifications) {
1190 msgw += QStringLiteral(
1191 " \
1192 <tr> \
1193 <td align='left'><img width=\"16\" height=\"16\" src=':/icons/Warning.svg'></td> \
1194 <td align='left'>FreeCAD</td> \
1195 <td align='left'>%1</td> \
1196 </tr>"
1197 )
1198 .arg(
1199 QObject::tr(
1200 "Too many opened non-intrusive notifications. Notifications "
1201 "are being omitted!"
1202 )
1203 );
1204 }
1205
1206 int i = 0;
1207
1208 // NOLINTNEXTLINE
1209 while (i < na->count() && static_cast<NotificationItem*>(na->getItem(i))->isNotifying()) {
1210
1211 if (i < pImp->maxOpenNotifications) { // show the first up to maxOpenNotifications
1212 // NOLINTNEXTLINE
1213 NotificationItem* item = static_cast<NotificationItem*>(na->getItem(i));
1214
1215 QString iconstr;
1216 if (item->isType(Base::LogStyle::Error)) {
1217 iconstr = QStringLiteral(":/icons/edit_Cancel.svg");
1218 }
1219 else if (item->isType(Base::LogStyle::Warning)) {
1220 iconstr = QStringLiteral(":/icons/Warning.svg");
1221 }
1222 else if (item->isType(Base::LogStyle::Critical)) {
1223 iconstr = QStringLiteral(":/icons/critical-info.svg");
1224 }
1225 else {
1226 iconstr = QStringLiteral(":/icons/info.svg");
1227 }
1228
1229 QString tmpmessage
1230 = convertFromPlainText(item->getMessage(), Qt::WhiteSpaceMode::WhiteSpaceNormal);
1231
1232 msgw += QStringLiteral(
1233 " \
1234 <tr> \
1235 <td align='left'><img width=\"16\" height=\"16\" src='%1'></td> \
1236 <td align='left'>%2</td> \
1237 <td align='left'>%3</td> \
1238 </tr>"
1239 )
1240 .arg(iconstr, item->getNotifier(), tmpmessage);
1241
1242 // start a timer for each of these notifications that was not previously shown
1243 if (!item->isShown()) {
1244 QTimer::singleShot(
1245 pImp->notificationExpirationTime,
1246 [this, item, repetitions = item->getRepetitions()]() {
1247 // guard to avoid modifying the notification
1248 // start index while creating the tooltip
1249 lock_guard<std::mutex> g(pImp->mutexNotification);
1250
1251 // if the item exists and the number of repetitions has not changed in
1252 // the meantime
1253 if (item && item->getRepetitions() == repetitions) {
1254 item->resetShown();
1255 item->setNotified();
1256
1257 if (pImp->autoRemoveUserNotifications) {
1258 if (item->isType(Base::LogStyle::Notification)) {
1259 // NOLINTNEXTLINE
1260 static_cast<NotificationsAction*>(pImp->notificationaction)
1261 ->deleteItem(item);
1262 }
1263 }
1264 }
1265 }
1266 );
1267 }
1268
1269 // We update the status to shown
1270 item->setShown();
1271 }
1272 else { // We do not have more space and older notifications will be too old
1273 // NOLINTBEGIN
1274 static_cast<NotificationItem*>(na->getItem(i))->setNotified();
1275 static_cast<NotificationItem*>(na->getItem(i))->resetShown();
1276 // NOLINTEND
1277 }
1278
1279 i++;
1280 }
1281
1282 msgw += QStringLiteral("</table></p>");
1283
1284 NotificationBox::Options options = NotificationBox::Options::RestrictAreaToReference;
1285
1286 if (pImp->preventNonIntrusiveNotificationsWhenWindowNotActive) {
1287 options = options | NotificationBox::Options::OnlyIfReferenceActive;
1288 }
1289
1290 if (pImp->hideNonIntrusiveNotificationsWhenWindowDeactivated) {
1291 options = options | NotificationBox::Options::HideIfReferenceWidgetDeactivated;
1292 }
1293
1294 bool isshown = NotificationBox::showText(
1295 this->mapToGlobal(QPoint()),
1296 msgw,
1297 getMainWindow(),
1298 static_cast<int>(pImp->notificationExpirationTime),
1299 pImp->minimumOnScreenTime,
1300 options,
1301 pImp->notificationWidth
1302 );
1303
1304 if (!isshown && !pImp->missedNotifications) {
1305 pImp->missedNotifications = true;
1306 setIcon(TrayIcon::MissedNotifications);
1307 }
1308 }
1309 }
1310
1311 void NotificationArea::slotRestoreFinished(const App::Document&)
1312 {
1313 // Re-arm on restore critical message modal notifications if another document is loaded
1314 pImp->requireConfirmationCriticalMessageDuringRestoring = true;
1315 }
1316
1317 void NotificationArea::setIcon(TrayIcon trayIcon)
1318 {
1319 if (trayIcon == TrayIcon::Normal) {
1320 QPushButton::setIcon(ResourceManager::NotificationAreaIcon());
1321 }
1322 else if (trayIcon == TrayIcon::MissedNotifications) {
1323 QPushButton::setIcon(ResourceManager::notificationAreaMissedNotificationsIcon());
1324 }
1325 }