File indexing completed on 2024-05-12 16:27:22

0001 /*
0002    SPDX-FileCopyrightText: 2020-2024 Laurent Montel <montel@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "servermenu.h"
0008 #include "accountmanager.h"
0009 #include "model/rocketchataccountmodel.h"
0010 #include "rocketchataccount.h"
0011 #include "ruqola.h"
0012 #include <KActionCollection>
0013 #include <KLocalizedString>
0014 #include <QActionGroup>
0015 #include <QMenu>
0016 
0017 ServerMenu::ServerMenu(QWidget *parent)
0018     : KActionMenu(parent)
0019 {
0020     setText(i18n("Server"));
0021     connect(menu(), &QMenu::aboutToShow, this, &ServerMenu::slotUpdateAccountMenu);
0022 }
0023 
0024 ServerMenu::~ServerMenu() = default;
0025 
0026 void ServerMenu::setActionCollection(KActionCollection *ac)
0027 {
0028     mActionCollection = ac;
0029 }
0030 
0031 void ServerMenu::slotUpdateAccountMenu()
0032 {
0033     menu()->clear();
0034     auto accountManager = Ruqola::self()->accountManager();
0035     auto *model = accountManager->rocketChatAccountProxyModel();
0036     const QString currentAccountName = accountManager->currentAccount();
0037     const int accountNumber = model->rowCount();
0038     if (accountNumber == 0) {
0039         // Nothing
0040     } else if (accountNumber == 1) {
0041         const auto index = model->index(0, 0);
0042         auto account = index.data(RocketChatAccountModel::Account).value<RocketChatAccount *>();
0043         auto action = new QAction(account->displayName(), this);
0044         menu()->addAction(action);
0045         action->setEnabled(false);
0046     } else {
0047         auto group = new QActionGroup(this);
0048         group->setExclusive(true);
0049         for (int i = 0; i < accountNumber; ++i) {
0050             const auto index = model->index(i, 0);
0051             auto account = index.data(RocketChatAccountModel::Account).value<RocketChatAccount *>();
0052             if (account->accountEnabled()) {
0053                 const QString accountName = account->accountName();
0054                 const QString displayName = account->displayName();
0055                 auto action = new QAction(displayName, this);
0056                 action->setCheckable(true);
0057                 group->addAction(action);
0058                 if (currentAccountName == accountName) {
0059                     action->setChecked(true);
0060                 }
0061                 menu()->addAction(action);
0062                 if (mActionCollection) {
0063                     mActionCollection->setDefaultShortcut(action, QKeySequence(QStringLiteral("CTRL+%1").arg(i)));
0064                 }
0065                 connect(action, &QAction::triggered, this, [accountName, accountManager]() {
0066                     accountManager->setCurrentAccount(accountName);
0067                 });
0068             }
0069         }
0070     }
0071 }
0072 
0073 #include "moc_servermenu.cpp"