File indexing completed on 2024-04-28 16:42:55

0001 // SPDX-FileCopyrightText: 2021 Devin Lin <devin@kde.org>
0002 // SPDX-License-Identifier: GPL-2.0-or-later
0003 
0004 #include "terminaltabmodel.h"
0005 
0006 #include <KLocalizedString>
0007 #include <QDebug>
0008 
0009 TerminalTabModel::TerminalTabModel(QObject *parent)
0010     : QAbstractListModel{ parent },
0011       m_indexCounter{ 1 },
0012       m_tabNames{}
0013 {
0014     newTab(); // default tab
0015 }
0016 
0017 int TerminalTabModel::rowCount(const QModelIndex &parent) const
0018 {
0019     Q_UNUSED(parent)
0020     return m_tabNames.count();
0021 }
0022 
0023 QVariant TerminalTabModel::data(const QModelIndex &index, int role) const
0024 {
0025     if (!index.isValid() || index.row() >= m_tabNames.count()) {
0026         return {};
0027     }
0028     
0029     if (role == NameRole) {
0030         return m_tabNames[index.row()];
0031     } else {
0032         return {};
0033     }
0034 }
0035 
0036 bool TerminalTabModel::setData(const QModelIndex &index, const QVariant &value, int role)
0037 {
0038     if (!index.isValid() || index.row() >= m_tabNames.count()) {
0039         return false;
0040     }
0041     
0042     if (role == NameRole) {
0043         m_tabNames[index.row()] = value.toString();
0044     } else {
0045         return false;
0046     }
0047     
0048     Q_EMIT dataChanged(index, index);
0049     return true;
0050 }
0051 
0052 Qt::ItemFlags TerminalTabModel::flags(const QModelIndex &index) const
0053 {
0054     Q_UNUSED(index);
0055     return Qt::ItemIsEditable;
0056 }
0057 
0058 QHash<int, QByteArray> TerminalTabModel::roleNames() const
0059 {
0060     return {{ NameRole, "name" }};
0061 }
0062 
0063 Q_INVOKABLE void TerminalTabModel::newTab()
0064 {
0065     auto index = m_indexCounter;
0066     
0067     Q_EMIT beginInsertRows(QModelIndex(), m_tabNames.count(), m_tabNames.count());
0068     m_tabNames.append(i18n("Tab %1", index));
0069     Q_EMIT endInsertRows();
0070     
0071     ++m_indexCounter;
0072 }
0073 
0074 void TerminalTabModel::removeTab(int index)
0075 {
0076     if (index < 0 || index >= m_tabNames.count()) {
0077         return;
0078     }
0079     
0080     Q_EMIT beginRemoveRows(QModelIndex(), index, index);
0081     m_tabNames.removeAt(index);
0082     Q_EMIT endRemoveRows();
0083     
0084     if (m_tabNames.count() == 0) {
0085         m_indexCounter = 1;
0086         newTab();
0087     }
0088 }