File indexing completed on 2024-05-12 05:52:09

0001 /*
0002     SPDX-FileCopyrightText: 2022 Jiří Wolker <woljiri@gmail.com>
0003     SPDX-FileCopyrightText: 2022 Eugene Popov <popov895@ukr.net>
0004 
0005     SPDX-License-Identifier: GPL-2.0-or-later
0006 */
0007 
0008 #include "recentitemsmodel.h"
0009 
0010 #include "ktexteditor_utils.h"
0011 
0012 #include <QMimeDatabase>
0013 
0014 RecentItemsModel::RecentItemsModel(QObject *parent)
0015     : QAbstractListModel(parent)
0016 {
0017 }
0018 
0019 QVariant RecentItemsModel::data(const QModelIndex &index, int role) const
0020 {
0021     if (index.isValid()) {
0022         const size_t row = index.row();
0023         if (row < m_recentItems.size()) {
0024             const RecentItemInfo &recentItem = m_recentItems.at(row);
0025             switch (role) {
0026             case Qt::DisplayRole:
0027                 return recentItem.name;
0028             case Qt::DecorationRole:
0029                 return recentItem.icon;
0030             case Qt::ToolTipRole:
0031                 return recentItem.url.toString(QUrl::PreferLocalFile);
0032             default:
0033                 break;
0034             }
0035         }
0036     }
0037 
0038     return QVariant();
0039 }
0040 
0041 int RecentItemsModel::rowCount(const QModelIndex &parent) const
0042 {
0043     Q_UNUSED(parent);
0044 
0045     return m_recentItems.size();
0046 }
0047 
0048 void RecentItemsModel::refresh(const QList<QUrl> &urls)
0049 {
0050     std::vector<RecentItemInfo> recentItems;
0051     recentItems.reserve(urls.size());
0052 
0053     QIcon icon;
0054     QString name;
0055     for (const QUrl &url : urls) {
0056         // lookup mime type without accessing file to avoid stall for e.g. NFS/SMB
0057         const QMimeType mimeType = QMimeDatabase().mimeTypeForFile(url.path(), QMimeDatabase::MatchExtension);
0058         if (url.isLocalFile() || !mimeType.isDefault()) {
0059             icon = QIcon::fromTheme(mimeType.iconName());
0060         } else {
0061             icon = QIcon::fromTheme(QStringLiteral("network-server"));
0062         }
0063 
0064         // we want some filename @ folder output to have chance to keep important stuff even on elide, see bug 472981
0065         name = Utils::niceFileNameWithPath(url);
0066 
0067         recentItems.push_back({icon, name, url});
0068     }
0069 
0070     beginResetModel();
0071     m_recentItems = std::move(recentItems);
0072     endResetModel();
0073 }
0074 
0075 QUrl RecentItemsModel::url(const QModelIndex &index) const
0076 {
0077     if (index.isValid()) {
0078         const size_t row = index.row();
0079         if (row < m_recentItems.size()) {
0080             return m_recentItems.at(row).url;
0081         }
0082     }
0083 
0084     return QUrl();
0085 }
0086 
0087 #include "moc_recentitemsmodel.cpp"