File indexing completed on 2024-05-12 05:36:52
0001 /* 0002 * SPDX-FileCopyrightText: 2018-2019 Daniel Vrátil <dvratil@kde.org> 0003 * 0004 * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL 0005 */ 0006 0007 #include "devicemodel.h" 0008 #include "device.h" 0009 0010 using namespace Bolt; 0011 0012 Q_DECLARE_METATYPE(QSharedPointer<Bolt::Device>) 0013 0014 void DeviceModel::setManager(Manager *manager) 0015 { 0016 if (mManager == manager) { 0017 return; 0018 } 0019 0020 if (mManager) { 0021 mManager->disconnect(this); 0022 } 0023 0024 beginResetModel(); 0025 mManager = manager; 0026 mDevices.clear(); 0027 if (mManager) { 0028 connect(mManager, &Manager::deviceAdded, this, [this](const QSharedPointer<Device> &device) { 0029 if (mShowHosts || device->type() == Type::Peripheral) { 0030 beginInsertRows({}, mDevices.count(), mDevices.count()); 0031 mDevices.push_back(device); 0032 endInsertRows(); 0033 } 0034 }); 0035 connect(mManager, &Manager::deviceRemoved, this, [this](const QSharedPointer<Device> &device) { 0036 const int idx = mDevices.indexOf(device); 0037 if (idx == -1) { 0038 return; 0039 } 0040 beginRemoveRows({}, idx, idx); 0041 mDevices.removeAt(idx); 0042 endRemoveRows(); 0043 }); 0044 0045 populateWithoutReset(); 0046 } 0047 endResetModel(); 0048 0049 Q_EMIT managerChanged(mManager); 0050 } 0051 0052 Manager *DeviceModel::manager() const 0053 { 0054 return mManager; 0055 } 0056 0057 bool DeviceModel::showHosts() const 0058 { 0059 return mShowHosts; 0060 } 0061 0062 void DeviceModel::setShowHosts(bool showHosts) 0063 { 0064 if (mShowHosts != showHosts) { 0065 mShowHosts = showHosts; 0066 Q_EMIT showHostsChanged(mShowHosts); 0067 if (mManager) { 0068 beginResetModel(); 0069 populateWithoutReset(); 0070 endResetModel(); 0071 } 0072 } 0073 } 0074 0075 QHash<int, QByteArray> DeviceModel::roleNames() const 0076 { 0077 auto roles = QAbstractListModel::roleNames(); 0078 roles[DeviceRole] = "device"; 0079 return roles; 0080 } 0081 0082 int DeviceModel::rowCount(const QModelIndex &parent) const 0083 { 0084 if (parent.isValid()) { 0085 return 0; 0086 } 0087 0088 return mDevices.count(); 0089 } 0090 0091 QVariant DeviceModel::data(const QModelIndex &index, int role) const 0092 { 0093 if (!index.isValid()) { 0094 return {}; 0095 } 0096 0097 if (index.row() >= mDevices.size()) { 0098 return {}; 0099 } 0100 0101 if (role == DeviceRole) { 0102 return QVariant::fromValue(mDevices.at(index.row()).data()); 0103 } 0104 0105 return {}; 0106 } 0107 0108 void DeviceModel::populateWithoutReset() 0109 { 0110 Q_ASSERT(mManager); 0111 0112 mDevices.clear(); 0113 const auto all = mManager->devices(); 0114 std::copy_if(all.cbegin(), all.cend(), std::back_inserter(mDevices), [this](const auto &device) { 0115 return mShowHosts || device->type() == Type::Peripheral; 0116 }); 0117 } 0118 0119 #include "moc_devicemodel.cpp"