1/*
2 SPDX-FileCopyrightText: 2013 Martin Gräßlin <mgraesslin@kde.org>
3 SPDX-FileCopyrightText: 2023 David Redondo <kde@david-redondo.de>
4
5 SPDX-License-Identifier: LGPL-2.0-or-later
6*/
7
8#include "kcolorschememenu.h"
9
10#include <KActionMenu>
11#include <KColorSchemeManager>
12#include <KColorSchemeModel>
13#include <KLocalizedString>
14
15#include <QActionGroup>
16#include <QIcon>
17#include <QMenu>
18
19constexpr int defaultSchemeRow = 0;
20
21KActionMenu *KColorSchemeMenu::createMenu(KColorSchemeManager *manager, QObject *parent)
22{
23 // Be careful here when connecting to signals. The menu can outlive the manager
24 KActionMenu *menu = new KActionMenu(QIcon::fromTheme(QStringLiteral("preferences-desktop-color")), i18n("Color Scheme"), parent);
25 QActionGroup *group = new QActionGroup(menu);
26 QObject::connect(sender: group, signal: &QActionGroup::triggered, context: manager, slot: [manager](QAction *action) {
27 const QString schemePath = action->data().toString();
28 if (schemePath.isEmpty()) {
29 // Reset to default
30 manager->activateScheme(index: QModelIndex());
31 } else {
32 // Software linking KXmlGui gets its static KCheckAccelerators object deploy
33 // KAcceleratorManager on the whole UI automatically, which adds accelerators
34 // also to the texts of this menu's actions.
35 // So they have to be remove here in case
36 // (hoping that no original names have them also in case no accelerators were added)
37 // See also KColorSchemeManager::saveSchemeToConfigFile(const QString &schemeName) const.
38 const QString schemeName = KLocalizedString::removeAcceleratorMarker(label: action->text());
39 manager->activateScheme(index: manager->indexForScheme(name: schemeName));
40 }
41 });
42 const auto model = manager->model();
43 for (int i = 0; i < model->rowCount(); ++i) {
44 QModelIndex index = model->index(row: i, column: 0);
45 QAction *action = new QAction(index.data(arole: KColorSchemeModel::NameRole).toString(), menu);
46 action->setData(index.data(arole: KColorSchemeModel::PathRole));
47 action->setActionGroup(group);
48 action->setCheckable(true);
49 if (index.data(arole: KColorSchemeModel::IdRole).toString() == manager->activeSchemeId()) {
50 action->setChecked(true);
51 }
52 menu->addAction(action);
53 QObject::connect(sender: menu->menu(), signal: &QMenu::aboutToShow, context: model, slot: [action, index] {
54 if (action->icon().isNull()) {
55 action->setIcon(index.data(arole: KColorSchemeModel::IconRole).value<QIcon>());
56 }
57 });
58 }
59 const auto groupActions = group->actions();
60 if (!group->checkedAction()) {
61 // If no (valid) color scheme has been selected we select the default one
62 groupActions[defaultSchemeRow]->setChecked(true);
63 }
64
65 return menu;
66}
67

source code of kconfigwidgets/src/kcolorschememenu.cpp