diff --git a/src/core/disk-node.cpp b/src/core/disk-node.cpp new file mode 100644 index 0000000..8131b7c --- /dev/null +++ b/src/core/disk-node.cpp @@ -0,0 +1,35 @@ +#include "core/disk-node.h" + +#include + +std::unique_ptr 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 &child) { + return child.get() == node; + }); + if (position == siblings.end()) { + return nullptr; + } + + std::unique_ptr 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; +} diff --git a/src/core/disk-node.h b/src/core/disk-node.h new file mode 100644 index 0000000..32557cf --- /dev/null +++ b/src/core/disk-node.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +#include +#include + +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> 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 detachNode(DiskNode *node); diff --git a/src/core/disk-scanner.cpp b/src/core/disk-scanner.cpp new file mode 100644 index 0000000..1f3e256 --- /dev/null +++ b/src/core/disk-scanner.cpp @@ -0,0 +1,128 @@ +#include "core/disk-scanner.h" + +#include +#include +#include + +#include +#include + +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 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(); + 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(); + 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(); + child->kind = NodeKind::File; + child->name = entry.fileName(); + child->path = entry.absoluteFilePath(); + child->totalSize = static_cast(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 &left, + const std::unique_ptr &right) { + return left->totalSize > right->totalSize; + }); +} diff --git a/src/core/disk-scanner.h b/src/core/disk-scanner.h new file mode 100644 index 0000000..a58dae9 --- /dev/null +++ b/src/core/disk-scanner.h @@ -0,0 +1,51 @@ +#pragma once + +#include "core/disk-node.h" + +#include +#include +#include + +#include +#include + +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 takeTree(); + ScanStats stats() const { return m_stats; } + +signals: + void progress(const QString ¤tPath, quint64 bytes); + +protected: + void run() override; + +private: + void scanDirectory(DiskNode &directory); + + QString m_rootPath; + std::shared_ptr m_tree; + ScanStats m_stats; + std::atomic_bool m_cancelled{false}; +}; diff --git a/src/core/format.h b/src/core/format.h new file mode 100644 index 0000000..4a83fa6 --- /dev/null +++ b/src/core/format.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include + +// 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(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])); +} diff --git a/src/core/treemap-layout.cpp b/src/core/treemap-layout.cpp new file mode 100644 index 0000000..8195756 --- /dev/null +++ b/src/core/treemap-layout.cpp @@ -0,0 +1,126 @@ +#include "core/treemap-layout.h" + +#include +#include + +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 &row, qreal side) +{ + if (row.isEmpty() || side <= 0.0) { + return std::numeric_limits::infinity(); + } + + qreal sum = 0.0; + qreal smallest = std::numeric_limits::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::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 &row, QRectF &free, QVector &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 squarify(const QVector &sizes, const QRectF &bounds) +{ + QVector 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 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 row; + row.append(items.at(next++)); + while (next < items.size()) { + QVector candidate = row; + candidate.append(items.at(next)); + if (worstAspect(candidate, side) > worstAspect(row, side)) { + break; + } + row = candidate; + ++next; + } + + layoutRow(row, free, tiles); + } + + return tiles; +} diff --git a/src/core/treemap-layout.h b/src/core/treemap-layout.h new file mode 100644 index 0000000..4e7f3a3 --- /dev/null +++ b/src/core/treemap-layout.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include +#include + +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 squarify(const QVector &sizes, const QRectF &bounds);