1 /* cache_proxy_model.cpp 2 * 3 * Wireshark - Network traffic analyzer 4 * By Gerald Combs <gerald@wireshark.org> 5 * Copyright 1998 Gerald Combs 6 * 7 * SPDX-License-Identifier: GPL-2.0-or-later 8 */ 9 10 #include <ui/qt/models/cache_proxy_model.h> 11 12 CacheProxyModel::CacheProxyModel(QObject *parent) : QIdentityProxyModel(parent) 13 { 14 } 15 16 QVariant CacheProxyModel::data(const QModelIndex &index, int role) const 17 { 18 QModelIndex dataIndex = cache.index(index.row(), index.column()); 19 if (!dataIndex.isValid()) { 20 // index is possibly outside columnCount or rowCount 21 return QVariant(); 22 } 23 24 if (hasModel()) { 25 QVariant value = QIdentityProxyModel::data(index, role); 26 cache.setData(dataIndex, value, role); 27 return value; 28 } else { 29 return cache.data(dataIndex, role); 30 } 31 } 32 33 Qt::ItemFlags CacheProxyModel::flags(const QModelIndex &index) const 34 { 35 if (hasModel()) { 36 return QIdentityProxyModel::flags(index); 37 } else { 38 // Override default to prevent editing. 39 return Qt::ItemIsSelectable | Qt::ItemIsEnabled; 40 } 41 } 42 43 QVariant CacheProxyModel::headerData(int section, Qt::Orientation orientation, 44 int role) const 45 { 46 if (hasModel()) { 47 QVariant value = QIdentityProxyModel::headerData(section, orientation, role); 48 cache.setHeaderData(section, orientation, value, role); 49 return value; 50 } else { 51 return cache.headerData(section, orientation, role); 52 } 53 } 54 55 int CacheProxyModel::rowCount(const QModelIndex &parent) const 56 { 57 if (hasModel()) { 58 int count = QIdentityProxyModel::rowCount(parent); 59 cache.setRowCount(count); 60 return count; 61 } else { 62 return cache.rowCount(parent); 63 } 64 } 65 66 int CacheProxyModel::columnCount(const QModelIndex &parent) const 67 { 68 if (hasModel()) { 69 int count = QIdentityProxyModel::columnCount(parent); 70 cache.setColumnCount(count); 71 return count; 72 } else { 73 return cache.columnCount(parent); 74 } 75 } 76 77 /** 78 * Sets the source model from which data must be pulled. If newSourceModel is 79 * NULL, then the cache will be used. 80 */ 81 void CacheProxyModel::setSourceModel(QAbstractItemModel *newSourceModel) 82 { 83 if (newSourceModel) { 84 cache.clear(); 85 QIdentityProxyModel::setSourceModel(newSourceModel); 86 connect(newSourceModel, &QAbstractItemModel::modelReset, 87 this, &CacheProxyModel::resetCacheModel); 88 } else { 89 if (sourceModel()) { 90 // Prevent further updates to source model from invalidating cache. 91 disconnect(sourceModel(), &QAbstractItemModel::modelReset, 92 this, &CacheProxyModel::resetCacheModel); 93 } 94 QIdentityProxyModel::setSourceModel(&cache); 95 } 96 } 97 98 void CacheProxyModel::resetCacheModel() { 99 cache.clear(); 100 } 101