Debian Codegraph @

src/Gui/Dialogs/DlgPreferencesImp.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /****************************************************************************
4 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
5 * Copyright (c) 2023 FreeCAD Project Association *
6 * *
7 * This file is part of FreeCAD. *
8 * *
9 * FreeCAD is free software: you can redistribute it and/or modify it *
10 * under the terms of the GNU Lesser General Public License as *
11 * published by the Free Software Foundation, either version 2.1 of the *
12 * License, or (at your option) any later version. *
13 * *
14 * FreeCAD is distributed in the hope that it will be useful, but *
15 * WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
17 * Lesser General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU Lesser General Public *
20 * License along with FreeCAD. If not, see *
21 * <https://www.gnu.org/licenses/>. *
22 * *
23 ***************************************************************************/
24
25 #include <algorithm>
26 #include <cstring>
27 #include <QAbstractButton>
28 #include <QApplication>
29 #include <QCheckBox>
30 #include <QCursor>
31 #include <QDebug>
32 #include <QFrame>
33 #include <QGroupBox>
34 #include <QLabel>
35 #include <QLineEdit>
36 #include <QListWidget>
37 #include <QMap>
38 #include <QMenu>
39 #include <QMessageBox>
40 #include <QRadioButton>
41 #include <QScreen>
42 #include <QScrollArea>
43 #include <QScrollBar>
44 #include <QTabWidget>
45 #include <QTimer>
46 #include <QToolButton>
47 #include <QToolTip>
48 #include <QProcess>
49 #include <QPushButton>
50 #include <QWindow>
51 #include <QKeyEvent>
52 #include <QFocusEvent>
53 #include <QMouseEvent>
54 #include <QPointer>
55 #include <QSet>
56 #include <QStyledItemDelegate>
57 #include <QPainter>
58
59 #include <App/Application.h>
60 #include <Base/Console.h>
61 #include <Base/Exception.h>
62 #include <Base/Tools.h>
63
64 #include "Dialogs/DlgPreferencesImp.h"
65 #include "ui_DlgPreferences.h"
66 #include "BitmapFactory.h"
67 #include "MainWindow.h"
68 #include "Tools.h"
69 #include "WidgetFactory.h"
70
71 using namespace Gui::Dialog;
72
73 // Simple delegate to render first line bold, second line normal
74 // used by search box
75 class MixedFontDelegate: public QStyledItemDelegate
76 {
77 static constexpr int horizontalPadding = 12;
78 static constexpr int verticalPadding = 4;
79
80 public:
81 explicit MixedFontDelegate(QObject* parent = nullptr)
82 : QStyledItemDelegate(parent)
83 {}
84
85 void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override
86 {
87 if (!index.isValid()) {
88 QStyledItemDelegate::paint(painter, option, index);
89 return;
90 }
91
92 QString pathText, widgetText;
93 extractTextData(index, pathText, widgetText);
94
95 if (pathText.isEmpty()) {
96 QStyledItemDelegate::paint(painter, option, index);
97 return;
98 }
99
100 QFont boldFont, normalFont;
101 createFonts(option.font, boldFont, normalFont);
102
103 LayoutInfo layout
104 = calculateLayout(pathText, widgetText, boldFont, normalFont, option.rect.width());
105
106 painter->save();
107
108 // draw selection background if selected
109 if (option.state & QStyle::State_Selected) {
110 painter->fillRect(option.rect, option.palette.highlight());
111 }
112
113 // Set text color based on selection
114 QColor textColor = (option.state & QStyle::State_Selected)
115 ? option.palette.highlightedText().color()
116 : option.palette.text().color();
117 painter->setPen(textColor);
118
119 // draw path in bold (Tab/Page) with wrapping
120 painter->setFont(boldFont);
121 QRect boldRect(
122 option.rect.left() + horizontalPadding,
123 option.rect.top() + verticalPadding,
124 layout.availableWidth,
125 layout.pathHeight
126 );
127 painter->drawText(boldRect, Qt::TextWordWrap | Qt::AlignTop, pathText);
128
129 // draw widget text in normal font (if present)
130 if (!widgetText.isEmpty()) {
131 painter->setFont(normalFont);
132 QRect normalRect(
133 option.rect.left() + horizontalPadding,
134 option.rect.top() + verticalPadding + layout.pathHeight,
135 layout.availableWidth,
136 layout.widgetHeight
137 );
138 painter->drawText(normalRect, Qt::TextWordWrap | Qt::AlignTop, widgetText);
139 }
140
141 painter->restore();
142 }
143
144 QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override
145 {
146 if (!index.isValid()) {
147 return QStyledItemDelegate::sizeHint(option, index);
148 }
149
150 QString pathText, widgetText;
151 extractTextData(index, pathText, widgetText);
152
153 if (pathText.isEmpty()) {
154 return QStyledItemDelegate::sizeHint(option, index);
155 }
156
157 QFont boldFont, normalFont;
158 createFonts(option.font, boldFont, normalFont);
159
160 LayoutInfo layout
161 = calculateLayout(pathText, widgetText, boldFont, normalFont, option.rect.width());
162
163 return {layout.totalWidth, layout.totalHeight};
164 }
165
166 private:
167 struct LayoutInfo
168 {
169 int availableWidth;
170 int pathHeight;
171 int widgetHeight;
172 int totalWidth;
173 int totalHeight;
174 };
175
176 void extractTextData(const QModelIndex& index, QString& pathText, QString& widgetText) const
177 {
178 // Use separate roles - all items should have proper role data
179 pathText = index.data(PreferencesSearchController::PathRole).toString();
180 widgetText = index.data(PreferencesSearchController::WidgetTextRole).toString();
181 }
182
183 void createFonts(const QFont& baseFont, QFont& boldFont, QFont& normalFont) const
184 {
185 boldFont = baseFont;
186 boldFont.setBold(true);
187 boldFont.setPointSize(boldFont.pointSize() - 1); // make header smaller like a subtitle
188
189 normalFont = baseFont; // keep widget text at normal size
190 }
191
192 LayoutInfo calculateLayout(
193 const QString& pathText,
194 const QString& widgetText,
195 const QFont& boldFont,
196 const QFont& normalFont,
197 int containerWidth
198 ) const
199 {
200
201 QFontMetrics boldFm(boldFont);
202 QFontMetrics normalFm(normalFont);
203
204 int availableWidth = containerWidth
205 - horizontalPadding * 2; // account for left and right padding
206 if (availableWidth <= 0) {
207 constexpr int defaultPopupWidth = 300;
208 availableWidth = defaultPopupWidth
209 - horizontalPadding * 2; // Fallback to popup width minus padding
210 }
211
212 // Calculate dimensions for path text (bold)
213 QRect pathBoundingRect
214 = boldFm.boundingRect(QRect(0, 0, availableWidth, 0), Qt::TextWordWrap, pathText);
215 int pathHeight = pathBoundingRect.height();
216 int pathWidth = pathBoundingRect.width();
217
218 // Calculate dimensions for widget text (normal font, if present)
219 int widgetHeight = 0;
220 int widgetWidth = 0;
221 if (!widgetText.isEmpty()) {
222 QRect widgetBoundingRect
223 = normalFm.boundingRect(QRect(0, 0, availableWidth, 0), Qt::TextWordWrap, widgetText);
224 widgetHeight = widgetBoundingRect.height();
225 widgetWidth = widgetBoundingRect.width();
226 }
227
228 int totalWidth = qMax(pathWidth, widgetWidth)
229 + horizontalPadding * 2; // +24 horizontal padding
230 int totalHeight = verticalPadding * 2 + pathHeight
231 + widgetHeight; // 8 vertical padding + content heights
232
233 LayoutInfo layout;
234 layout.availableWidth = availableWidth;
235 layout.pathHeight = pathHeight;
236 layout.widgetHeight = widgetHeight;
237 layout.totalWidth = totalWidth;
238 layout.totalHeight = totalHeight;
239 return layout;
240 }
241 };
242
243 bool isParentOf(const QModelIndex& parent, const QModelIndex& child)
244 {
245 for (auto it = child; it.isValid(); it = it.parent()) {
246 if (it == parent) {
247 return true;
248 }
249 }
250
251 return false;
252 }
253
254 QModelIndex findRootIndex(const QModelIndex& index)
255 {
256 auto root = index;
257
258 while (root.parent().isValid()) {
259 root = root.parent();
260 }
261
262 return root;
263 }
264
265 QWidget* PreferencesPageItem::getWidget() const
266 {
267 return _widget;
268 }
269
270 void PreferencesPageItem::setWidget(QWidget* widget)
271 {
272 if (_widget) {
273 _widget->setProperty(PropertyName, QVariant::fromValue<PreferencesPageItem*>(nullptr));
274 }
275
276 _widget = widget;
277 _widget->setProperty(PropertyName, QVariant::fromValue(this));
278 }
279
280 bool PreferencesPageItem::isExpanded() const
281 {
282 return _expanded;
283 }
284
285 void PreferencesPageItem::setExpanded(bool expanded)
286 {
287 _expanded = expanded;
288 }
289
290 // NOLINTBEGIN
291 Q_DECLARE_METATYPE(PreferencesPageItem*);
292
293 const int DlgPreferencesImp::GroupNameRole = Qt::UserRole + 1;
294 const int DlgPreferencesImp::PageNameRole = Qt::UserRole + 2;
295
296 /* TRANSLATOR Gui::Dialog::DlgPreferencesImp */
297
298 std::list<DlgPreferencesImp::TGroupPages> DlgPreferencesImp::_pages;
299 std::map<std::string, DlgPreferencesImp::Group> DlgPreferencesImp::_groupMap;
300
301 DlgPreferencesImp* DlgPreferencesImp::_activeDialog = nullptr;
302 // NOLINTEND
303
304 /**
305 * Constructs a DlgPreferencesImp which is a child of 'parent', with
306 * widget flags set to 'fl'
307 *
308 * The dialog will by default be modeless, unless you set 'modal' to
309 * true to construct a modal dialog.
310 */
311 DlgPreferencesImp::DlgPreferencesImp(QWidget* parent, Qt::WindowFlags fl)
312 : QDialog(parent, fl)
313 , ui(new Ui_DlgPreferences)
314 , invalidParameter(false)
315 , canEmbedScrollArea(true)
316 , restartRequired(false)
317 {
318 ui->setupUi(this);
319
320 // remove unused help button
321 setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
322
323 // Initialize search controller
324 m_searchController = std::make_unique<PreferencesSearchController>(this, this);
325
326 setupConnections();
327
328 ui->groupsTreeView->setModel(&_model);
329
330 // Configure search controller after UI setup
331 m_searchController->setPreferencesModel(&_model);
332 m_searchController->setGroupNameRole(GroupNameRole);
333 m_searchController->setPageNameRole(PageNameRole);
334
335 setupPages();
336
337 // Maintain a static pointer to the current active dialog (if there is one) so that
338 // if the static page manipulation functions are called while the dialog is showing
339 // it can update its content.
340 DlgPreferencesImp::_activeDialog = this;
341 }
342
343 /**
344 * Destroys the object and frees any allocated resources.
345 */
346 DlgPreferencesImp::~DlgPreferencesImp()
347 {
348 // Remove global event filter
349 qApp->removeEventFilter(this);
350
351 if (DlgPreferencesImp::_activeDialog == this) {
352 DlgPreferencesImp::_activeDialog = nullptr;
353 }
354 }
355
356 void DlgPreferencesImp::setupConnections()
357 {
358 connect(ui->buttonBox, &QDialogButtonBox::clicked, this, &DlgPreferencesImp::onButtonBoxClicked);
359 connect(ui->buttonBox, &QDialogButtonBox::helpRequested, getMainWindow(), &MainWindow::whatsThis);
360 connect(ui->groupsTreeView, &QTreeView::clicked, this, &DlgPreferencesImp::onPageSelected);
361 connect(ui->groupsTreeView, &QTreeView::expanded, this, &DlgPreferencesImp::onGroupExpanded);
362 connect(ui->groupsTreeView, &QTreeView::collapsed, this, &DlgPreferencesImp::onGroupCollapsed);
363 connect(ui->buttonReset, &QPushButton::clicked, this, &DlgPreferencesImp::showResetOptions);
364 connect(
365 ui->groupWidgetStack,
366 &QStackedWidget::currentChanged,
367 this,
368 &DlgPreferencesImp::onStackWidgetChange
369 );
370 // Connect search functionality to controller
371 connect(
372 ui->searchBox,
373 &QLineEdit::textChanged,
374 m_searchController.get(),
375 &PreferencesSearchController::onSearchTextChanged
376 );
377
378 // Connect navigation signal from controller to dialog
379 connect(
380 m_searchController.get(),
381 &PreferencesSearchController::navigationRequested,
382 this,
383 &DlgPreferencesImp::onNavigationRequested
384 );
385
386 // Install event filter on search box for arrow key navigation
387 ui->searchBox->installEventFilter(this);
388
389 // Install global event filter to handle clicks outside popup
390 qApp->installEventFilter(this);
391 }
392
393 void DlgPreferencesImp::setupPages()
394 {
395 // make sure that pages are ready to create
396 GetWidgetFactorySupplier();
397
398 for (const auto& [name, pages] : _pages) {
399 auto* group = createGroup(name);
400
401 for (const auto& page : pages) {
402 createPageInGroup(group, page);
403 }
404 }
405
406 updatePageDependentWidgets();
407 }
408
409 QPixmap DlgPreferencesImp::loadIconForGroup(const std::string& name) const
410 {
411 // normalize file name
412 auto normalizeName = [](std::string str) {
413 std::transform(str.begin(), str.end(), str.begin(), [](unsigned char ch) {
414 return ch == ' ' ? '_' : std::tolower(ch);
415 });
416 return str;
417 };
418
419 std::string fileName = normalizeName(name);
420 fileName = std::string("preferences-") + fileName;
421
422 const int px = 24;
423 QSize iconSize(px, px);
424 QPixmap icon = Gui::BitmapFactory().pixmapFromSvg(fileName.c_str(), iconSize);
425
426 if (icon.isNull()) {
427 icon = Gui::BitmapFactory().pixmap(fileName.c_str());
428 if (icon.isNull()) {
429 qWarning() << "No group icon found for " << fileName.c_str();
430 }
431 else if (icon.size() != iconSize) {
432 icon = icon.scaled(iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
433 }
434 }
435
436 return icon;
437 }
438
439 /**
440 * Create the necessary widgets for a new group named \a groupName. Returns a
441 * pointer to the group's SettingsPageItem: that widget's lifetime is managed by the
442 * QStandardItemModel, do not manually deallocate.
443 */
444 PreferencesPageItem* DlgPreferencesImp::createGroup(const std::string& groupName)
445 {
446 QString groupNameQString = QString::fromStdString(groupName);
447
448 std::string iconName;
449
450 QString tooltip;
451 getGroupData(groupName, iconName, tooltip);
452
453 auto groupPages = new QStackedWidget;
454 groupPages->setProperty(GroupNameProperty, QVariant(groupNameQString));
455
456 connect(groupPages, &QStackedWidget::currentChanged, this, &DlgPreferencesImp::onStackWidgetChange);
457
458
459 if (ui->groupWidgetStack->count() > 0) {
460 groupPages->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
461 }
462 ui->groupWidgetStack->addWidget(groupPages);
463
464 auto item = new PreferencesPageItem;
465
466 item->setData(QVariant(groupNameQString), GroupNameRole);
467 item->setText(QObject::tr(groupNameQString.toLatin1()));
468 item->setToolTip(tooltip);
469 item->setIcon(loadIconForGroup(iconName));
470 item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
471 item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
472 item->setWidget(groupPages);
473 item->setSelectable(false);
474
475 _model.invisibleRootItem()->appendRow(item);
476
477 return item;
478 }
479
480
481 PreferencePage* DlgPreferencesImp::createPreferencePage(
482 const std::string& pageName,
483 const std::string& groupName
484 )
485 {
486 PreferencePage* page = WidgetFactory().createPreferencePage(pageName.c_str());
487
488 if (!page) {
489 return nullptr;
490 }
491
492 auto resetMargins = [](QWidget* widget) {
493 widget->setContentsMargins(0, 0, 0, 0);
494 if (auto layout = widget->layout()) {
495 layout->setContentsMargins(0, 0, 0, 0);
496 }
497 };
498
499 // settings layout already takes care for margins, we need to reset everything to 0
500 resetMargins(page);
501
502 // special handling for PreferenceUiForm to reset margins for forms too
503 if (auto uiFormPage = qobject_cast<PreferenceUiForm*>(page)) {
504 resetMargins(uiFormPage->form());
505 }
506
507 page->setProperty(GroupNameProperty, QString::fromStdString(groupName));
508 page->setProperty(PageNameProperty, QString::fromStdString(pageName));
509
510 return page;
511 }
512
513 /**
514 * Create a new preference page called \a pageName in the group \a groupItem.
515 */
516 void DlgPreferencesImp::createPageInGroup(PreferencesPageItem* groupItem, const std::string& pageName)
517 {
518 try {
519 PreferencePage* page
520 = createPreferencePage(pageName, groupItem->data(GroupNameRole).toString().toStdString());
521
522 if (!page) {
523 Base::Console().warning("%s is not a preference page\n", pageName.c_str());
524 return;
525 }
526
527 auto pageItem = new PreferencesPageItem;
528
529 pageItem->setText(page->windowTitle());
530 pageItem->setEditable(false);
531 pageItem->setData(groupItem->data(GroupNameRole), GroupNameRole);
532 pageItem->setData(QString::fromStdString(pageName), PageNameRole);
533 pageItem->setWidget(page);
534
535 groupItem->appendRow(pageItem);
536
537 page->loadSettings();
538
539 auto pages = qobject_cast<QStackedWidget*>(groupItem->getWidget());
540
541 if (pages->count() > 0) {
542 page->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
543 }
544
545 pages->addWidget(page);
546 addSizeHint(page);
547 }
548 catch (const Base::Exception& e) {
549 Base::Console().error("Base exception thrown for '%s'\n", pageName.c_str());
550 e.reportException();
551 }
552 catch (const std::exception& e) {
553 Base::Console().error("C++ exception thrown for '%s' (%s)\n", pageName.c_str(), e.what());
554 }
555 }
556
557 void DlgPreferencesImp::addSizeHint(QWidget* page)
558 {
559 _sizeHintOfPages = _sizeHintOfPages.expandedTo(page->minimumSizeHint());
560 }
561
562 int DlgPreferencesImp::minimumPageWidth() const
563 {
564 return _sizeHintOfPages.width();
565 }
566
567 int DlgPreferencesImp::minimumDialogWidth(int pageWidth) const
568 {
569 // this is additional safety spacing to ensure that everything fits with scrollbar etc.
570 const auto additionalMargin = style()->pixelMetric(QStyle::PM_ScrollBarExtent) + 8;
571
572 QSize tree = ui->groupsTreeView->sizeHint();
573 return pageWidth + tree.width() + additionalMargin;
574 }
575
576 void DlgPreferencesImp::updatePageDependentWidgets()
577 {
578 auto currentPageItem = getCurrentPage();
579
580 // update header of the page
581 ui->headerLabel->setText(currentPageItem->text());
582
583 // reset scroll area to start position
584 ui->scrollArea->horizontalScrollBar()->setValue(0);
585 ui->scrollArea->verticalScrollBar()->setValue(0);
586 }
587
588 /**
589 * Adds a preference page with its class name \a className and
590 * the group \a group it belongs to. To create this page it must
591 * be registered in the WidgetFactory.
592 * @see WidgetFactory
593 * @see PrefPageProducer
594 */
595 void DlgPreferencesImp::addPage(const std::string& className, const std::string& group)
596 {
597 auto groupToAddTo = _pages.end();
598 for (auto it = _pages.begin(); it != _pages.end(); ++it) {
599 if (it->first == group) {
600 groupToAddTo = it;
601 break;
602 }
603 }
604
605 if (groupToAddTo != _pages.end()) {
606 // The group exists: add this page to the end of the list
607 groupToAddTo->second.push_back(className);
608 }
609 else {
610 // This is a new group: create it, with its one page
611 std::list<std::string> pages;
612 pages.push_back(className);
613 _pages.emplace_back(group, pages);
614 }
615
616 if (DlgPreferencesImp::_activeDialog) {
617 // If the dialog is currently showing, tell it to insert the new page
618 _activeDialog->reloadPages();
619 }
620 }
621
622 void DlgPreferencesImp::removePage(const std::string& className, const std::string& group)
623 {
624 for (auto it = _pages.begin(); it != _pages.end(); ++it) {
625 if (it->first == group) {
626 if (className.empty()) {
627 _pages.erase(it);
628 return;
629 }
630
631 std::list<std::string>& p = it->second;
632 for (auto jt = p.begin(); jt != p.end(); ++jt) {
633 if (*jt == className) {
634 p.erase(jt);
635 if (p.empty()) {
636 _pages.erase(it);
637 }
638 return;
639 }
640 }
641 }
642 }
643 }
644
645 /**
646 * Sets a custom icon name or tool tip for a given group.
647 */
648 void DlgPreferencesImp::setGroupData(const std::string& name, const std::string& icon, const QString& tip)
649 {
650 Group group;
651 group.iconName = icon;
652 group.tooltip = tip;
653 _groupMap[name] = group;
654 }
655
656 /**
657 * Gets the icon name or tool tip for a given group. If no custom name or tool tip is given
658 * they are determined from the group name.
659 */
660 void DlgPreferencesImp::getGroupData(const std::string& group, std::string& icon, QString& tip)
661 {
662 auto it = _groupMap.find(group);
663
664 if (it != _groupMap.end()) {
665 icon = it->second.iconName;
666 tip = it->second.tooltip;
667 }
668
669 if (icon.empty()) {
670 icon = group;
671 }
672
673 if (tip.isEmpty()) {
674 tip = QObject::tr(group.c_str());
675 }
676 }
677
678 /**
679 * Activates the page at position \a index of the group with name \a group.
680 */
681 void DlgPreferencesImp::activateGroupPage(const QString& group, int index)
682 {
683 for (int i = 0; i < ui->groupWidgetStack->count(); i++) {
684 auto* pageStackWidget = qobject_cast<QStackedWidget*>(ui->groupWidgetStack->widget(i));
685
686 if (!pageStackWidget) {
687 continue;
688 }
689
690 if (pageStackWidget->property(GroupNameProperty).toString() == group) {
691 ui->groupWidgetStack->setCurrentWidget(pageStackWidget);
692 pageStackWidget->setCurrentIndex(index);
693
694 updatePageDependentWidgets();
695
696 return;
697 }
698 }
699 }
700
701 /**
702 * Activates the page with name \a pageName of the group with name \a group.
703 */
704 void DlgPreferencesImp::activateGroupPageByPageName(const QString& group, const QString& pageName)
705 {
706
707 for (int i = 0; i < ui->groupWidgetStack->count(); i++) {
708 auto* pageStackWidget = qobject_cast<QStackedWidget*>(ui->groupWidgetStack->widget(i));
709
710 if (!pageStackWidget) {
711 continue;
712 }
713
714 if (pageStackWidget->property(GroupNameProperty).toString() == group) {
715 ui->groupWidgetStack->setCurrentWidget(pageStackWidget);
716 for (int pageIdx = 0; pageIdx < pageStackWidget->count(); pageIdx++) {
717 auto page = qobject_cast<PreferencePage*>(pageStackWidget->widget(pageIdx));
718 if (page) {
719 if (page->property(PageNameProperty).toString() == pageName) {
720 pageStackWidget->setCurrentIndex(pageIdx);
721 break;
722 }
723 }
724 }
725
726 updatePageDependentWidgets();
727
728 return;
729 }
730 }
731 }
732
733 /**
734 * Returns the group name \a group and position \a index of the active page.
735 */
736 void DlgPreferencesImp::activeGroupPage(QString& group, int& index) const
737 {
738 auto groupWidget = qobject_cast<QStackedWidget*>(ui->groupWidgetStack->currentWidget());
739
740 if (groupWidget) {
741 group = groupWidget->property(GroupNameProperty).toString();
742 index = groupWidget->currentIndex();
743 }
744 }
745
746 void DlgPreferencesImp::accept()
747 {
748 this->invalidParameter = false;
749
750 applyChanges();
751
752 if (!this->invalidParameter) {
753 QDialog::accept();
754 restartIfRequired();
755 }
756 }
757
758 void DlgPreferencesImp::reject()
759 {
760 QDialog::reject();
761 restartIfRequired();
762 }
763
764 void DlgPreferencesImp::onButtonBoxClicked(QAbstractButton* btn)
765 {
766 if (ui->buttonBox->standardButton(btn) == QDialogButtonBox::Apply) {
767 applyChanges();
768 }
769 }
770
771 void DlgPreferencesImp::showResetOptions()
772 {
773 QMenu menu(this);
774
775 auto currentPageItem = getCurrentPage();
776 auto currentGroupItem = static_cast<PreferencesPageItem*>(currentPageItem->parent());
777
778 auto pageText = currentPageItem->text();
779 auto groupText = currentGroupItem->text();
780
781 // Reset per page
782 QAction* pageAction = menu.addAction(tr("Reset Page '%1'").arg(pageText), this, [&] {
783 restorePageDefaults(currentPageItem);
784 });
785 pageAction->setToolTip(tr("Resets the user settings for the page '%1'").arg(pageText));
786
787 // Reset per group
788 QAction* groupAction = menu.addAction(
789 tr("Reset Group '%1'").arg(groupText),
790
791 this,
792 [&] { restorePageDefaults(static_cast<PreferencesPageItem*>(currentPageItem->parent())); }
793 );
794 groupAction->setToolTip(tr("Resets the user settings for the group '%1'").arg(groupText));
795
796 // Reset all
797 QAction* allAction = menu.addAction(tr("Reset All"), this, &DlgPreferencesImp::restoreDefaults);
798
799 allAction->setToolTip(tr("Resets the user settings entirely"));
800
801 connect(&menu, &QMenu::hovered, [&menu](QAction* hover) {
802 QPoint pos = menu.pos();
803 const int pad = 10;
804 pos.rx() += menu.width() + pad;
805 QToolTip::showText(pos, hover->toolTip());
806 });
807
808 menu.exec(QCursor::pos());
809 }
810
811 void DlgPreferencesImp::restoreDefaults()
812 {
813 QMessageBox box(this);
814 box.setIcon(QMessageBox::Question);
815 box.setWindowTitle(tr("Clear User Settings"));
816 box.setText(tr("Clear all your user settings?"));
817 box.setInformativeText(tr("All settings will be cleared."));
818 box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
819 box.setDefaultButton(QMessageBox::No);
820
821 if (box.exec() == QMessageBox::Yes) {
822 // keep this parameter
823 bool saveParameter = App::GetApplication()
824 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
825 ->GetBool("SaveUserParameter", true);
826
827 ParameterManager* mgr = App::GetApplication().GetParameterSet("User parameter");
828 mgr->Clear();
829
830 App::GetApplication()
831 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
832 ->SetBool("SaveUserParameter", saveParameter);
833
834 reject();
835 }
836 }
837 /**
838 * If the dialog is currently showing and the static variable _pages changed, this function
839 * will rescan that list of pages and add any that are new to the current dialog. It will not
840 * remove any pages that are no longer in the list, and will not change the user's current
841 * active page.
842 */
843 void DlgPreferencesImp::reloadPages()
844 {
845 // Make sure that pages are ready to create
846 GetWidgetFactorySupplier();
847
848 for (const auto& [group, pages] : _pages) {
849 QString groupName = QString::fromStdString(group);
850
851 // First, does this group already exist?
852 PreferencesPageItem* groupItem = nullptr;
853
854 auto root = _model.invisibleRootItem();
855 for (int i = 0; i < root->rowCount(); i++) {
856 auto currentGroupItem = static_cast<PreferencesPageItem*>(root->child(i));
857 auto currentGroupName = currentGroupItem->data(GroupNameRole).toString();
858
859 if (currentGroupName == groupName) {
860 groupItem = currentGroupItem;
861 break;
862 }
863 }
864
865 // This is a new group that wasn't there when we started this instance of the dialog:
866 if (!groupItem) {
867 groupItem = createGroup(group);
868 }
869
870 // Move on to the pages in the group to see if we need to add any
871 for (const auto& page : pages) {
872 // Does this page already exist?
873 QString pageName = QString::fromStdString(page);
874
875 bool pageExists = false;
876
877 for (int i = 0; i < groupItem->rowCount(); i++) {
878 auto currentPageItem = static_cast<PreferencesPageItem*>(groupItem->child(i));
879
880 if (currentPageItem->data(PageNameRole).toString() == pageName) {
881 pageExists = true;
882 break;
883 }
884 }
885
886 // This is a new page that wasn't there when we started this instance of the dialog:
887 if (!pageExists) {
888 createPageInGroup(groupItem, page);
889 }
890 }
891 }
892 }
893
894 void DlgPreferencesImp::applyChanges()
895 {
896 // Checks if any of the classes that represent several pages of settings
897 // (DlgSettings*.*) implement checkSettings() method. If any of them do,
898 // call it to validate if user input is correct. If something fails (i.e.,
899 // not correct), shows a messageBox and set this->invalidParameter = true to
900 // cancel further operation in other methods (like in accept()).
901
902 for (int i = 0; i < ui->groupWidgetStack->count(); i++) {
903 auto pagesStackWidget = qobject_cast<QStackedWidget*>(ui->groupWidgetStack->widget(i));
904
905 for (int j = 0; j < pagesStackWidget->count(); j++) {
906 QWidget* page = pagesStackWidget->widget(j);
907
908 int index = page->metaObject()->indexOfMethod("checkSettings()");
909
910 if (index >= 0) {
911 try {
912 page->qt_metacall(QMetaObject::InvokeMetaMethod, index, nullptr);
913 }
914 catch (const Base::Exception& e) {
915 ui->groupWidgetStack->setCurrentIndex(i);
916 pagesStackWidget->setCurrentIndex(j);
917
918 QMessageBox::warning(this, tr("Wrong parameter"), QString::fromLatin1(e.what()));
919
920 this->invalidParameter = true;
921
922 // exit early due to found errors
923 return;
924 }
925 }
926 }
927 }
928
929 // If everything is ok (i.e., no validation problem), call method
930 // saveSettings() in every subpage (DlgSetting*) object.
931 for (int i = 0; i < ui->groupWidgetStack->count(); i++) {
932 auto pageStackWidget = qobject_cast<QStackedWidget*>(ui->groupWidgetStack->widget(i));
933
934 for (int j = 0; j < pageStackWidget->count(); j++) {
935 auto page = qobject_cast<PreferencePage*>(pageStackWidget->widget(j));
936
937 if (page) {
938 page->saveSettings();
939 restartRequired = restartRequired || page->isRestartRequired();
940 }
941 }
942 }
943
944 bool saveParameter = App::GetApplication()
945 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
946 ->GetBool("SaveUserParameter", true);
947
948 if (saveParameter) {
949 ParameterManager* parmgr = App::GetApplication().GetParameterSet("User parameter");
950 parmgr->SaveDocument(App::Application::Config()["UserParameter"].c_str());
951 }
952 }
953
954 void DlgPreferencesImp::restartIfRequired()
955 {
956 if (restartRequired) {
957 QMessageBox restartBox(parentWidget()); // current window likely already closed, cant
958 // parent to it
959
960 restartBox.setIcon(QMessageBox::Warning);
961 restartBox.setWindowTitle(tr("Restart Required"));
962 restartBox.setText(tr("Restart FreeCAD for changes to take effect."));
963 restartBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
964 restartBox.setDefaultButton(QMessageBox::Cancel);
965 auto okBtn = restartBox.button(QMessageBox::Ok);
966 auto cancelBtn = restartBox.button(QMessageBox::Cancel);
967 okBtn->setText(tr("Restart Now"));
968 cancelBtn->setText(tr("Restart Later"));
969
970 int exec = restartBox.exec();
971
972 if (exec == QMessageBox::Ok) {
973 // restart FreeCAD after a delay to give time to this dialog to close
974 const int ms = 1000;
975 QTimer::singleShot(ms, []() {
976 QStringList args = QApplication::arguments();
977 args.pop_front();
978 if (getMainWindow()->close()) {
979 QProcess::startDetached(QApplication::applicationFilePath(), args);
980 }
981 });
982 }
983 }
984 }
985
986 void DlgPreferencesImp::showEvent(QShowEvent* ev)
987 {
988 QDialog::showEvent(ev);
989
990 auto screen = windowHandle()->screen();
991 auto availableSize = screen->availableSize();
992
993 // leave some portion of height so preferences window does not take
994 // entire screen height. User will still be able to resize the window,
995 // but it should never start too tall.
996 auto maxStartHeight = availableSize.height() - minVerticalEmptySpace;
997
998 if (height() > maxStartHeight) {
999 auto heightDifference = availableSize.height() - maxStartHeight;
1000
1001 // resize and reposition window so it is fully visible
1002 resize(width(), maxStartHeight);
1003 move(x(), heightDifference / 2);
1004 }
1005
1006 expandToMinimumDialogWidth();
1007 }
1008
1009 void DlgPreferencesImp::expandToMinimumDialogWidth()
1010 {
1011 auto screen = windowHandle()->screen();
1012 auto availableSize = screen->availableSize();
1013
1014 int mw = minimumDialogWidth(minimumPageWidth());
1015 // expand dialog to minimum size required but do not use more than specified width portion
1016 resize(std::min(int(maxScreenWidthCoveragePercent * availableSize.width()), mw), height());
1017 }
1018
1019 void DlgPreferencesImp::onPageSelected(const QModelIndex& index)
1020 {
1021 auto* currentItem = static_cast<PreferencesPageItem*>(_model.itemFromIndex(index));
1022
1023 if (currentItem->hasChildren()) {
1024 auto pageIndex = currentItem->child(0)->index();
1025
1026 ui->groupsTreeView->selectionModel()->select(pageIndex, QItemSelectionModel::ClearAndSelect);
1027
1028 onPageSelected(pageIndex);
1029
1030 return;
1031 }
1032
1033 auto groupIndex = findRootIndex(index);
1034
1035 auto* groupItem = static_cast<PreferencesPageItem*>(_model.itemFromIndex(groupIndex));
1036 auto* pagesStackWidget = static_cast<QStackedWidget*>(groupItem->getWidget());
1037
1038 ui->groupWidgetStack->setCurrentWidget(groupItem->getWidget());
1039
1040 if (index != groupIndex) {
1041 pagesStackWidget->setCurrentIndex(index.row());
1042 }
1043
1044 updatePageDependentWidgets();
1045 }
1046
1047 void DlgPreferencesImp::onGroupExpanded(const QModelIndex& index)
1048 {
1049 auto root = findRootIndex(index);
1050
1051 auto* groupItem = static_cast<PreferencesPageItem*>(_model.itemFromIndex(root));
1052
1053 groupItem->setExpanded(true);
1054 }
1055
1056 void DlgPreferencesImp::onGroupCollapsed(const QModelIndex& index)
1057 {
1058 auto root = findRootIndex(index);
1059
1060 auto* groupItem = static_cast<PreferencesPageItem*>(_model.itemFromIndex(root));
1061
1062 groupItem->setExpanded(false);
1063 }
1064
1065 void DlgPreferencesImp::onStackWidgetChange(int index)
1066 {
1067 auto stack = qobject_cast<QStackedWidget*>(sender());
1068
1069 for (int i = 0; i < stack->count(); i++) {
1070 auto current = stack->widget(i);
1071 current->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
1072 }
1073
1074 if (auto selected = stack->widget(index)) {
1075 selected->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
1076 }
1077
1078 auto currentItem = getCurrentPage();
1079
1080 if (!currentItem) {
1081 return;
1082 }
1083
1084 auto currentIndex = currentItem->index();
1085
1086 auto root = _model.invisibleRootItem();
1087 for (int i = 0; i < root->rowCount(); i++) {
1088 auto currentGroup = static_cast<PreferencesPageItem*>(root->child(i));
1089 auto currentGroupIndex = currentGroup->index();
1090
1091 // don't do anything to group of selected item
1092 if (isParentOf(currentGroupIndex, currentIndex)) {
1093 continue;
1094 }
1095
1096 if (!currentGroup->isExpanded()) {
1097 ui->groupsTreeView->collapse(currentGroupIndex);
1098 }
1099 }
1100
1101 auto parentItem = currentItem;
1102 while ((parentItem = static_cast<PreferencesPageItem*>(parentItem->parent()))) {
1103 bool wasExpanded = parentItem->isExpanded();
1104 ui->groupsTreeView->expand(parentItem->index());
1105 parentItem->setExpanded(wasExpanded);
1106 }
1107
1108 ui->groupsTreeView->selectionModel()->select(currentIndex, QItemSelectionModel::ClearAndSelect);
1109 }
1110
1111 void DlgPreferencesImp::onNavigationRequested(const QString& groupName, const QString& pageName)
1112 {
1113 navigateToSearchResult(groupName, pageName);
1114 }
1115
1116 void DlgPreferencesImp::navigateToSearchResult(const QString& groupName, const QString& pageName)
1117 {
1118 // Find the group and page items
1119 auto root = _model.invisibleRootItem();
1120 for (int i = 0; i < root->rowCount(); i++) {
1121 auto groupItem = static_cast<PreferencesPageItem*>(root->child(i));
1122 if (groupItem->data(GroupNameRole).toString() == groupName) {
1123
1124 // Find the specific page
1125 for (int j = 0; j < groupItem->rowCount(); j++) {
1126 auto pageItem = static_cast<PreferencesPageItem*>(groupItem->child(j));
1127 if (pageItem->data(PageNameRole).toString() == pageName) {
1128
1129 // Expand the group if needed
1130 ui->groupsTreeView->expand(groupItem->index());
1131
1132 // Select the page
1133 ui->groupsTreeView->selectionModel()->select(
1134 pageItem->index(),
1135 QItemSelectionModel::ClearAndSelect
1136 );
1137
1138 // Navigate to the page
1139 onPageSelected(pageItem->index());
1140
1141 return;
1142 }
1143 }
1144
1145 // If no specific page found, just navigate to the group
1146 ui->groupsTreeView->selectionModel()->select(
1147 groupItem->index(),
1148 QItemSelectionModel::ClearAndSelect
1149 );
1150 onPageSelected(groupItem->index());
1151 return;
1152 }
1153 }
1154 }
1155
1156 void DlgPreferencesImp::changeEvent(QEvent* e)
1157 {
1158 if (e->type() == QEvent::LanguageChange) {
1159 ui->retranslateUi(this);
1160
1161 auto root = _model.invisibleRootItem();
1162 for (int i = 0; i < root->rowCount(); i++) {
1163 auto groupItem = static_cast<PreferencesPageItem*>(root->child(i));
1164 auto groupName = groupItem->data(GroupNameRole).toString();
1165
1166 groupItem->setText(QObject::tr(groupName.toLatin1()));
1167
1168 for (int j = 0; j < groupItem->rowCount(); j++) {
1169 auto pageModelItem = static_cast<PreferencesPageItem*>(groupItem->child(j));
1170 auto pageModelWidget = static_cast<PreferencePage*>(pageModelItem->getWidget());
1171
1172 pageModelItem->setText(pageModelWidget->windowTitle());
1173 }
1174 }
1175
1176 expandToMinimumDialogWidth();
1177 updatePageDependentWidgets();
1178 }
1179 else {
1180 QWidget::changeEvent(e);
1181 }
1182 }
1183
1184 void DlgPreferencesImp::reload()
1185 {
1186 for (int i = 0; i < ui->groupWidgetStack->count(); i++) {
1187 auto pageStackWidget = static_cast<QStackedWidget*>(ui->groupWidgetStack->widget(i));
1188
1189 for (int j = 0; j < pageStackWidget->count(); j++) {
1190 auto page = qobject_cast<PreferencePage*>(pageStackWidget->widget(j));
1191
1192 if (page) {
1193 page->loadSettings();
1194 }
1195 }
1196 }
1197
1198 applyChanges();
1199 }
1200
1201 void DlgPreferencesImp::restorePageDefaults(PreferencesPageItem* item)
1202 {
1203 if (item->hasChildren()) {
1204 // If page has children iterate over them and restore each
1205 for (int i = 0; i < item->rowCount(); i++) {
1206 auto child = static_cast<PreferencesPageItem*>(item->child(i));
1207
1208 restorePageDefaults(child);
1209 }
1210 }
1211 else {
1212 auto* page = qobject_cast<PreferencePage*>(item->getWidget());
1213
1214 page->resetSettingsToDefaults();
1215 /**
1216 * Let's save the restart request before the page object is deleted and replaced with
1217 * the newPage object (which has restartRequired initialized to false)
1218 */
1219 restartRequired = restartRequired || page->isRestartRequired();
1220
1221 std::string pageName = page->property(PageNameProperty).toString().toStdString();
1222 std::string groupName = page->property(GroupNameProperty).toString().toStdString();
1223
1224 auto newPage = createPreferencePage(pageName, groupName);
1225
1226 newPage->loadSettings();
1227
1228 auto groupPageStack = qobject_cast<QStackedWidget*>(page->parentWidget());
1229 auto replacedWidgetIndex = groupPageStack->indexOf(page);
1230 auto currentWidgetIndex = groupPageStack->currentIndex();
1231
1232 groupPageStack->removeWidget(page);
1233 groupPageStack->insertWidget(replacedWidgetIndex, newPage);
1234
1235 item->setWidget(newPage);
1236
1237 if (replacedWidgetIndex == currentWidgetIndex) {
1238 groupPageStack->setCurrentIndex(currentWidgetIndex);
1239 }
1240 }
1241 }
1242
1243 PreferencesPageItem* DlgPreferencesImp::getCurrentPage() const
1244 {
1245 auto groupPagesStack = qobject_cast<QStackedWidget*>(ui->groupWidgetStack->currentWidget());
1246
1247 if (!groupPagesStack) {
1248 return nullptr;
1249 }
1250
1251 auto pageWidget = qobject_cast<PreferencePage*>(groupPagesStack->currentWidget());
1252
1253 if (!pageWidget) {
1254 return nullptr;
1255 }
1256
1257 return pageWidget->property(PreferencesPageItem::PropertyName).value<PreferencesPageItem*>();
1258 }
1259
1260 // PreferencesSearchController implementation
1261 PreferencesSearchController::PreferencesSearchController(DlgPreferencesImp* parentDialog, QObject* parent)
1262 : QObject(parent)
1263 , m_parentDialog(parentDialog)
1264 , m_preferencesModel(nullptr)
1265 , m_groupNameRole(0)
1266 , m_pageNameRole(0)
1267 , m_searchBox(nullptr)
1268 , m_searchResultsList(nullptr)
1269 {
1270 // Get reference to search box from parent dialog's UI
1271 m_searchBox = m_parentDialog->ui->searchBox;
1272
1273 // Create the search results popup list
1274 m_searchResultsList = new QListWidget(m_parentDialog);
1275 m_searchResultsList->setWindowFlags(
1276 Qt::ToolTip | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint
1277 );
1278 m_searchResultsList->setVisible(false);
1279 m_searchResultsList->setMinimumWidth(300);
1280 m_searchResultsList->setMaximumHeight(400); // Increased max height
1281 m_searchResultsList->setFrameStyle(QFrame::Box | QFrame::Raised);
1282 m_searchResultsList->setLineWidth(1);
1283 m_searchResultsList->setFocusPolicy(Qt::NoFocus); // Don't steal focus from search box
1284 m_searchResultsList->setAttribute(Qt::WA_ShowWithoutActivating); // Show without
1285 // activating/stealing focus
1286 m_searchResultsList->setWordWrap(true); // Enable word wrapping
1287 m_searchResultsList->setTextElideMode(Qt::ElideNone); // Don't elide text, let it wrap instead
1288 m_searchResultsList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Disable horizontal
1289 // scrollbar
1290 m_searchResultsList->setSpacing(0); // Remove spacing between items
1291 m_searchResultsList->setContentsMargins(0, 0, 0, 0); // Remove margins
1292
1293 // Set custom delegate for mixed font rendering (bold first line, normal second line)
1294 m_searchResultsList->setItemDelegate(new MixedFontDelegate(m_searchResultsList));
1295
1296 // Connect search results list signals
1297 connect(
1298 m_searchResultsList,
1299 &QListWidget::itemSelectionChanged,
1300 this,
1301 &PreferencesSearchController::onSearchResultSelected
1302 );
1303 connect(
1304 m_searchResultsList,
1305 &QListWidget::itemDoubleClicked,
1306 this,
1307 &PreferencesSearchController::onSearchResultDoubleClicked
1308 );
1309 connect(
1310 m_searchResultsList,
1311 &QListWidget::itemClicked,
1312 this,
1313 &PreferencesSearchController::onSearchResultClicked
1314 );
1315
1316 // Install event filter for keyboard navigation in search results
1317 m_searchResultsList->installEventFilter(m_parentDialog);
1318 }
1319
1320 void PreferencesSearchController::setPreferencesModel(QStandardItemModel* model)
1321 {
1322 m_preferencesModel = model;
1323 }
1324
1325 void PreferencesSearchController::setGroupNameRole(int role)
1326 {
1327 m_groupNameRole = role;
1328 }
1329
1330 void PreferencesSearchController::setPageNameRole(int role)
1331 {
1332 m_pageNameRole = role;
1333 }
1334
1335 QListWidget* PreferencesSearchController::getSearchResultsList() const
1336 {
1337 return m_searchResultsList;
1338 }
1339
1340 bool PreferencesSearchController::isPopupVisible() const
1341 {
1342 return m_searchResultsList && m_searchResultsList->isVisible();
1343 }
1344
1345 bool PreferencesSearchController::isPopupUnderMouse() const
1346 {
1347 return m_searchResultsList && m_searchResultsList->underMouse();
1348 }
1349
1350 bool PreferencesSearchController::isPopupAncestorOf(QWidget* widget) const
1351 {
1352 return m_searchResultsList && m_searchResultsList->isAncestorOf(widget);
1353 }
1354
1355 void PreferencesSearchController::onSearchTextChanged(const QString& text)
1356 {
1357 if (text.isEmpty()) {
1358 clearHighlights();
1359 m_searchResults.clear();
1360 m_lastSearchText.clear();
1361 hideSearchResultsList();
1362 return;
1363 }
1364
1365 // Only perform new search if text changed
1366 if (text != m_lastSearchText) {
1367 performSearch(text);
1368 m_lastSearchText = text;
1369 }
1370 }
1371
1372 void PreferencesSearchController::performSearch(const QString& searchText)
1373 {
1374 clearHighlights();
1375 m_searchResults.clear();
1376
1377 if (searchText.length() < 2) {
1378 hideSearchResultsList();
1379 return;
1380 }
1381
1382 // Search through all groups and pages to collect ALL results
1383 auto root = m_preferencesModel->invisibleRootItem();
1384 for (int i = 0; i < root->rowCount(); i++) {
1385 auto groupItem = static_cast<PreferencesPageItem*>(root->child(i));
1386 auto groupName = groupItem->data(m_groupNameRole).toString();
1387 auto groupStack = qobject_cast<QStackedWidget*>(groupItem->getWidget());
1388
1389 if (!groupStack) {
1390 continue;
1391 }
1392
1393 // Search in each page of the group
1394 for (int j = 0; j < groupItem->rowCount(); j++) {
1395 auto pageItem = static_cast<PreferencesPageItem*>(groupItem->child(j));
1396 auto pageName = pageItem->data(m_pageNameRole).toString();
1397 auto pageWidget = qobject_cast<PreferencePage*>(pageItem->getWidget());
1398
1399 if (!pageWidget) {
1400 continue;
1401 }
1402
1403 // Collect all matching widgets in this page
1404 collectSearchResults(
1405 pageWidget,
1406 searchText,
1407 groupName,
1408 pageName,
1409 pageItem->text(),
1410 groupItem->text()
1411 );
1412 }
1413 }
1414
1415 // Sort results by score (highest first)
1416 std::sort(
1417 m_searchResults.begin(),
1418 m_searchResults.end(),
1419 [](const SearchResult& a, const SearchResult& b) { return a.score > b.score; }
1420 );
1421
1422 // Update UI with search results
1423 if (!m_searchResults.isEmpty()) {
1424 populateSearchResultsList();
1425 showSearchResultsList();
1426 }
1427 else {
1428 hideSearchResultsList();
1429 }
1430 }
1431
1432 void PreferencesSearchController::clearHighlights()
1433 {
1434 // Restore original styles for all highlighted widgets
1435 for (auto widget : m_highlightedWidgets) {
1436 if (widget && m_originalStyles.contains(widget)) {
1437 widget->setStyleSheet(m_originalStyles[widget]);
1438 }
1439 }
1440 m_highlightedWidgets.clear();
1441 m_originalStyles.clear();
1442 }
1443
1444 void PreferencesSearchController::collectSearchResults(
1445 QWidget* widget,
1446 const QString& searchText,
1447 const QString& groupName,
1448 const QString& pageName,
1449 const QString& pageDisplayName,
1450 const QString& tabName
1451 )
1452 {
1453 if (!widget) {
1454 return;
1455 }
1456
1457 // First, check if the page display name itself matches (highest priority)
1458 int pageScore = 0;
1459 if (fuzzyMatch(searchText, pageDisplayName, pageScore)) {
1460 SearchResult result {
1461 .groupName = groupName,
1462 .pageName = pageName,
1463 .widget = widget, // Use the page widget itself
1464 .matchText = pageDisplayName, // Use display name, not internal name
1465 .groupBoxName = QString(), // No groupbox for page-level match
1466 .tabName = tabName,
1467 .pageDisplayName = pageDisplayName,
1468 .isPageLevelMatch = true, // Mark as page-level match
1469 .score = pageScore + 2000 // Boost page-level matches
1470 };
1471 m_searchResults.append(result);
1472 // Continue searching for individual items even if page matches
1473 }
1474
1475 // Search different widget types using the template method
1476 searchWidgetType<QLabel>(widget, searchText, groupName, pageName, pageDisplayName, tabName);
1477 searchWidgetType<QCheckBox>(widget, searchText, groupName, pageName, pageDisplayName, tabName);
1478 searchWidgetType<QRadioButton>(widget, searchText, groupName, pageName, pageDisplayName, tabName);
1479 searchWidgetType<QPushButton>(widget, searchText, groupName, pageName, pageDisplayName, tabName);
1480 }
1481
1482 void PreferencesSearchController::onSearchResultSelected()
1483 {
1484 // This method is called when a search result is selected (arrow keys or single click)
1485 // Navigate immediately but keep popup open
1486 if (m_searchResultsList && m_searchResultsList->currentItem()) {
1487 navigateToCurrentSearchResult(PopupAction::KeepOpen);
1488 }
1489
1490 ensureSearchBoxFocus();
1491 }
1492
1493 void PreferencesSearchController::onSearchResultClicked()
1494 {
1495 // Handle single click - navigate immediately but keep popup open
1496 if (m_searchResultsList && m_searchResultsList->currentItem()) {
1497 navigateToCurrentSearchResult(PopupAction::KeepOpen);
1498 }
1499
1500 ensureSearchBoxFocus();
1501 }
1502
1503 void PreferencesSearchController::onSearchResultDoubleClicked()
1504 {
1505 // Handle double click - navigate and close popup
1506 if (m_searchResultsList && m_searchResultsList->currentItem()) {
1507 navigateToCurrentSearchResult(PopupAction::CloseAfter);
1508 }
1509 }
1510
1511 void PreferencesSearchController::navigateToCurrentSearchResult(PopupAction action)
1512 {
1513 QListWidgetItem* currentItem = m_searchResultsList->currentItem();
1514
1515 // Skip if it's a separator (non-selectable item) or no item selected
1516 if (!currentItem || !(currentItem->flags() & Qt::ItemIsSelectable)) {
1517 return;
1518 }
1519
1520 // Get the result index directly from the item data
1521 bool ok = false;
1522 int resultIndex = currentItem->data(Qt::UserRole).toInt(&ok);
1523
1524 if (ok && resultIndex >= 0 && resultIndex < m_searchResults.size()) {
1525 const SearchResult& result = m_searchResults.at(resultIndex);
1526
1527 // Emit signal to request navigation
1528 Q_EMIT navigationRequested(result.groupName, result.pageName);
1529
1530 // Clear any existing highlights
1531 clearHighlights();
1532
1533 // Only highlight specific widgets for non-page-level matches
1534 if (!result.isPageLevelMatch && !result.widget.isNull()) {
1535 applyHighlightToWidget(result.widget);
1536 }
1537 // For page-level matches, we just navigate without highlighting anything
1538
1539 // Close popup only if requested (double-click or Enter)
1540 if (action == PopupAction::CloseAfter) {
1541 hideSearchResultsList();
1542 }
1543 }
1544 }
1545
1546 void PreferencesSearchController::populateSearchResultsList()
1547 {
1548 m_searchResultsList->clear();
1549
1550 for (int i = 0; i < m_searchResults.size(); ++i) {
1551 const SearchResult& result = m_searchResults.at(i);
1552
1553 // Create item without setting DisplayRole
1554 auto* item = new QListWidgetItem();
1555
1556 // Store path and widget text in separate roles
1557 if (result.isPageLevelMatch) {
1558 // For page matches: parent group as header, page name as content
1559 item->setData(PathRole, result.tabName);
1560 item->setData(WidgetTextRole, result.pageDisplayName);
1561 }
1562 else {
1563 // For widget matches: full path as header, widget text as content
1564 QString pathText = result.tabName + QStringLiteral("/") + result.pageDisplayName;
1565 item->setData(PathRole, pathText);
1566 item->setData(WidgetTextRole, result.matchText);
1567 }
1568 item->setData(Qt::UserRole, i); // Keep existing index storage
1569
1570 m_searchResultsList->addItem(item);
1571 }
1572
1573 // Select first actual item (not separator)
1574 if (!m_searchResults.isEmpty()) {
1575 m_searchResultsList->setCurrentRow(0);
1576 }
1577 }
1578
1579 void PreferencesSearchController::hideSearchResultsList()
1580 {
1581 m_searchResultsList->setVisible(false);
1582 }
1583
1584 void PreferencesSearchController::showSearchResultsList()
1585 {
1586 // Configure popup size and position
1587 configurePopupSize();
1588
1589 // Show the popup
1590 m_searchResultsList->setVisible(true);
1591 m_searchResultsList->raise();
1592
1593 // Use QTimer to ensure focus returns to search box after Qt finishes processing the popup show event
1594 QTimer::singleShot(0, this, [this]() {
1595 if (m_searchBox) {
1596 m_searchBox->setFocus();
1597 m_searchBox->activateWindow();
1598 }
1599 });
1600 }
1601
1602 QString PreferencesSearchController::findGroupBoxForWidget(QWidget* widget)
1603 {
1604 if (!widget) {
1605 return {};
1606 }
1607
1608 // Walk up the parent hierarchy to find a QGroupBox
1609 QWidget* parent = widget->parentWidget();
1610 while (parent) {
1611 auto* groupBox = qobject_cast<QGroupBox*>(parent);
1612 if (groupBox) {
1613 return groupBox->title();
1614 }
1615 parent = parent->parentWidget();
1616 }
1617
1618 return {};
1619 }
1620
1621
1622 template<typename WidgetType>
1623 void PreferencesSearchController::searchWidgetType(
1624 QWidget* parentWidget,
1625 const QString& searchText,
1626 const QString& groupName,
1627 const QString& pageName,
1628 const QString& pageDisplayName,
1629 const QString& tabName
1630 )
1631 {
1632 const QList<WidgetType*> widgets = parentWidget->findChildren<WidgetType*>();
1633
1634 for (WidgetType* widget : widgets) {
1635 QString widgetText;
1636
1637 // Get text based on widget type
1638 if constexpr (std::is_same_v<WidgetType, QLabel>) {
1639 widgetText = widget->text();
1640 }
1641 else if constexpr (std::is_same_v<WidgetType, QCheckBox>) {
1642 widgetText = widget->text();
1643 }
1644 else if constexpr (std::is_same_v<WidgetType, QRadioButton>) {
1645 widgetText = widget->text();
1646 }
1647 else if constexpr (std::is_same_v<WidgetType, QPushButton>) {
1648 widgetText = widget->text();
1649 }
1650
1651 // Use fuzzy matching instead of simple contains
1652 int score = 0;
1653 if (fuzzyMatch(searchText, widgetText, score)) {
1654 SearchResult result {
1655 .groupName = groupName,
1656 .pageName = pageName,
1657 .widget = widget,
1658 .matchText = widgetText,
1659 .groupBoxName = findGroupBoxForWidget(widget),
1660 .tabName = tabName,
1661 .pageDisplayName = pageDisplayName,
1662 .isPageLevelMatch = false,
1663 .score = score
1664 };
1665 m_searchResults.append(result);
1666 }
1667 }
1668 }
1669
1670 int PreferencesSearchController::calculatePopupHeight(int popupWidth) const
1671 {
1672 int totalHeight = 0;
1673 int itemCount = m_searchResultsList->count();
1674 int visibleItemCount = 0;
1675 const int maxVisibleItems = 4;
1676
1677 for (int i = 0; i < itemCount && visibleItemCount < maxVisibleItems; ++i) {
1678 QListWidgetItem* item = m_searchResultsList->item(i);
1679 if (!item) {
1680 continue;
1681 }
1682
1683 // For separator items, use their widget height
1684 if (m_searchResultsList->itemWidget(item)) {
1685 totalHeight += m_searchResultsList->itemWidget(item)->sizeHint().height();
1686 }
1687 else {
1688 // For text items, use the delegate's size hint instead of calculating manually
1689 QStyleOptionViewItem option;
1690 option.rect = QRect(0, 0, popupWidth, 100); // Temporary rect for calculation
1691 option.font = m_searchResultsList->font();
1692
1693 QSize delegateSize = m_searchResultsList->itemDelegate()->sizeHint(
1694 option,
1695 m_searchResultsList->model()->index(i, 0)
1696 );
1697 totalHeight += delegateSize.height();
1698
1699 visibleItemCount++; // Only count actual items, not separators
1700 }
1701 }
1702
1703 return qMax(50, totalHeight); // Minimum 50px height
1704 }
1705
1706 void PreferencesSearchController::configurePopupSize()
1707 {
1708 if (m_searchResults.isEmpty()) {
1709 hideSearchResultsList();
1710 return;
1711 }
1712
1713 // Set a fixed width to prevent flashing when content changes
1714 int popupWidth = 300; // Fixed width for consistent appearance
1715 m_searchResultsList->setFixedWidth(popupWidth);
1716
1717 // Calculate and set the height
1718 int finalHeight = calculatePopupHeight(popupWidth);
1719 m_searchResultsList->setFixedHeight(finalHeight);
1720
1721 // Position the popup's upper-left corner at the upper-right corner of the search box
1722 QPoint globalPos = m_searchBox->mapToGlobal(QPoint(m_searchBox->width(), 0));
1723
1724 // Check if popup would go off-screen to the right
1725 QScreen* screen = QApplication::screenAt(globalPos);
1726 if (!screen) {
1727 screen = QApplication::primaryScreen();
1728 }
1729 QRect screenGeometry = screen->availableGeometry();
1730
1731 // If popup would extend beyond right edge of screen, position it below the search box instead
1732 if (globalPos.x() + popupWidth > screenGeometry.right()) {
1733 globalPos = m_searchBox->mapToGlobal(QPoint(0, m_searchBox->height()));
1734 }
1735
1736 m_searchResultsList->move(globalPos);
1737 }
1738
1739 // Fuzzy search implementation
1740
1741 bool PreferencesSearchController::isExactMatch(const QString& searchText, const QString& targetText)
1742 {
1743 return targetText.toLower().contains(searchText.toLower());
1744 }
1745
1746 bool PreferencesSearchController::fuzzyMatch(
1747 const QString& searchText,
1748 const QString& targetText,
1749 int& score
1750 )
1751 {
1752 if (searchText.isEmpty()) {
1753 score = 0;
1754 return true;
1755 }
1756
1757 const QString lowerSearch = searchText.toLower();
1758 const QString lowerTarget = targetText.toLower();
1759
1760 // First check for exact substring match (highest score)
1761 if (lowerTarget.contains(lowerSearch)) {
1762 // Score based on how early the match appears and how much of the string it covers
1763 int matchIndex = lowerTarget.indexOf(lowerSearch);
1764 int coverage = (lowerSearch.length() * 100) / lowerTarget.length(); // Percentage coverage
1765 score = 1000 - matchIndex + coverage; // Higher score for earlier matches and better coverage
1766 return true;
1767 }
1768
1769 // For fuzzy matching, require minimum search length to avoid too many false positives
1770 if (lowerSearch.length() < 3) {
1771 score = 0;
1772 return false;
1773 }
1774
1775 // Fuzzy matching: check if all characters appear in order
1776 int searchIndex = 0;
1777 int targetIndex = 0;
1778 int consecutiveMatches = 0;
1779 int maxConsecutive = 0;
1780 int firstMatchIndex = -1;
1781 int lastMatchIndex = -1;
1782
1783 while (searchIndex < lowerSearch.length() && targetIndex < lowerTarget.length()) {
1784 if (lowerSearch[searchIndex] == lowerTarget[targetIndex]) {
1785 if (firstMatchIndex == -1) {
1786 firstMatchIndex = targetIndex;
1787 }
1788 lastMatchIndex = targetIndex;
1789 searchIndex++;
1790 consecutiveMatches++;
1791 maxConsecutive = qMax(maxConsecutive, consecutiveMatches);
1792 }
1793 else {
1794 consecutiveMatches = 0;
1795 }
1796 targetIndex++;
1797 }
1798
1799 // Check if all search characters were found
1800 if (searchIndex == lowerSearch.length()) {
1801 // Calculate match density - how spread out are the matches?
1802 int matchSpan = lastMatchIndex - firstMatchIndex + 1;
1803 int density = (lowerSearch.length() * 100) / matchSpan; // Characters per span
1804
1805 // Require minimum density - matches shouldn't be too spread out
1806 if (density < 20) { // Less than 20% density is too sparse
1807 score = 0;
1808 return false;
1809 }
1810
1811 // Require minimum coverage of search term
1812 int coverage = (lowerSearch.length() * 100) / lowerTarget.length();
1813 if (coverage < 15 && lowerTarget.length() > 20) { // For long strings, require better coverage
1814 score = 0;
1815 return false;
1816 }
1817
1818 // Calculate score based on:
1819 // - Match density (how compact the matches are)
1820 // - Consecutive matches bonus
1821 // - Coverage (how much of target string is the search term)
1822 // - Position bonus (earlier matches are better)
1823 int densityScore = qMin(density, 100); // Cap at 100
1824 int consecutiveBonus = (maxConsecutive * 30) / lowerSearch.length();
1825 int coverageScore = qMin(coverage * 2, 100); // Coverage is important
1826 int positionBonus = qMax(0, 50 - firstMatchIndex); // Earlier is better
1827
1828 score = densityScore + consecutiveBonus + coverageScore + positionBonus;
1829
1830 // Minimum score threshold for fuzzy matches
1831 if (score < 80) {
1832 score = 0;
1833 return false;
1834 }
1835
1836 return true;
1837 }
1838
1839 score = 0;
1840 return false;
1841 }
1842
1843 void PreferencesSearchController::ensureSearchBoxFocus()
1844 {
1845 if (m_searchBox && !m_searchBox->hasFocus()) {
1846 m_searchBox->setFocus();
1847 }
1848 }
1849
1850 QString PreferencesSearchController::getHighlightStyleForWidget(QWidget* widget)
1851 {
1852 const auto baseStyle = QStringLiteral(
1853 "background-color: #E3F2FD; color: #1565C0; border: 2px solid #2196F3; border-radius: 3px;"
1854 );
1855
1856 if (qobject_cast<QLabel*>(widget)) {
1857 return QStringLiteral("QLabel { ") + baseStyle + QStringLiteral(" padding: 2px; }");
1858 }
1859
1860 if (qobject_cast<QCheckBox*>(widget)) {
1861 return QStringLiteral("QCheckBox { ") + baseStyle + QStringLiteral(" padding: 2px; }");
1862 }
1863
1864 if (qobject_cast<QRadioButton*>(widget)) {
1865 return QStringLiteral("QRadioButton { ") + baseStyle + QStringLiteral(" padding: 2px; }");
1866 }
1867
1868 if (qobject_cast<QGroupBox*>(widget)) {
1869 return QStringLiteral("QGroupBox::title { ") + baseStyle + QStringLiteral(" padding: 2px; }");
1870 }
1871
1872 if (qobject_cast<QPushButton*>(widget)) {
1873 return QStringLiteral("QPushButton { ") + baseStyle + QStringLiteral(" }");
1874 }
1875
1876 return QStringLiteral("QWidget { ") + baseStyle + QStringLiteral(" padding: 2px; }");
1877 }
1878
1879 void PreferencesSearchController::applyHighlightToWidget(QWidget* widget)
1880 {
1881 if (!widget) {
1882 return;
1883 }
1884
1885 m_originalStyles[widget] = widget->styleSheet();
1886 widget->setStyleSheet(getHighlightStyleForWidget(widget));
1887 m_highlightedWidgets.append(widget);
1888 }
1889
1890 bool PreferencesSearchController::handleSearchBoxKeyPress(QKeyEvent* keyEvent)
1891 {
1892 switch (keyEvent->key()) {
1893 case Qt::Key_Down: {
1894 // Move selection down in popup, skipping separators
1895 const int currentRow = m_searchResultsList->currentRow();
1896 const int totalItems = m_searchResultsList->count();
1897 for (int i = 1; i < totalItems; ++i) {
1898 const int nextRow = (currentRow + i) % totalItems;
1899 if (QListWidgetItem* item = m_searchResultsList->item(nextRow);
1900 item && (item->flags() & Qt::ItemIsSelectable)) {
1901 m_searchResultsList->setCurrentRow(nextRow);
1902 break;
1903 }
1904 }
1905 return true;
1906 }
1907 case Qt::Key_Up: {
1908 // Move selection up in popup, skipping separators
1909 const int currentRow = m_searchResultsList->currentRow();
1910 const int totalItems = m_searchResultsList->count();
1911 for (int i = 1; i < totalItems; ++i) {
1912 int prevRow = (currentRow - i + totalItems) % totalItems;
1913 QListWidgetItem* item = m_searchResultsList->item(prevRow);
1914 if (item && (item->flags() & Qt::ItemIsSelectable)) {
1915 m_searchResultsList->setCurrentRow(prevRow);
1916 break;
1917 }
1918 }
1919 return true;
1920 }
1921 case Qt::Key_Return:
1922 case Qt::Key_Enter:
1923 navigateToCurrentSearchResult(PopupAction::CloseAfter);
1924 return true;
1925 case Qt::Key_Escape:
1926 hideSearchResultsList();
1927 return true;
1928 default:
1929 return false;
1930 }
1931 }
1932
1933 bool PreferencesSearchController::handlePopupKeyPress(const QKeyEvent* keyEvent)
1934 {
1935 switch (keyEvent->key()) {
1936 case Qt::Key_Return:
1937 case Qt::Key_Enter:
1938 navigateToCurrentSearchResult(PopupAction::CloseAfter);
1939 return true;
1940 case Qt::Key_Escape:
1941 hideSearchResultsList();
1942 ensureSearchBoxFocus();
1943 return true;
1944 default:
1945 return false;
1946 }
1947 }
1948
1949 bool PreferencesSearchController::isClickOutsidePopup(const QMouseEvent* mouseEvent) const
1950 {
1951 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1952 QPoint globalPos = mouseEvent->globalPos();
1953 #else
1954 const QPoint globalPos = mouseEvent->globalPosition().toPoint();
1955 #endif
1956 const auto searchBoxRect = QRect(m_searchBox->mapToGlobal(QPoint(0, 0)), m_searchBox->size());
1957 auto popupRect = QRect(m_searchResultsList->mapToGlobal(QPoint(0, 0)), m_searchResultsList->size());
1958
1959 return !searchBoxRect.contains(globalPos) && !popupRect.contains(globalPos);
1960 }
1961
1962 bool DlgPreferencesImp::eventFilter(QObject* obj, QEvent* event)
1963 {
1964 // Handle search box key presses
1965 if (obj == ui->searchBox && event->type() == QEvent::KeyPress) {
1966 auto* keyEvent = static_cast<QKeyEvent*>(event);
1967 return m_searchController->handleSearchBoxKeyPress(keyEvent);
1968 }
1969
1970 // Handle popup key presses
1971 if (obj == m_searchController->getSearchResultsList() && event->type() == QEvent::KeyPress) {
1972 auto* keyEvent = static_cast<QKeyEvent*>(event);
1973 return m_searchController->handlePopupKeyPress(keyEvent);
1974 }
1975
1976 // Prevent popup from stealing focus
1977 if (obj == m_searchController->getSearchResultsList() && event->type() == QEvent::FocusIn) {
1978 m_searchController->ensureSearchBoxFocus();
1979 return true;
1980 }
1981
1982 // Handle search box focus loss
1983 if (obj == ui->searchBox && event->type() == QEvent::FocusOut) {
1984 auto* focusEvent = static_cast<QFocusEvent*>(event);
1985 if (focusEvent->reason() != Qt::PopupFocusReason
1986 && focusEvent->reason() != Qt::MouseFocusReason) {
1987 // Only hide if focus is going somewhere else, not due to popup interaction
1988 QTimer::singleShot(100, this, [this]() {
1989 if (!ui->searchBox->hasFocus() && !m_searchController->isPopupUnderMouse()) {
1990 m_searchController->hideSearchResultsList();
1991 }
1992 });
1993 }
1994 }
1995
1996 // Handle clicks outside popup
1997 if (event->type() == QEvent::MouseButtonPress) {
1998 auto* mouseEvent = static_cast<QMouseEvent*>(event);
1999 auto widget = qobject_cast<QWidget*>(obj);
2000
2001 // Check if click is outside search area
2002 if (m_searchController->isPopupVisible() && obj != m_searchController->getSearchResultsList()
2003 && obj != ui->searchBox && widget && // Only check if obj is actually a QWidget
2004 !m_searchController->isPopupAncestorOf(widget) && !ui->searchBox->isAncestorOf(widget)) {
2005
2006 if (m_searchController->isClickOutsidePopup(mouseEvent)) {
2007 m_searchController->hideSearchResultsList();
2008 m_searchController->clearHighlights();
2009 }
2010 }
2011 }
2012
2013 return QDialog::eventFilter(obj, event);
2014 }
2015
2016 #include "moc_DlgPreferencesImp.cpp"