From 977b1c35a90a18ace3a53feea19317558a5fe55c Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Thu, 26 Nov 2026 18:56:07 +0100 Subject: [PATCH] feat: add treemap disk space analyzer Users need to see at a glance what fills a disk and to remove the largest entries without digging through a file manager. The treemap makes sizes comparable, the scan runs off the UI thread, and removing an entry updates the tree in place instead of rescanning. --- CMakeLists.txt | 68 +++++ PKGBUILD | 31 +++ README.md | 67 +++++ packaging/fws-diskcleaner.desktop | 12 + packaging/fws-diskcleaner.svg | 10 + run.sh | 12 + src/main.cpp | 23 ++ src/ui/main-window.cpp | 448 ++++++++++++++++++++++++++++++ src/ui/main-window.h | 61 ++++ src/ui/treemap-widget.cpp | 362 ++++++++++++++++++++++++ src/ui/treemap-widget.h | 59 ++++ tests/disk-node.test.cpp | 65 +++++ tests/disk-scanner.test.cpp | 114 ++++++++ tests/test-helpers.h | 45 +++ tests/treemap-layout.test.cpp | 84 ++++++ 15 files changed, 1461 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 PKGBUILD create mode 100644 README.md create mode 100644 packaging/fws-diskcleaner.desktop create mode 100644 packaging/fws-diskcleaner.svg create mode 100755 run.sh create mode 100644 src/main.cpp create mode 100644 src/ui/main-window.cpp create mode 100644 src/ui/main-window.h create mode 100644 src/ui/treemap-widget.cpp create mode 100644 src/ui/treemap-widget.h create mode 100644 tests/disk-node.test.cpp create mode 100644 tests/disk-scanner.test.cpp create mode 100644 tests/test-helpers.h create mode 100644 tests/treemap-layout.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..d364deb --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,68 @@ +cmake_minimum_required(VERSION 3.21) + +# The version is stored once, at the repository root, so the Arch package and +# the running application cannot disagree about it. +file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/version" FWS_DISKCLEANER_VERSION LIMIT_COUNT 1) +string(STRIP "${FWS_DISKCLEANER_VERSION}" FWS_DISKCLEANER_VERSION) + +project(fws-diskcleaner VERSION ${FWS_DISKCLEANER_VERSION} LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(Qt6 6.4 REQUIRED COMPONENTS Core Gui Widgets) +qt_standard_project_setup() + +# Scanning and geometry stay free of widgets so they can be tested without a +# display and reused by a future command-line mode. +add_library(fws-diskcleaner-core STATIC + src/core/disk-node.cpp + src/core/disk-node.h + src/core/disk-scanner.cpp + src/core/disk-scanner.h + src/core/format.h + src/core/treemap-layout.cpp + src/core/treemap-layout.h +) +# Includes are written from `src/` (`core/...`, `ui/...`) so the layout of the +# tree is visible in every include directive. +target_include_directories(fws-diskcleaner-core PUBLIC src) +target_link_libraries(fws-diskcleaner-core PUBLIC Qt6::Core) + +qt_add_executable(fws-diskcleaner + src/main.cpp + src/ui/main-window.cpp + src/ui/main-window.h + src/ui/treemap-widget.cpp + src/ui/treemap-widget.h +) +target_link_libraries(fws-diskcleaner PRIVATE fws-diskcleaner-core Qt6::Widgets) + +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(fws-diskcleaner-core PRIVATE -Wall -Wextra) + target_compile_options(fws-diskcleaner PRIVATE -Wall -Wextra) +endif() + +include(GNUInstallDirs) +install(TARGETS fws-diskcleaner RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") +install(FILES packaging/fws-diskcleaner.desktop + DESTINATION "${CMAKE_INSTALL_DATADIR}/applications") +install(FILES packaging/fws-diskcleaner.svg + DESTINATION "${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps") + +include(CTest) +if(BUILD_TESTING) + find_package(Qt6 6.4 REQUIRED COMPONENTS Test) + + add_executable(disk-node-test tests/disk-node.test.cpp tests/test-helpers.h) + target_link_libraries(disk-node-test PRIVATE fws-diskcleaner-core Qt6::Test) + add_test(NAME disk-node COMMAND disk-node-test) + + add_executable(disk-scanner-test tests/disk-scanner.test.cpp tests/test-helpers.h) + target_link_libraries(disk-scanner-test PRIVATE fws-diskcleaner-core Qt6::Test) + add_test(NAME disk-scanner COMMAND disk-scanner-test) + + add_executable(treemap-layout-test tests/treemap-layout.test.cpp) + target_link_libraries(treemap-layout-test PRIVATE fws-diskcleaner-core Qt6::Test) + add_test(NAME treemap-layout COMMAND treemap-layout-test) +endif() diff --git a/PKGBUILD b/PKGBUILD new file mode 100644 index 0000000..2e43dd5 --- /dev/null +++ b/PKGBUILD @@ -0,0 +1,31 @@ +# Maintainer: FWS +pkgname=fws-diskcleaner +pkgver=$(tr -d '[:space:]' < version) +pkgrel=1 +pkgdesc='Visual disk usage analyzer with a treemap view' +arch=('x86_64') +license=('custom') +depends=('qt6-base') +makedepends=('cmake' 'gcc') + +# The release workflow builds this tarball with `git archive` next to the +# PKGBUILD, so the source is local and has no upstream checksum to verify. +source=("$pkgname-$pkgver.tar.gz") +sha256sums=('SKIP') + +build() { + cd "$pkgname-$pkgver" + cmake -B build -S . \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX=/usr + cmake --build build +} + +check() { + cd "$pkgname-$pkgver" + ctest --test-dir build --output-on-failure +} + +package() { + DESTDIR="$pkgdir" cmake --install "$pkgname-$pkgver/build" +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..719ac98 --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# FWS DiskCleaner + +Analyseur d'espace disque visuel pour FWS ISO. Il parcourt un dossier puis +affiche son contenu sous forme de **treemap** : chaque carré est un fichier ou un +dossier, et sa surface est proportionnelle à la place qu'il occupe. Les plus gros +éléments sautent donc aux yeux immédiatement. + +## Fonctionnalités + +- Analyse récursive d'un dossier (fichiers cachés compris) sur un thread séparé, + avec progression et annulation. +- Treemap « squarified » : les plus gros éléments en premier, nom et taille + affichés quand le carré est assez grand, couleurs vives par type de fichier et + par dossier. +- Clic sur un carré : sélection et panneau de détail (taille, part de l'espace + analysé, chemin, nombre de fichiers, boutons de suppression). +- Double-clic sur un dossier : on entre dedans. Bouton « Remonter » pour sortir. +- Suppression vers la corbeille (par défaut, restaurable) ou définitive, toujours + après confirmation. La carte se met à jour sans réanalyser tout le disque. +- Clic droit sur un carré : menu contextuel avec les mêmes actions. + +## Compilation + +```bash +cmake -B build -S . -DCMAKE_BUILD_TYPE=Release +cmake --build build +ctest --test-dir build --output-on-failure +./build/fws-diskcleaner ~/Téléchargements +``` + +Ou, pour compiler puis lancer directement : + +```bash +./run.sh ~/Téléchargements +``` + +Rien n'est analysé au lancement : choisissez un dossier avec « Choisir un +dossier… », ou passez-le en argument (`./run.sh ~/Téléchargements`) pour lancer +l'analyse immédiatement. + +## Organisation du code + +``` +src/ + main.cpp point d'entrée + core/ modèle de l'arbre, scanneur, formats et géométrie du treemap + ui/ fenêtre principale et widget de treemap +``` + +Tout ce qui se trouve dans `core/` ne dépend que de QtCore et reste testable sans +écran ; les includes s'écrivent depuis `src/` (`core/…`, `ui/…`). + +## Paquet Arch + +`PKGBUILD` construit le paquet à partir de l'archive produite par +`.gitea/workflows/package.yml`, qui déclenche une release à chaque changement du +fichier `version`. + +## Limites + +- Les tailles sont **apparentes** (somme des tailles de fichiers), pas l'espace + réellement occupé sur le disque (blocs alloués). +- Les liens symboliques sont ignorés pour éviter les boucles ; un lien physique + est compté une fois par lien. +- La suppression définitive est immédiate : préférer la corbeille en cas de doute. +- Un disque entier reste analysable, mais les carrés trop petits pour être dessinés + ne sont pas cliquables : entrez dans un dossier pour voir son contenu en détail. diff --git a/packaging/fws-diskcleaner.desktop b/packaging/fws-diskcleaner.desktop new file mode 100644 index 0000000..c4a94ad --- /dev/null +++ b/packaging/fws-diskcleaner.desktop @@ -0,0 +1,12 @@ +[Desktop Entry] +Type=Application +Name=FWS DiskCleaner +GenericName=Disk Usage Analyzer +GenericName[fr]=Analyseur d'espace disque +Comment=Find what takes up space on your disks and clean it up +Comment[fr]=Repérez ce qui occupe vos disques et nettoyez +Exec=fws-diskcleaner %f +Icon=fws-diskcleaner +Terminal=false +Categories=System;Filesystem;Utility; +Keywords=disk;space;usage;treemap;clean;storage; diff --git a/packaging/fws-diskcleaner.svg b/packaging/fws-diskcleaner.svg new file mode 100644 index 0000000..e2c70bb --- /dev/null +++ b/packaging/fws-diskcleaner.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..ac41336 --- /dev/null +++ b/run.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Configure, build and launch the disk cleaner. Nothing is scanned unless a +# folder is given: ./run.sh ~/Téléchargements +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +build="$root/build" + +cmake -B "$build" -S "$root" -DCMAKE_BUILD_TYPE=Release +cmake --build "$build" --parallel + +exec "$build/fws-diskcleaner" "$@" diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..4b6282b --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,23 @@ +#include "ui/main-window.h" + +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QApplication::setApplicationName(QStringLiteral("FWS DiskCleaner")); + QApplication::setApplicationDisplayName(QStringLiteral("FWS DiskCleaner")); + QApplication::setDesktopFileName(QStringLiteral("fws-diskcleaner")); + QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("fws-diskcleaner"))); + + QString startPath; + const QStringList arguments = QApplication::arguments(); + if (arguments.size() > 1) { + startPath = arguments.at(1); + } + + MainWindow window(startPath); + window.show(); + return app.exec(); +} diff --git a/src/ui/main-window.cpp b/src/ui/main-window.cpp new file mode 100644 index 0000000..e38f71c --- /dev/null +++ b/src/ui/main-window.cpp @@ -0,0 +1,448 @@ +#include "ui/main-window.h" + +#include "core/disk-node.h" +#include "core/disk-scanner.h" +#include "core/format.h" +#include "ui/treemap-widget.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MainWindow::MainWindow(const QString &startPath, QWidget *parent) + : QMainWindow(parent) +{ + buildUi(); + + // Never scan on startup: analysing a folder is an explicit user action, + // either through the folder picker or through the command line argument. + if (!startPath.isEmpty()) { + startScan(startPath); + } else { + m_statusLabel->setText(tr("Prêt. Choisissez un dossier à analyser.")); + } +} + +MainWindow::~MainWindow() +{ + stopScanning(); +} + +void MainWindow::buildUi() +{ + setWindowTitle(tr("FWS DiskCleaner")); + setWindowIcon(QIcon::fromTheme(QStringLiteral("fws-diskcleaner"))); + resize(1180, 760); + + auto *central = new QWidget(this); + auto *rootLayout = new QVBoxLayout(central); + rootLayout->setContentsMargins(8, 8, 8, 8); + rootLayout->setSpacing(6); + + auto *toolbar = new QHBoxLayout; + toolbar->setSpacing(6); + + m_upButton = new QToolButton(central); + m_upButton->setText(tr("Remonter")); + m_upButton->setToolButtonStyle(Qt::ToolButtonTextOnly); + m_upButton->setEnabled(false); + connect(m_upButton, &QToolButton::clicked, this, [this] { + if (m_current && m_current->parent) { + showDirectory(m_current->parent); + } + }); + + m_pathEdit = new QLineEdit(central); + m_pathEdit->setReadOnly(true); + m_pathEdit->setPlaceholderText(tr("Aucun dossier analysé")); + m_pathEdit->setToolTip(tr("Dossier affiché")); + + m_chooseButton = new QPushButton(tr("Choisir un dossier…"), central); + connect(m_chooseButton, &QPushButton::clicked, this, &MainWindow::chooseFolder); + + m_rescanButton = new QPushButton(tr("Réanalyser"), central); + m_rescanButton->setEnabled(false); + connect(m_rescanButton, &QPushButton::clicked, this, [this] { + if (!m_scanRoot.isEmpty()) { + startScan(m_scanRoot); + } + }); + + toolbar->addWidget(m_upButton); + toolbar->addWidget(m_pathEdit, 1); + toolbar->addWidget(m_chooseButton); + toolbar->addWidget(m_rescanButton); + + m_treemap = new TreemapWidget(central); + connect(m_treemap, &TreemapWidget::selectionChanged, this, &MainWindow::updateSelection); + connect(m_treemap, &TreemapWidget::directoryActivated, this, &MainWindow::showDirectory); + connect(m_treemap, &TreemapWidget::contextMenuRequested, this, &MainWindow::showContextMenu); + + auto *details = new QWidget(central); + details->setMinimumWidth(280); + details->setMaximumWidth(420); + auto *detailsLayout = new QVBoxLayout(details); + detailsLayout->setContentsMargins(4, 0, 4, 0); + detailsLayout->setSpacing(8); + + auto *detailsTitle = new QLabel(tr("Détails"), details); + QFont titleFont = detailsTitle->font(); + titleFont.setBold(true); + detailsTitle->setFont(titleFont); + + m_nameLabel = new QLabel(tr("Aucune sélection"), details); + m_nameLabel->setWordWrap(true); + QFont nameFont = m_nameLabel->font(); + nameFont.setBold(true); + if (nameFont.pointSize() > 0) { + nameFont.setPointSize(nameFont.pointSize() + 2); + } + m_nameLabel->setFont(nameFont); + + m_pathLabel = new QLabel(details); + m_pathLabel->setWordWrap(true); + m_pathLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); + + m_sizeLabel = new QLabel(details); + m_shareLabel = new QLabel(details); + m_kindLabel = new QLabel(details); + + m_openButton = new QPushButton(tr("Voir le contenu"), details); + m_trashButton = new QPushButton(tr("Mettre à la corbeille"), details); + m_deleteButton = new QPushButton(tr("Supprimer définitivement"), details); + connect(m_openButton, &QPushButton::clicked, this, [this] { + showDirectory(m_selected); + }); + connect(m_trashButton, &QPushButton::clicked, this, [this] { + removeNode(m_selected, true); + }); + connect(m_deleteButton, &QPushButton::clicked, this, [this] { + removeNode(m_selected, false); + }); + + auto *hint = new QLabel( + tr("Cliquez sur un carré pour le sélectionner, double-cliquez sur un dossier pour " + "l'explorer."), + details); + hint->setWordWrap(true); + + detailsLayout->addWidget(detailsTitle); + detailsLayout->addWidget(m_nameLabel); + detailsLayout->addWidget(m_pathLabel); + detailsLayout->addSpacing(6); + detailsLayout->addWidget(m_sizeLabel); + detailsLayout->addWidget(m_shareLabel); + detailsLayout->addWidget(m_kindLabel); + detailsLayout->addSpacing(10); + detailsLayout->addWidget(m_openButton); + detailsLayout->addWidget(m_trashButton); + detailsLayout->addWidget(m_deleteButton); + detailsLayout->addStretch(1); + detailsLayout->addWidget(hint); + + auto *splitter = new QSplitter(Qt::Horizontal, central); + splitter->addWidget(m_treemap); + splitter->addWidget(details); + splitter->setStretchFactor(0, 1); + splitter->setStretchFactor(1, 0); + splitter->setChildrenCollapsible(false); + + rootLayout->addLayout(toolbar); + rootLayout->addWidget(splitter, 1); + setCentralWidget(central); + + m_statusLabel = new QLabel(tr("Prêt."), this); + m_progress = new QProgressBar(this); + m_progress->setRange(0, 0); + m_progress->setMaximumWidth(140); + m_progress->setTextVisible(false); + m_progress->setVisible(false); + + m_cancelButton = new QPushButton(tr("Annuler"), this); + m_cancelButton->setVisible(false); + connect(m_cancelButton, &QPushButton::clicked, this, [this] { + if (m_scanner) { + m_scanner->cancel(); + m_cancelButton->setEnabled(false); + m_statusLabel->setText(tr("Annulation…")); + } + }); + + statusBar()->addWidget(m_statusLabel, 1); + statusBar()->addPermanentWidget(m_progress); + statusBar()->addPermanentWidget(m_cancelButton); + + updateSelection(nullptr); +} + +void MainWindow::startScan(const QString &path) +{ + const QFileInfo info(path); + if (!info.exists() || !info.isDir()) { + QMessageBox::warning(this, tr("Dossier introuvable"), + tr("%1 n'est pas un dossier.").arg(path)); + return; + } + + stopScanning(); + + m_scanRoot = info.absoluteFilePath(); + m_tree.reset(); + m_current = nullptr; + m_selected = nullptr; + m_treemap->setTree(nullptr); + m_pathEdit->setText(m_scanRoot); + m_pathEdit->setCursorPosition(0); + setWindowTitle(tr("FWS DiskCleaner — %1").arg(m_scanRoot)); + updateSelection(nullptr); + setBusy(true); + m_statusLabel->setText(tr("Analyse de %1…").arg(m_scanRoot)); + + m_scanner = new DiskScanner(m_scanRoot, this); + connect(m_scanner, &QThread::finished, this, &MainWindow::handleScanFinished); + connect(m_scanner, &DiskScanner::progress, this, + [this](const QString ¤t, quint64 bytes) { + const QString shown = current.size() > 64 + ? QStringLiteral("…") + current.right(63) + : current; + m_statusLabel->setText(tr("Analyse de %1 — %2").arg(shown, formatBytes(bytes))); + }); + m_scanner->start(); +} + +void MainWindow::stopScanning() +{ + if (!m_scanner) { + return; + } + DiskScanner *scanner = m_scanner; + m_scanner = nullptr; + scanner->disconnect(this); + scanner->cancel(); + scanner->wait(); + delete scanner; +} + +void MainWindow::handleScanFinished() +{ + if (!m_scanner) { + return; + } + DiskScanner *scanner = m_scanner; + m_scanner = nullptr; + + const std::shared_ptr tree = scanner->takeTree(); + const ScanStats stats = scanner->stats(); + scanner->deleteLater(); + + setBusy(false); + + if (!tree) { + m_statusLabel->setText(tr("Analyse annulée.")); + return; + } + + m_tree = tree; + m_treemap->setTree(m_tree); + m_treemap->setCurrent(m_tree.get()); + m_current = m_tree.get(); + updateHeader(); + updateSelection(nullptr); + + QString summary = tr("%1 · %2 fichiers").arg(formatBytes(m_tree->totalSize), + QLocale().toString(m_tree->fileCount)); + if (!stats.errors.isEmpty()) { + summary += tr(" · %1 élément(s) ignoré(s)").arg(stats.errors.size()); + } + m_statusLabel->setText(summary); + m_statusLabel->setToolTip(stats.errors.join(QLatin1Char('\n'))); +} + +void MainWindow::setBusy(bool busy) +{ + m_progress->setVisible(busy); + m_cancelButton->setVisible(busy); + m_cancelButton->setEnabled(busy); + m_treemap->setEnabled(!busy); + m_chooseButton->setEnabled(!busy); + m_rescanButton->setEnabled(!busy && !m_scanRoot.isEmpty()); + m_upButton->setEnabled(!busy && m_current && m_current->parent); + if (busy) { + m_openButton->setEnabled(false); + m_trashButton->setEnabled(false); + m_deleteButton->setEnabled(false); + } +} + +void MainWindow::showDirectory(DiskNode *node) +{ + if (!node || !node->isDirectory() || !m_tree) { + return; + } + + m_current = node; + m_selected = nullptr; + m_treemap->setCurrent(node); + updateHeader(); + updateSelection(nullptr); +} + +void MainWindow::updateSelection(DiskNode *node) +{ + m_selected = node; + + if (!node) { + m_nameLabel->setText(tr("Aucune sélection")); + m_pathLabel->setText( + tr("Cliquez sur un carré pour voir sa taille, son chemin et le supprimer. " + "Double-cliquez sur un dossier pour l'explorer.")); + m_pathLabel->setToolTip(QString()); + m_sizeLabel->clear(); + m_shareLabel->clear(); + m_kindLabel->clear(); + m_openButton->setEnabled(false); + m_trashButton->setEnabled(false); + m_deleteButton->setEnabled(false); + return; + } + + m_nameLabel->setText(node->name); + m_pathLabel->setText(node->path); + m_pathLabel->setToolTip(node->path); + m_sizeLabel->setText(tr("Taille : %1").arg(formatBytes(node->totalSize))); + + const double share = (m_tree && m_tree->totalSize > 0) + ? 100.0 * static_cast(node->totalSize) / static_cast(m_tree->totalSize) + : 0.0; + m_shareLabel->setText( + tr("%1 % de l'espace analysé").arg(QLocale().toString(share, 'f', 1))); + + m_kindLabel->setText(node->isDirectory() + ? tr("Dossier · %1 fichiers").arg(QLocale().toString(node->fileCount)) + : tr("Fichier")); + + m_openButton->setEnabled(node->isDirectory()); + const bool removable = canRemove(node); + m_trashButton->setEnabled(removable); + m_deleteButton->setEnabled(removable); +} + +void MainWindow::updateHeader() +{ + if (!m_current) { + m_upButton->setEnabled(false); + return; + } + m_pathEdit->setText(m_current->path); + m_pathEdit->setCursorPosition(0); + m_upButton->setEnabled(m_current->parent != nullptr); + setWindowTitle(tr("FWS DiskCleaner — %1").arg(m_current->name)); +} + +void MainWindow::chooseFolder() +{ + const QString start = m_current ? m_current->path : QDir::homePath(); + const QString directory = + QFileDialog::getExistingDirectory(this, tr("Choisir un dossier à analyser"), start); + if (!directory.isEmpty()) { + startScan(directory); + } +} + +void MainWindow::showContextMenu(DiskNode *node, const QPoint &globalPos) +{ + if (!node) { + return; + } + + QMenu menu(this); + if (node->isDirectory()) { + QAction *open = menu.addAction(tr("Voir le contenu")); + connect(open, &QAction::triggered, this, [this, node] { showDirectory(node); }); + menu.addSeparator(); + } + + QAction *trash = menu.addAction(tr("Mettre à la corbeille")); + trash->setEnabled(canRemove(node)); + connect(trash, &QAction::triggered, this, [this, node] { removeNode(node, true); }); + + QAction *remove = menu.addAction(tr("Supprimer définitivement")); + remove->setEnabled(canRemove(node)); + connect(remove, &QAction::triggered, this, [this, node] { removeNode(node, false); }); + + menu.exec(globalPos); +} + +bool MainWindow::canRemove(const DiskNode *node) const +{ + return node && m_tree && node != m_tree.get() && node->parent + && node->path != QLatin1String("/"); +} + +void MainWindow::removeNode(DiskNode *node, bool toTrash) +{ + if (!canRemove(node)) { + return; + } + + const QString path = node->path; + const QString name = node->name; + const quint64 size = node->totalSize; + const QString action = toTrash ? tr("Déplacer vers la corbeille") + : tr("Supprimer définitivement"); + + QMessageBox box(QMessageBox::Warning, action, path, QMessageBox::NoButton, this); + box.setInformativeText( + tr("%1\n\n%2") + .arg(formatBytes(size), + toTrash ? tr("L'élément part dans la corbeille et pourra être restauré.") + : tr("Cette action est immédiate et ne peut pas être annulée."))); + QPushButton *confirm = box.addButton(action, QMessageBox::DestructiveRole); + box.addButton(QMessageBox::Cancel); + box.setDefaultButton(QMessageBox::Cancel); + box.exec(); + if (box.clickedButton() != confirm) { + return; + } + + bool removed = false; + if (toTrash) { + removed = QFile::moveToTrash(path); + } else { + const QFileInfo info(path); + removed = info.isDir() ? QDir(path).removeRecursively() : QFile::remove(path); + } + + if (!removed) { + QMessageBox::critical(this, tr("Suppression impossible"), + tr("Le système a refusé de supprimer :\n%1").arg(path)); + return; + } + + // Every pointer into the subtree must be dropped before the node is freed. + m_treemap->clearSelection(); + m_selected = nullptr; + std::unique_ptr detached = detachNode(node); + detached.reset(); + + m_treemap->refreshLayout(); + updateSelection(nullptr); + updateHeader(); + m_statusLabel->setText(tr("%1 supprimé — %2 libérés").arg(name, formatBytes(size))); +} diff --git a/src/ui/main-window.h b/src/ui/main-window.h new file mode 100644 index 0000000..3e7d851 --- /dev/null +++ b/src/ui/main-window.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include + +#include + +struct DiskNode; +class DiskScanner; +class QLabel; +class QLineEdit; +class QProgressBar; +class QPushButton; +class QToolButton; +class TreemapWidget; + +class MainWindow : public QMainWindow { + Q_OBJECT + +public: + explicit MainWindow(const QString &startPath = QString(), QWidget *parent = nullptr); + ~MainWindow() override; + +private: + void buildUi(); + void startScan(const QString &path); + void stopScanning(); + void handleScanFinished(); + void setBusy(bool busy); + void showDirectory(DiskNode *node); + void updateSelection(DiskNode *node); + void updateHeader(); + void chooseFolder(); + void showContextMenu(DiskNode *node, const QPoint &globalPos); + void removeNode(DiskNode *node, bool toTrash); + bool canRemove(const DiskNode *node) const; + + std::shared_ptr m_tree; + QString m_scanRoot; + DiskScanner *m_scanner = nullptr; + DiskNode *m_current = nullptr; + DiskNode *m_selected = nullptr; + + TreemapWidget *m_treemap = nullptr; + QToolButton *m_upButton = nullptr; + QLineEdit *m_pathEdit = nullptr; + QPushButton *m_chooseButton = nullptr; + QPushButton *m_rescanButton = nullptr; + QLabel *m_nameLabel = nullptr; + QLabel *m_pathLabel = nullptr; + QLabel *m_sizeLabel = nullptr; + QLabel *m_shareLabel = nullptr; + QLabel *m_kindLabel = nullptr; + QPushButton *m_openButton = nullptr; + QPushButton *m_trashButton = nullptr; + QPushButton *m_deleteButton = nullptr; + QLabel *m_statusLabel = nullptr; + QProgressBar *m_progress = nullptr; + QPushButton *m_cancelButton = nullptr; +}; diff --git a/src/ui/treemap-widget.cpp b/src/ui/treemap-widget.cpp new file mode 100644 index 0000000..5de0d35 --- /dev/null +++ b/src/ui/treemap-widget.cpp @@ -0,0 +1,362 @@ +#include "ui/treemap-widget.h" + +#include "core/format.h" +#include "core/treemap-layout.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace { + +constexpr qreal kOuterMargin = 3.0; +constexpr qreal kTileInset = 1.0; +constexpr qreal kMinimumLabelWidth = 64.0; +constexpr qreal kMinimumLabelHeight = 22.0; +constexpr qreal kSizeLabelMinimumHeight = 42.0; + +const QColor kBackground(0x1c, 0x1e, 0x23); +const QColor kMutedText(0x8a, 0x90, 0x9c); + +enum class FileFamily { + Video, + Image, + Audio, + Archive, + Document, + Code, + Other, +}; + +FileFamily familyForSuffix(const QString &suffix) +{ + static const QHash families{ + {QStringLiteral("mkv"), FileFamily::Video}, {QStringLiteral("mp4"), FileFamily::Video}, + {QStringLiteral("avi"), FileFamily::Video}, {QStringLiteral("mov"), FileFamily::Video}, + {QStringLiteral("webm"), FileFamily::Video}, {QStringLiteral("wmv"), FileFamily::Video}, + {QStringLiteral("m4v"), FileFamily::Video}, {QStringLiteral("jpg"), FileFamily::Image}, + {QStringLiteral("jpeg"), FileFamily::Image}, {QStringLiteral("png"), FileFamily::Image}, + {QStringLiteral("gif"), FileFamily::Image}, {QStringLiteral("bmp"), FileFamily::Image}, + {QStringLiteral("webp"), FileFamily::Image}, {QStringLiteral("svg"), FileFamily::Image}, + {QStringLiteral("heic"), FileFamily::Image}, {QStringLiteral("tiff"), FileFamily::Image}, + {QStringLiteral("raw"), FileFamily::Image}, {QStringLiteral("mp3"), FileFamily::Audio}, + {QStringLiteral("flac"), FileFamily::Audio}, {QStringLiteral("ogg"), FileFamily::Audio}, + {QStringLiteral("wav"), FileFamily::Audio}, {QStringLiteral("m4a"), FileFamily::Audio}, + {QStringLiteral("opus"), FileFamily::Audio}, {QStringLiteral("aac"), FileFamily::Audio}, + {QStringLiteral("zip"), FileFamily::Archive}, {QStringLiteral("tar"), FileFamily::Archive}, + {QStringLiteral("gz"), FileFamily::Archive}, {QStringLiteral("xz"), FileFamily::Archive}, + {QStringLiteral("zst"), FileFamily::Archive}, {QStringLiteral("7z"), FileFamily::Archive}, + {QStringLiteral("rar"), FileFamily::Archive}, {QStringLiteral("bz2"), FileFamily::Archive}, + {QStringLiteral("iso"), FileFamily::Archive}, {QStringLiteral("img"), FileFamily::Archive}, + {QStringLiteral("pdf"), FileFamily::Document}, {QStringLiteral("doc"), FileFamily::Document}, + {QStringLiteral("docx"), FileFamily::Document}, {QStringLiteral("odt"), FileFamily::Document}, + {QStringLiteral("txt"), FileFamily::Document}, {QStringLiteral("md"), FileFamily::Document}, + {QStringLiteral("xls"), FileFamily::Document}, {QStringLiteral("xlsx"), FileFamily::Document}, + {QStringLiteral("ods"), FileFamily::Document}, {QStringLiteral("ppt"), FileFamily::Document}, + {QStringLiteral("pptx"), FileFamily::Document}, {QStringLiteral("odp"), FileFamily::Document}, + {QStringLiteral("epub"), FileFamily::Document}, {QStringLiteral("c"), FileFamily::Code}, + {QStringLiteral("h"), FileFamily::Code}, {QStringLiteral("cpp"), FileFamily::Code}, + {QStringLiteral("hpp"), FileFamily::Code}, {QStringLiteral("cc"), FileFamily::Code}, + {QStringLiteral("py"), FileFamily::Code}, {QStringLiteral("rs"), FileFamily::Code}, + {QStringLiteral("go"), FileFamily::Code}, {QStringLiteral("js"), FileFamily::Code}, + {QStringLiteral("ts"), FileFamily::Code}, {QStringLiteral("java"), FileFamily::Code}, + {QStringLiteral("sh"), FileFamily::Code}, {QStringLiteral("qml"), FileFamily::Code}, + {QStringLiteral("html"), FileFamily::Code}, {QStringLiteral("css"), FileFamily::Code}, + {QStringLiteral("json"), FileFamily::Code}, {QStringLiteral("xml"), FileFamily::Code}, + {QStringLiteral("yaml"), FileFamily::Code}, {QStringLiteral("yml"), FileFamily::Code}, + {QStringLiteral("toml"), FileFamily::Code}, + }; + return families.value(suffix, FileFamily::Other); +} + +QString suffixOf(const QString &name) +{ + const int dot = name.lastIndexOf(QLatin1Char('.')); + return dot > 0 ? name.mid(dot + 1).toLower() : QString(); +} + +QColor colorForNode(const DiskNode &node) +{ + const quint32 hash = static_cast(qHash(node.name)); + // A wider jitter than the family width keeps neighbours from looking flat. + const int jitter = static_cast(hash % 29) - 14; + + if (node.isDirectory()) { + // Directories share a violet-blue band so they still read as containers, + // but strong saturation gives each folder its own visible colour. + return QColor::fromHsv((246 + static_cast(hash % 46) + jitter + 360) % 360, 198, + 172 + static_cast(hash % 34)); + } + + int hue = 214; + int saturation = 172; + switch (familyForSuffix(suffixOf(node.name))) { + case FileFamily::Video: + hue = 272; + saturation = 215; + break; + case FileFamily::Image: + hue = 142; + saturation = 205; + break; + case FileFamily::Audio: + hue = 186; + saturation = 212; + break; + case FileFamily::Archive: + hue = 22; + saturation = 235; + break; + case FileFamily::Document: + hue = 50; + saturation = 225; + break; + case FileFamily::Code: + hue = 100; + saturation = 168; + break; + case FileFamily::Other: + break; + } + + return QColor::fromHsv((hue + jitter + 360) % 360, saturation, + 204 - static_cast(hash % 34)); +} + +QColor labelColor(const QColor &background) +{ + return background.lightness() > 145 ? QColor(24, 26, 30) : QColor(240, 242, 246); +} + +} // namespace + +TreemapWidget::TreemapWidget(QWidget *parent) + : QWidget(parent) +{ + setMouseTracking(true); + setMinimumSize(320, 240); + setAutoFillBackground(false); +} + +void TreemapWidget::setTree(std::shared_ptr root) +{ + m_tree = std::move(root); + m_current = nullptr; + m_selected = nullptr; + m_hovered = nullptr; + m_tiles.clear(); + update(); +} + +void TreemapWidget::setCurrent(DiskNode *node) +{ + m_current = node; + m_selected = nullptr; + m_hovered = nullptr; + refreshLayout(); +} + +void TreemapWidget::clearSelection() +{ + if (!m_selected) { + return; + } + m_selected = nullptr; + update(); + emit selectionChanged(nullptr); +} + +void TreemapWidget::refreshLayout() +{ + m_tiles.clear(); + + if (!m_current) { + update(); + return; + } + + const QRectF content = QRectF(rect()).adjusted(kOuterMargin, kOuterMargin, -kOuterMargin, + -kOuterMargin); + + QVector sizes; + QVector nodes; + sizes.reserve(static_cast(m_current->children.size())); + nodes.reserve(static_cast(m_current->children.size())); + for (const auto &child : m_current->children) { + if (child->totalSize == 0) { + continue; // an empty entry has no surface to show + } + sizes.append(static_cast(child->totalSize)); + nodes.append(child.get()); + } + + const QVector tiles = squarify(sizes, content); + for (const TreemapTile &tile : tiles) { + const QRectF tileRect = + tile.rect.adjusted(kTileInset, kTileInset, -kTileInset, -kTileInset); + if (tileRect.width() > 0.0 && tileRect.height() > 0.0) { + m_tiles.append({nodes.at(tile.index), tileRect}); + } + } + + update(); +} + +void TreemapWidget::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event) + + QPainter painter(this); + painter.fillRect(rect(), kBackground); + + if (!m_current) { + painter.setPen(kMutedText); + painter.drawText(rect().adjusted(24, 24, -24, -24), Qt::AlignCenter | Qt::TextWordWrap, + tr("Aucun élément à afficher.\n\nChoisissez un dossier puis lancez " + "l'analyse.")); + return; + } + + if (m_tiles.isEmpty()) { + painter.setPen(kMutedText); + painter.drawText(rect().adjusted(24, 24, -24, -24), Qt::AlignCenter | Qt::TextWordWrap, + tr("%1 ne contient aucun fichier.").arg(m_current->name)); + return; + } + + QFont labelFont = font(); + labelFont.setPointSizeF(std::max(7.5, labelFont.pointSizeF())); + const QFontMetricsF metrics(labelFont); + + for (const Tile &tile : m_tiles) { + if (tile.rect.width() < 1.0 || tile.rect.height() < 1.0) { + continue; + } + + QColor color = colorForNode(*tile.node); + if (tile.node == m_hovered) { + color = color.lighter(118); + } + if (tile.node == m_selected) { + color = color.lighter(126); + } + painter.fillRect(tile.rect, color); + + if (tile.rect.width() >= kMinimumLabelWidth + && tile.rect.height() >= kMinimumLabelHeight) { + painter.setFont(labelFont); + painter.setPen(labelColor(color)); + const QRectF textRect = tile.rect.adjusted(4, 2, -4, -2); + painter.drawText(textRect, Qt::AlignLeft | Qt::AlignTop, + metrics.elidedText(tile.node->name, Qt::ElideMiddle, + textRect.width())); + if (tile.rect.height() >= kSizeLabelMinimumHeight) { + painter.drawText(textRect, Qt::AlignLeft | Qt::AlignBottom, + formatBytes(tile.node->totalSize)); + } + } + } + + if (m_hovered) { + for (const Tile &tile : m_tiles) { + if (tile.node != m_hovered) { + continue; + } + painter.setPen(QPen(QColor(255, 255, 255, 110), 1)); + painter.drawRect(tile.rect.adjusted(0.5, 0.5, -0.5, -0.5)); + break; + } + } + + if (m_selected) { + for (const Tile &tile : m_tiles) { + if (tile.node != m_selected) { + continue; + } + painter.setPen(QPen(QColor(0xf4, 0xf6, 0xfa), 2)); + painter.drawRect(tile.rect.adjusted(1, 1, -1, -1)); + break; + } + } +} + +void TreemapWidget::resizeEvent(QResizeEvent *event) +{ + QWidget::resizeEvent(event); + refreshLayout(); +} + +void TreemapWidget::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + select(nodeAt(event->position())); + } + QWidget::mousePressEvent(event); +} + +void TreemapWidget::mouseMoveEvent(QMouseEvent *event) +{ + DiskNode *node = nodeAt(event->position()); + if (node != m_hovered) { + m_hovered = node; + setCursor(node ? Qt::PointingHandCursor : Qt::ArrowCursor); + setToolTip(node ? tr("%1 — %2").arg(node->name, formatBytes(node->totalSize)) + : QString()); + update(); + } + QWidget::mouseMoveEvent(event); +} + +void TreemapWidget::mouseDoubleClickEvent(QMouseEvent *event) +{ + DiskNode *node = nodeAt(event->position()); + if (node && node->isDirectory()) { + emit directoryActivated(node); + } + QWidget::mouseDoubleClickEvent(event); +} + +void TreemapWidget::leaveEvent(QEvent *event) +{ + if (m_hovered) { + m_hovered = nullptr; + update(); + } + QWidget::leaveEvent(event); +} + +void TreemapWidget::contextMenuEvent(QContextMenuEvent *event) +{ + DiskNode *node = nodeAt(event->pos()); + if (!node) { + return; + } + select(node); + emit contextMenuRequested(node, event->globalPos()); +} + +DiskNode *TreemapWidget::nodeAt(const QPointF &point) const +{ + for (const Tile &tile : m_tiles) { + if (tile.rect.contains(point)) { + return tile.node; + } + } + return nullptr; +} + +void TreemapWidget::select(DiskNode *node) +{ + if (m_selected == node) { + return; + } + m_selected = node; + update(); + emit selectionChanged(node); +} diff --git a/src/ui/treemap-widget.h b/src/ui/treemap-widget.h new file mode 100644 index 0000000..b3fe083 --- /dev/null +++ b/src/ui/treemap-widget.h @@ -0,0 +1,59 @@ +#pragma once + +#include "core/disk-node.h" + +#include +#include +#include + +#include + +class QContextMenuEvent; +class QMouseEvent; +class QPaintEvent; +class QResizeEvent; + +// Shows one directory as a squarified treemap: each child is a rectangle whose +// area is proportional to its size. Click selects, double-click drills down. +class TreemapWidget : public QWidget { + Q_OBJECT + +public: + explicit TreemapWidget(QWidget *parent = nullptr); + + void setTree(std::shared_ptr root); + void setCurrent(DiskNode *node); + DiskNode *current() const { return m_current; } + DiskNode *selected() const { return m_selected; } + void clearSelection(); + void refreshLayout(); + +signals: + void selectionChanged(DiskNode *node); + void directoryActivated(DiskNode *node); + void contextMenuRequested(DiskNode *node, const QPoint &globalPos); + +protected: + void paintEvent(QPaintEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseDoubleClickEvent(QMouseEvent *event) override; + void leaveEvent(QEvent *event) override; + void contextMenuEvent(QContextMenuEvent *event) override; + +private: + struct Tile { + DiskNode *node = nullptr; + QRectF rect; + }; + + DiskNode *nodeAt(const QPointF &point) const; + void select(DiskNode *node); + + std::shared_ptr m_tree; + DiskNode *m_current = nullptr; + DiskNode *m_selected = nullptr; + DiskNode *m_hovered = nullptr; + QVector m_tiles; +}; diff --git a/tests/disk-node.test.cpp b/tests/disk-node.test.cpp new file mode 100644 index 0000000..387a5d4 --- /dev/null +++ b/tests/disk-node.test.cpp @@ -0,0 +1,65 @@ +#include "test-helpers.h" + +#include +#include +#include + +class DiskNodeTest : public QObject { + Q_OBJECT + +private slots: + void detachUpdatesAncestors(); + void detachKeepsSubtreeIntact(); + void detachRefusesTheRoot(); +}; + +void DiskNodeTest::detachUpdatesAncestors() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + QVERIFY(test_helpers::writeFile(dir.filePath("top.bin"), 100)); + QVERIFY(QDir().mkpath(dir.filePath("sub"))); + QVERIFY(test_helpers::writeFile(dir.filePath("sub/big.bin"), 900)); + + const std::shared_ptr tree = test_helpers::scan(dir.path()); + QVERIFY(tree); + QCOMPARE(tree->totalSize, quint64(1000)); + QCOMPARE(tree->fileCount, quint64(2)); + + DiskNode *sub = test_helpers::childNamed(*tree, "sub"); + QVERIFY(sub); + std::unique_ptr removed = detachNode(sub); + QVERIFY(removed); + + QCOMPARE(tree->totalSize, quint64(100)); + QCOMPARE(tree->fileCount, quint64(1)); + QCOMPARE(int(tree->children.size()), 1); +} + +void DiskNodeTest::detachKeepsSubtreeIntact() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + QVERIFY(QDir().mkpath(dir.filePath("sub/deep"))); + QVERIFY(test_helpers::writeFile(dir.filePath("sub/deep/leaf.bin"), 900)); + + const std::shared_ptr tree = test_helpers::scan(dir.path()); + QVERIFY(tree); + + std::unique_ptr removed = detachNode(test_helpers::childNamed(*tree, "sub")); + QVERIFY(removed); + QCOMPARE(removed->totalSize, quint64(900)); + QVERIFY(removed->parent == nullptr); + QVERIFY(test_helpers::childNamed(*removed, "deep") != nullptr); +} + +void DiskNodeTest::detachRefusesTheRoot() +{ + DiskNode root; + root.kind = NodeKind::Directory; + root.totalSize = 10; + QVERIFY(!detachNode(&root)); +} + +QTEST_GUILESS_MAIN(DiskNodeTest) +#include "disk-node.test.moc" diff --git a/tests/disk-scanner.test.cpp b/tests/disk-scanner.test.cpp new file mode 100644 index 0000000..95d9860 --- /dev/null +++ b/tests/disk-scanner.test.cpp @@ -0,0 +1,114 @@ +#include "test-helpers.h" + +#include +#include +#include +#include + +class DiskScannerTest : public QObject { + Q_OBJECT + +private slots: + void aggregatesNestedSizes(); + void sortsChildrenBySize(); + void skipsSymlinks(); + void reportsMissingDirectory(); + void cancellationBeforeStartYieldsNoTree(); +}; + +void DiskScannerTest::aggregatesNestedSizes() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + QVERIFY(test_helpers::writeFile(dir.filePath("top.bin"), 1000)); + QVERIFY(QDir().mkpath(dir.filePath("sub/deep"))); + QVERIFY(QDir().mkpath(dir.filePath("empty"))); + QVERIFY(test_helpers::writeFile(dir.filePath("sub/mid.bin"), 2000)); + QVERIFY(test_helpers::writeFile(dir.filePath("sub/deep/leaf.bin"), 3000)); + + ScanStats stats; + const std::shared_ptr tree = test_helpers::scan(dir.path(), &stats); + QVERIFY(tree); + + QCOMPARE(tree->totalSize, quint64(6000)); + QCOMPARE(tree->fileCount, quint64(3)); + QCOMPARE(stats.fileCount, quint64(3)); + QCOMPARE(stats.dirCount, quint64(3)); // sub, sub/deep, empty + QCOMPARE(stats.totalBytes, quint64(6000)); + + const DiskNode *sub = test_helpers::childNamed(*tree, "sub"); + QVERIFY(sub); + QCOMPARE(sub->totalSize, quint64(5000)); + QCOMPARE(sub->fileCount, quint64(2)); + + const DiskNode *deep = test_helpers::childNamed(*sub, "deep"); + QVERIFY(deep); + QCOMPARE(deep->totalSize, quint64(3000)); + + const DiskNode *empty = test_helpers::childNamed(*tree, "empty"); + QVERIFY(empty); + QCOMPARE(empty->totalSize, quint64(0)); + QCOMPARE(empty->fileCount, quint64(0)); +} + +void DiskScannerTest::sortsChildrenBySize() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + QVERIFY(test_helpers::writeFile(dir.filePath("small.bin"), 10)); + QVERIFY(test_helpers::writeFile(dir.filePath("large.bin"), 5000)); + QVERIFY(test_helpers::writeFile(dir.filePath("medium.bin"), 500)); + + const std::shared_ptr tree = test_helpers::scan(dir.path()); + QVERIFY(tree); + QCOMPARE(int(tree->children.size()), 3); + QCOMPARE(tree->children.at(0)->name, QStringLiteral("large.bin")); + QCOMPARE(tree->children.at(1)->name, QStringLiteral("medium.bin")); + QCOMPARE(tree->children.at(2)->name, QStringLiteral("small.bin")); +} + +void DiskScannerTest::skipsSymlinks() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + const QString target = dir.filePath("target.bin"); + QVERIFY(test_helpers::writeFile(target, 1000)); + if (!QFile::link(target, dir.filePath("link.bin"))) { + QSKIP("this filesystem does not support symbolic links"); + } + + const std::shared_ptr tree = test_helpers::scan(dir.path()); + QVERIFY(tree); + QCOMPARE(tree->totalSize, quint64(1000)); + QCOMPARE(tree->fileCount, quint64(1)); + QVERIFY(test_helpers::childNamed(*tree, "link.bin") == nullptr); +} + +void DiskScannerTest::reportsMissingDirectory() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + + ScanStats stats; + const std::shared_ptr tree = + test_helpers::scan(dir.filePath("does-not-exist"), &stats); + QVERIFY(tree); + QCOMPARE(tree->totalSize, quint64(0)); + QVERIFY(!stats.errors.isEmpty()); +} + +void DiskScannerTest::cancellationBeforeStartYieldsNoTree() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + QVERIFY(test_helpers::writeFile(dir.filePath("a.bin"), 10)); + + DiskScanner scanner(dir.path()); + scanner.cancel(); + scanner.start(); + QVERIFY(scanner.wait(5000)); + QVERIFY(!scanner.takeTree()); +} + +QTEST_GUILESS_MAIN(DiskScannerTest) +#include "disk-scanner.test.moc" diff --git a/tests/test-helpers.h b/tests/test-helpers.h new file mode 100644 index 0000000..9b4d573 --- /dev/null +++ b/tests/test-helpers.h @@ -0,0 +1,45 @@ +#pragma once + +#include "core/disk-node.h" +#include "core/disk-scanner.h" + +#include +#include +#include + +// Test helpers only: they keep the fixtures readable without hiding behaviour. +namespace test_helpers { + +inline bool writeFile(const QString &path, int bytes) +{ + QFile file(path); + if (!file.open(QIODevice::WriteOnly)) { + return false; + } + return file.write(QByteArray(bytes, 'x')) == bytes; +} + +inline DiskNode *childNamed(const DiskNode &node, const QString &name) +{ + for (const auto &child : node.children) { + if (child->name == name) { + return child.get(); + } + } + return nullptr; +} + +inline std::shared_ptr scan(const QString &path, ScanStats *stats = nullptr) +{ + DiskScanner scanner(path); + scanner.start(); + if (!scanner.wait(30000)) { + return nullptr; + } + if (stats) { + *stats = scanner.stats(); + } + return scanner.takeTree(); +} + +} // namespace test_helpers diff --git a/tests/treemap-layout.test.cpp b/tests/treemap-layout.test.cpp new file mode 100644 index 0000000..e1e759e --- /dev/null +++ b/tests/treemap-layout.test.cpp @@ -0,0 +1,84 @@ +#include "core/treemap-layout.h" + +#include +#include + +class TreemapLayoutTest : public QObject { + Q_OBJECT + +private slots: + void emptyInputYieldsNoTiles(); + void tilesStayInsideBounds(); + void tileAreasAreProportional(); + void zeroSizesGetNoTile(); + void singleItemFillsTheBounds(); +}; + +void TreemapLayoutTest::emptyInputYieldsNoTiles() +{ + QVERIFY(squarify({}, QRectF(0, 0, 400, 300)).isEmpty()); + QVERIFY(squarify({0, 0}, QRectF(0, 0, 400, 300)).isEmpty()); + QVERIFY(squarify({10, 20}, QRectF(0, 0, 0, 300)).isEmpty()); +} + +void TreemapLayoutTest::tilesStayInsideBounds() +{ + const QRectF bounds(10, 20, 800, 500); + const QVector sizes{50, 25, 15, 5, 3, 1, 1}; + const QVector tiles = squarify(sizes, bounds); + QCOMPARE(tiles.size(), sizes.size()); + + const QRectF allowed = bounds.adjusted(-0.01, -0.01, 0.01, 0.01); + for (const TreemapTile &tile : tiles) { + QVERIFY(allowed.contains(tile.rect)); + QVERIFY(tile.rect.width() > 0.0); + QVERIFY(tile.rect.height() > 0.0); + } + + for (int i = 0; i < tiles.size(); ++i) { + for (int j = i + 1; j < tiles.size(); ++j) { + const QRectF overlap = tiles.at(i).rect.intersected(tiles.at(j).rect); + QVERIFY(qFuzzyIsNull(overlap.width() * overlap.height())); + } + } +} + +void TreemapLayoutTest::tileAreasAreProportional() +{ + const QRectF bounds(0, 0, 800, 600); + const QVector sizes{50, 25, 15, 10}; + const QVector tiles = squarify(sizes, bounds); + QCOMPARE(tiles.size(), sizes.size()); + + const qreal total = 100.0; + for (const TreemapTile &tile : tiles) { + const qreal expected = bounds.width() * bounds.height() * sizes.at(tile.index) / total; + const qreal actual = tile.rect.width() * tile.rect.height(); + QVERIFY2(qAbs(actual - expected) / expected < 0.01, + qPrintable(QStringLiteral("tile %1: expected %2, got %3") + .arg(tile.index) + .arg(expected) + .arg(actual))); + } +} + +void TreemapLayoutTest::zeroSizesGetNoTile() +{ + const QVector tiles = squarify({10, 0, 30}, QRectF(0, 0, 200, 100)); + QCOMPARE(tiles.size(), 2); + for (const TreemapTile &tile : tiles) { + QVERIFY(tile.index != 1); + } +} + +void TreemapLayoutTest::singleItemFillsTheBounds() +{ + const QRectF bounds(0, 0, 320, 200); + const QVector tiles = squarify({42}, bounds); + QCOMPARE(tiles.size(), 1); + QVERIFY(qAbs(tiles.at(0).rect.width() - bounds.width()) < 1e-6); + QVERIFY(qAbs(tiles.at(0).rect.height() - bounds.height()) < 1e-6); +} + +QTEST_GUILESS_MAIN(TreemapLayoutTest) +#include "treemap-layout.test.moc"