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.
This commit is contained in:
1 parent
08befc1bf5
commit
977b1c35a9
15 files changed
+1461
No files matched your search
@@ -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()
|
||||
@@ -0,0 +1,31 @@
|
||||
# Maintainer: FWS <dami.scoot3@gmail.com>
|
||||
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"
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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;
|
||||
@@ -0,0 +1,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
|
||||
<rect width="128" height="128" rx="24" fill="#1c1e23"/>
|
||||
<rect x="14" y="14" width="64" height="62" rx="4" fill="#3d7ea6"/>
|
||||
<rect x="82" y="14" width="32" height="36" rx="4" fill="#e0a458"/>
|
||||
<rect x="82" y="54" width="32" height="22" rx="4" fill="#8ec07c"/>
|
||||
<rect x="14" y="80" width="40" height="34" rx="4" fill="#b16286"/>
|
||||
<rect x="58" y="80" width="30" height="34" rx="4" fill="#d5c4a1"/>
|
||||
<rect x="92" y="80" width="22" height="16" rx="4" fill="#7c6f64"/>
|
||||
<rect x="92" y="100" width="22" height="14" rx="4" fill="#458588"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 637 B |
@@ -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" "$@"
|
||||
@@ -0,0 +1,23 @@
|
||||
#include "ui/main-window.h"
|
||||
|
||||
#include <QApplication>
|
||||
#include <QIcon>
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -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 <QAction>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileDialog>
|
||||
#include <QFileInfo>
|
||||
#include <QFont>
|
||||
#include <QHBoxLayout>
|
||||
#include <QIcon>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QLocale>
|
||||
#include <QMenu>
|
||||
#include <QMessageBox>
|
||||
#include <QProgressBar>
|
||||
#include <QPushButton>
|
||||
#include <QSplitter>
|
||||
#include <QStatusBar>
|
||||
#include <QToolButton>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
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<DiskNode> 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<double>(node->totalSize) / static_cast<double>(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<DiskNode> 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)));
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include <QMainWindow>
|
||||
#include <QPoint>
|
||||
#include <QString>
|
||||
|
||||
#include <memory>
|
||||
|
||||
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<DiskNode> 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;
|
||||
};
|
||||
@@ -0,0 +1,362 @@
|
||||
#include "ui/treemap-widget.h"
|
||||
|
||||
#include "core/format.h"
|
||||
#include "core/treemap-layout.h"
|
||||
|
||||
#include <QContextMenuEvent>
|
||||
#include <QFontMetricsF>
|
||||
#include <QHash>
|
||||
#include <QMouseEvent>
|
||||
#include <QPainter>
|
||||
#include <QResizeEvent>
|
||||
#include <QToolTip>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
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<QString, FileFamily> 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<quint32>(qHash(node.name));
|
||||
// A wider jitter than the family width keeps neighbours from looking flat.
|
||||
const int jitter = static_cast<int>(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<int>(hash % 46) + jitter + 360) % 360, 198,
|
||||
172 + static_cast<int>(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<int>(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<DiskNode> 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<qreal> sizes;
|
||||
QVector<DiskNode *> nodes;
|
||||
sizes.reserve(static_cast<int>(m_current->children.size()));
|
||||
nodes.reserve(static_cast<int>(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<qreal>(child->totalSize));
|
||||
nodes.append(child.get());
|
||||
}
|
||||
|
||||
const QVector<TreemapTile> 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);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/disk-node.h"
|
||||
|
||||
#include <QRectF>
|
||||
#include <QVector>
|
||||
#include <QWidget>
|
||||
|
||||
#include <memory>
|
||||
|
||||
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<DiskNode> 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<DiskNode> m_tree;
|
||||
DiskNode *m_current = nullptr;
|
||||
DiskNode *m_selected = nullptr;
|
||||
DiskNode *m_hovered = nullptr;
|
||||
QVector<Tile> m_tiles;
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
#include "test-helpers.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QTemporaryDir>
|
||||
#include <QtTest>
|
||||
|
||||
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<DiskNode> 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<DiskNode> 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<DiskNode> tree = test_helpers::scan(dir.path());
|
||||
QVERIFY(tree);
|
||||
|
||||
std::unique_ptr<DiskNode> 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"
|
||||
@@ -0,0 +1,114 @@
|
||||
#include "test-helpers.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QTemporaryDir>
|
||||
#include <QtTest>
|
||||
|
||||
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<DiskNode> 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<DiskNode> 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<DiskNode> 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<DiskNode> 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"
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/disk-node.h"
|
||||
#include "core/disk-scanner.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <memory>
|
||||
|
||||
// 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<DiskNode> 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
|
||||
@@ -0,0 +1,84 @@
|
||||
#include "core/treemap-layout.h"
|
||||
|
||||
#include <QRectF>
|
||||
#include <QtTest>
|
||||
|
||||
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<qreal> sizes{50, 25, 15, 5, 3, 1, 1};
|
||||
const QVector<TreemapTile> 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<qreal> sizes{50, 25, 15, 10};
|
||||
const QVector<TreemapTile> 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<TreemapTile> 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<TreemapTile> 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"
|
||||
Reference in new issue
Block a user