feat(core): add the disk tree, scanner and treemap layout
version / print-version (push) Successful in 1s

The UI and the tests were written against these modules, but the sources
were never tracked, so the package could not build. The scanner aggregates
sizes and file counts, skips symlinks, reports unreadable entries, and the
layout implements a squarified treemap so tile areas stay proportional to
the sizes.
This commit is contained in:
BlackAngelTV committed 2026-11-27 07:50:11 +01:00
1 parent cb4434be0b
commit dd17a679d0
7 files changed
+416

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
#include "core/disk-node.h"
#include <algorithm>
std::unique_ptr<DiskNode> detachNode(DiskNode *node)
{
if (!node || !node->parent) {
return nullptr;
}
DiskNode *parent = node->parent;
auto &siblings = parent->children;
const auto position = std::find_if(siblings.begin(), siblings.end(),
[node](const std::unique_ptr<DiskNode> &child) {
return child.get() == node;
});
if (position == siblings.end()) {
return nullptr;
}
std::unique_ptr<DiskNode> detached = std::move(*position);
siblings.erase(position);
// Every ancestor aggregated this subtree, so its contribution has to leave
// them as well or the shares shown above would stay wrong.
const quint64 size = detached->totalSize;
const quint64 files = detached->fileCount;
for (DiskNode *ancestor = parent; ancestor; ancestor = ancestor->parent) {
ancestor->totalSize -= std::min(ancestor->totalSize, size);
ancestor->fileCount -= std::min(ancestor->fileCount, files);
}
detached->parent = nullptr;
return detached;
}
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include <QString>
#include <QtGlobal>
#include <memory>
#include <vector>
enum class NodeKind {
File,
Directory,
};
// A node owns its children; parent links are borrowed and stay valid for as
// long as the owning tree is alive.
struct DiskNode {
QString name;
QString path;
NodeKind kind = NodeKind::File;
// Aggregates over the whole subtree, so a directory is comparable to the
// files it contains without walking it again.
quint64 totalSize = 0;
quint64 fileCount = 0;
DiskNode *parent = nullptr;
std::vector<std::unique_ptr<DiskNode>> children;
bool isDirectory() const { return kind == NodeKind::Directory; }
};
// Removes `node` from its parent and hands its ownership to the caller, with
// the ancestors' aggregates updated. Detaching the root (or a node that is not
// in its parent's children) is refused and returns nullptr.
std::unique_ptr<DiskNode> detachNode(DiskNode *node);
+128
View File
@@ -0,0 +1,128 @@
#include "core/disk-scanner.h"
#include <QDir>
#include <QFileInfo>
#include <QFileInfoList>
#include <algorithm>
#include <utility>
DiskScanner::DiskScanner(QString rootPath, QObject *parent)
: QThread(parent)
, m_rootPath(std::move(rootPath))
{
}
DiskScanner::~DiskScanner()
{
cancel();
wait();
}
void DiskScanner::cancel()
{
m_cancelled.store(true);
}
std::shared_ptr<DiskNode> DiskScanner::takeTree()
{
return std::move(m_tree);
}
void DiskScanner::run()
{
m_tree.reset();
m_stats = ScanStats();
const QFileInfo rootInfo(m_rootPath);
auto root = std::make_shared<DiskNode>();
root->kind = NodeKind::Directory;
root->path = rootInfo.absoluteFilePath();
// The root of a filesystem has no file name, so its path is the only label.
root->name = rootInfo.fileName().isEmpty() ? root->path : rootInfo.fileName();
if (!rootInfo.exists() || !rootInfo.isDir()) {
m_stats.errors.append(tr("%1 is not a readable directory").arg(m_rootPath));
m_tree = root;
return;
}
if (m_cancelled.load()) {
return;
}
scanDirectory(*root);
if (m_cancelled.load()) {
// A partial tree would show sizes that depend on where the scan
// stopped, so a cancelled scan reports nothing instead.
return;
}
m_tree = root;
}
void DiskScanner::scanDirectory(DiskNode &directory)
{
QDir dir(directory.path);
if (!dir.isReadable()) {
m_stats.errors.append(directory.path);
return;
}
const QFileInfoList entries = dir.entryInfoList(
QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System, QDir::Name);
for (const QFileInfo &entry : entries) {
if (m_cancelled.load()) {
return;
}
if (entry.isSymLink()) {
continue;
}
if (entry.isDir()) {
auto child = std::make_unique<DiskNode>();
child->kind = NodeKind::Directory;
child->name = entry.fileName();
child->path = entry.absoluteFilePath();
child->parent = &directory;
++m_stats.dirCount;
DiskNode *rawChild = child.get();
directory.children.push_back(std::move(child));
scanDirectory(*rawChild);
} else if (entry.isFile()) {
auto child = std::make_unique<DiskNode>();
child->kind = NodeKind::File;
child->name = entry.fileName();
child->path = entry.absoluteFilePath();
child->totalSize = static_cast<quint64>(entry.size());
child->fileCount = 1;
child->parent = &directory;
m_stats.fileCount += 1;
m_stats.totalBytes += child->totalSize;
directory.children.push_back(std::move(child));
emit progress(entry.absoluteFilePath(), m_stats.totalBytes);
}
}
// Aggregates are summed on the way back up, so every node owns the totals
// of its subtree as soon as its parent is done.
directory.totalSize = 0;
directory.fileCount = 0;
for (const auto &child : directory.children) {
directory.totalSize += child->totalSize;
directory.fileCount += child->fileCount;
}
// Biggest first: the treemap lays out in this order and the largest entries
// get the squares that are easiest to hit.
std::stable_sort(directory.children.begin(), directory.children.end(),
[](const std::unique_ptr<DiskNode> &left,
const std::unique_ptr<DiskNode> &right) {
return left->totalSize > right->totalSize;
});
}
+51
View File
@@ -0,0 +1,51 @@
#pragma once
#include "core/disk-node.h"
#include <QString>
#include <QStringList>
#include <QThread>
#include <atomic>
#include <memory>
struct ScanStats {
quint64 fileCount = 0;
quint64 dirCount = 0;
quint64 totalBytes = 0;
// Entries that could not be read; the scan continues past them.
QStringList errors;
};
// Walks a directory on its own thread so the window stays responsive while a
// large tree is being analysed. Symlinks are skipped: following them can loop
// and would count the same bytes twice.
class DiskScanner : public QThread {
Q_OBJECT
public:
explicit DiskScanner(QString rootPath, QObject *parent = nullptr);
~DiskScanner() override;
// Safe to call from another thread; the run stops at the next entry and
// leaves no tree behind.
void cancel();
// Hands the scanned tree to the caller. Null when the scan was cancelled.
std::shared_ptr<DiskNode> takeTree();
ScanStats stats() const { return m_stats; }
signals:
void progress(const QString &currentPath, quint64 bytes);
protected:
void run() override;
private:
void scanDirectory(DiskNode &directory);
QString m_rootPath;
std::shared_ptr<DiskNode> m_tree;
ScanStats m_stats;
std::atomic_bool m_cancelled{false};
};
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <QString>
#include <QtGlobal>
// Sizes are apparent sizes, so binary units keep the labels honest without
// suggesting that this is the space actually allocated on the disk.
inline QString formatBytes(quint64 bytes)
{
static const char *const units[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB"};
double value = static_cast<double>(bytes);
int unit = 0;
while (value >= 1024.0 && unit < 5) {
value /= 1024.0;
++unit;
}
if (unit == 0) {
return QStringLiteral("%1 B").arg(bytes);
}
// One decimal is enough above 10 units; below that the extra digit tells
// apart the files that look equally big in the treemap.
return QStringLiteral("%1 %2")
.arg(QString::number(value, 'f', value < 10.0 ? 2 : 1), QLatin1String(units[unit]));
}
+126
View File
@@ -0,0 +1,126 @@
#include "core/treemap-layout.h"
#include <algorithm>
#include <limits>
namespace {
struct Item {
qreal area = 0.0;
int index = 0;
};
// Worst width/height ratio of a row laid along a side of `side` pixels. The
// squarified algorithm keeps a row together only while that value improves.
qreal worstAspect(const QVector<Item> &row, qreal side)
{
if (row.isEmpty() || side <= 0.0) {
return std::numeric_limits<qreal>::infinity();
}
qreal sum = 0.0;
qreal smallest = std::numeric_limits<qreal>::max();
qreal largest = 0.0;
for (const Item &item : row) {
sum += item.area;
smallest = std::min(smallest, item.area);
largest = std::max(largest, item.area);
}
if (sum <= 0.0 || smallest <= 0.0) {
return std::numeric_limits<qreal>::infinity();
}
const qreal squaredSum = sum * sum;
const qreal squaredSide = side * side;
return std::max(squaredSide * largest / squaredSum, squaredSum / (squaredSide * smallest));
}
// Places one row along the shorter side of the free rectangle and shrinks it by
// the row's thickness. Areas are preserved exactly, which is what keeps the
// tiles proportional to the sizes.
void layoutRow(const QVector<Item> &row, QRectF &free, QVector<TreemapTile> &tiles)
{
qreal area = 0.0;
for (const Item &item : row) {
area += item.area;
}
if (area <= 0.0 || free.width() <= 0.0 || free.height() <= 0.0) {
return;
}
if (free.width() >= free.height()) {
const qreal thickness = area / free.height();
qreal top = free.top();
for (const Item &item : row) {
const qreal height = item.area / thickness;
tiles.append({item.index, QRectF(free.left(), top, thickness, height)});
top += height;
}
free.setLeft(free.left() + thickness);
} else {
const qreal thickness = area / free.width();
qreal left = free.left();
for (const Item &item : row) {
const qreal width = item.area / thickness;
tiles.append({item.index, QRectF(left, free.top(), width, thickness)});
left += width;
}
free.setTop(free.top() + thickness);
}
}
} // namespace
QVector<TreemapTile> squarify(const QVector<qreal> &sizes, const QRectF &bounds)
{
QVector<TreemapTile> tiles;
if (sizes.isEmpty() || bounds.width() <= 0.0 || bounds.height() <= 0.0) {
return tiles;
}
qreal total = 0.0;
for (const qreal size : sizes) {
if (size > 0.0) {
total += size;
}
}
if (total <= 0.0) {
return tiles;
}
const qreal available = bounds.width() * bounds.height();
QVector<Item> items;
items.reserve(sizes.size());
for (int index = 0; index < sizes.size(); ++index) {
if (sizes.at(index) <= 0.0) {
continue;
}
items.append({sizes.at(index) / total * available, index});
}
// Large tiles first: a row of similar sizes gives the squarest result.
std::stable_sort(items.begin(), items.end(),
[](const Item &left, const Item &right) { return left.area > right.area; });
QRectF free = bounds;
int next = 0;
while (next < items.size() && free.width() > 0.0 && free.height() > 0.0) {
const qreal side = std::min(free.width(), free.height());
QVector<Item> row;
row.append(items.at(next++));
while (next < items.size()) {
QVector<Item> candidate = row;
candidate.append(items.at(next));
if (worstAspect(candidate, side) > worstAspect(row, side)) {
break;
}
row = candidate;
++next;
}
layoutRow(row, free, tiles);
}
return tiles;
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <QRectF>
#include <QVector>
#include <QtGlobal>
struct TreemapTile {
// Index in the sizes vector the layout was computed from.
int index = 0;
QRectF rect;
};
// Squarified treemap (Bruls, Huizing, van Wijk): the tile areas are
// proportional to `sizes` while the tiles stay as close to squares as the
// bounds allow. Entries with a zero size get no tile, so their index is absent
// from the result.
QVector<TreemapTile> squarify(const QVector<qreal> &sizes, const QRectF &bounds);