1 #include "cacheview.hpp"
2
CacheView(const lib::paths & paths,QWidget * parent)3 CacheView::CacheView(const lib::paths &paths, QWidget *parent)
4 : paths(paths),
5 QTreeWidget(parent)
6 {
7 setHeaderLabels({
8 "Folder",
9 "Files",
10 "Size",
11 });
12 setRootIsDecorated(false);
13
14 setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
15 QWidget::connect(this, &QWidget::customContextMenuRequested, this, &CacheView::menu);
16 }
17
fullName(const QString & folderName)18 auto CacheView::fullName(const QString &folderName) -> QString
19 {
20 if (folderName == "album")
21 {
22 return "Album covers";
23 }
24 if (folderName == "librespot")
25 {
26 return "Librespot cache";
27 }
28 if (folderName == "playlist")
29 {
30 return "Playlists";
31 }
32 if (folderName == "qmlcache")
33 {
34 return "spotify-qt-quick cache";
35 }
36 if (folderName == "tracks")
37 {
38 return "Album and library";
39 }
40 if (folderName == "lyrics")
41 {
42 return "Lyrics";
43 }
44
45 return folderName;
46 }
47
folderSize(const QString & path,unsigned int * count,unsigned int * size)48 void CacheView::folderSize(const QString &path, unsigned int *count, unsigned int *size)
49 {
50 for (auto &file : QDir(path).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Files))
51 {
52 if (file.isDir())
53 {
54 folderSize(file.absoluteFilePath(), count, size);
55 continue;
56 }
57
58 (*count)++;
59 *size += file.size();
60 }
61 }
62
menu(const QPoint & pos)63 void CacheView::menu(const QPoint &pos)
64 {
65 auto *item = itemAt(pos);
66 auto folder = item->data(0, 0x100).toString();
67 if (folder.isEmpty())
68 {
69 return;
70 }
71
72 auto *menu = new QMenu(this);
73 QAction::connect(menu->addAction(Icon::get("folder-temp"),
74 "Open folder"),
75 &QAction::triggered, [this, folder](bool /*checked*/)
76 {
77 UrlUtils::open(folder, LinkType::Path, this);
78 });
79 menu->popup(mapToGlobal(pos));
80 }
81
reload()82 void CacheView::reload()
83 {
84 clear();
85
86 QDir cacheDir(QString::fromStdString(paths.cache()));
87 for (auto &dir : cacheDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
88 {
89 auto *item = new QTreeWidgetItem(this);
90 item->setText(0, fullName(dir.baseName()));
91
92 auto count = 0U;
93 auto size = 0U;
94 folderSize(dir.absoluteFilePath(), &count, &size);
95
96 item->setData(0, 0x100, dir.absoluteFilePath());
97 item->setText(1, QString::number(count));
98 item->setText(2, QString::fromStdString(lib::fmt::size(size)));
99 }
100
101 header()->resizeSections(QHeaderView::ResizeToContents);
102 }
103
showEvent(QShowEvent *)104 void CacheView::showEvent(QShowEvent */*event*/)
105 {
106 reload();
107 }
108