-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1634 lines (1454 loc) · 59.8 KB
/
Copy pathmainwindow.cpp
File metadata and controls
1634 lines (1454 loc) · 59.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* mainwindow.cpp
**********************************************************************
* Copyright (C) 2018-2025 MX Authors
*
* Authors: Adrian
* MX Linux <http://mxlinux.org>
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDialogButtonBox>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QFileInfo>
#include <QLocale>
#include <QProcess>
#include <QProgressDialog>
#include <QRegularExpression>
#include <QSignalBlocker>
#include <QStandardPaths>
#include <QTemporaryFile>
#include <QTextEdit>
#include <QTimer>
#include <csignal>
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include "about.h"
#include "packagemanager.h"
extern const QString starting_home;
namespace {
// Settings keys shared between loadSettings and saveSettings
inline const QString keyThumbnails = QStringLiteral("Folders/Thumbnails");
inline const QString keyCache = QStringLiteral("Folders/Cache");
inline const QString keyCacheOlderThan = QStringLiteral("Folders/CacheOlderThan");
inline const QString keyCacheSafer = QStringLiteral("Folders/CacheSafer");
inline const QString keyAptCleanup = QStringLiteral("Apt/AptCleanup");
inline const QString keyAptSelection = QStringLiteral("Apt/AptSelection");
inline const QString keyAptPurge = QStringLiteral("Apt/AptPurge");
inline const QString keyLogsCleanup = QStringLiteral("Logs/LogsCleanup");
inline const QString keyLogsSelection = QStringLiteral("Logs/LogsSelection");
inline const QString keyLogsOlderThan = QStringLiteral("Logs/LogsOlderThan");
inline const QString keyTrashCleanup = QStringLiteral("Trash/TrashCleanup");
inline const QString keyTrashSelection = QStringLiteral("Trash/TrashSelection");
inline const QString keyTrashOlderThan = QStringLiteral("Trash/TrashOlderThan");
inline const QString keyFlatpakCleanup = QStringLiteral("Flatpak/FlatpakCleanup");
inline const QString keyFlatpakUnused = QStringLiteral("Flatpak/UninstallUnusedRuntimes");
// Run the child in its own process group so a timeout can kill the whole
// tree (e.g. pkexec -> helper -> apt-get), not just the immediate child.
void makeNewProcessGroup(QProcess &proc)
{
proc.setChildProcessModifier([] { ::setpgid(0, 0); });
}
void killProcessGroup(QProcess &proc)
{
const qint64 pid = proc.processId();
if (pid > 0) {
::killpg(static_cast<pid_t>(pid), SIGKILL);
}
proc.kill();
proc.waitForFinished();
}
}
MainWindow::MainWindow(QWidget *parent)
: QDialog(parent),
ui(new Ui::MainWindow)
{
qDebug().noquote() << QApplication::applicationName() << "version:" << QApplication::applicationVersion();
ui->setupUi(this);
setConnections();
setWindowFlags(Qt::Window); // For the close, min and max buttons
setup();
}
MainWindow::~MainWindow()
{
if (!shadowSettingsPath.isEmpty()) {
QFile::remove(shadowSettingsPath);
}
delete ui;
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if (manualRemovalInProgress) {
event->ignore();
return;
}
QDialog::closeEvent(event);
}
void MainWindow::removeManuals()
{
QSettings defaultlocale("/etc/default/locale", QSettings::NativeFormat);
QString lang = defaultlocale.value("LANG", "C").toString().section('.', 0, 0);
// Fix for pt_BR, others use base language
if (lang == "pt_BR") {
lang = "pt-br";
} else {
lang = lang.section("_", 0, 0);
}
if (lang.isEmpty()) {
return;
}
QString exclusionPattern = QString("(mx|mxfb)-(docs|faq)-(en|common%1)")
.arg(lang == "en" || lang == "C" ? "" : QString("|%1").arg(lang));
QString listCmd = QString("dpkg-query -W -f='${Package}\n' -- 'mx-docs-*' 'mxfb-docs-*' 'mx-faq-*' 'mxfb-faq-*' "
"2>/dev/null | grep -vE '%1'")
.arg(exclusionPattern);
QStringList packageList = cmdOut(listCmd).split('\n', Qt::SkipEmptyParts);
if (packageList.isEmpty()) {
QMessageBox::information(this, tr("Remove Manuals"), tr("No manuals to remove."));
return;
}
if (getuid() != 0
&& !helperProc({"check"}, QuietMode::Yes, nullptr, {}, nullptr, nullptr, kDiskScanTimeoutMs)) {
QMessageBox::critical(this, tr("Error"), tr("Failed to elevate privileges"));
return;
}
manualRemovalInProgress = true;
ui->pushCancel->setDisabled(true);
ui->tabWidget->setDisabled(true);
QProgressDialog prog(tr("Removing packages, please wait"), QString(), 0, packageList.size(), this);
prog.setMinimumDuration(0);
prog.setValue(0);
prog.show();
QApplication::processEvents();
for (int index = 0; index < packageList.size(); ++index) {
prog.setLabelText(tr("Removing packages, please wait"));
helperProc({"purge-packages", packageList.at(index)}, QuietMode::Yes, nullptr, {}, nullptr, nullptr,
kNoTimeoutMs);
prog.setValue(index + 1);
QApplication::processEvents();
}
ui->tabWidget->setEnabled(true);
ui->pushCancel->setEnabled(true);
manualRemovalInProgress = false;
}
void MainWindow::addGroupCheckbox(QLayout *layout, const QStringList &packages, const QString &name, QStringList *list)
{
if (packages.isEmpty()) {
return;
}
auto *grpBox = new QGroupBox(name);
grpBox->setFlat(true);
auto *vBox = new QVBoxLayout(grpBox);
layout->addWidget(grpBox);
for (const auto &item : packages) {
auto *btn = new QCheckBox(item);
vBox->addWidget(btn);
connect(btn, &QCheckBox::toggled, [btn, list]() {
if (btn->isChecked()) {
list->append(btn->text());
} else {
list->removeAll(btn->text());
}
});
}
vBox->addStretch(1);
}
// Setup various items for the first run of the program
void MainWindow::setup()
{
setWindowTitle(tr("MX Cleanup"));
ui->tabWidget->setCurrentIndex(0);
adjustSize();
// Hide disk usage analyzer group box if none of the tools are available
const QStringList diskUsageTools = {"baobab", "qdirstat", "filelight"};
bool hasAnyTool = false;
for (const auto &tool : diskUsageTools) {
if (!QStandardPaths::findExecutable(tool).isEmpty()) {
hasAnyTool = true;
break;
}
}
if (!hasAnyTool) {
ui->groupBoxUsage->hide();
}
isArchLinux = isArchLinuxHost();
if (isArchLinux) {
ui->groupBoxKernel->hide();
ui->groupBoxApt->setTitle(tr("Clean pacman cache"));
}
suppressUserSwitch = true;
currentUser = cmdOut("logname", QuietMode::Yes);
ui->pushApply->setDisabled(true);
ui->checkCache->setChecked(true);
ui->checkThumbs->setChecked(true);
ui->radioAutoClean->setChecked(true);
ui->radioOldLogs->setChecked(true);
ui->radioSelectedUser->setChecked(true);
QStringList users = cmdOut("lslogins --noheadings -u -o user", QuietMode::Yes)
.split('\n', Qt::SkipEmptyParts);
users.removeAll(QStringLiteral("root"));
// Some lslogins versions/environments can emit unexpected output (e.g. a
// header row) despite --noheadings; drop anything that isn't a real user
// so it can't end up selected and passed to the helper as --user.
users.removeIf([](const QString &user) { return getpwnam(user.toUtf8().constData()) == nullptr; });
{
QSignalBlocker blocker(ui->comboUserClean);
ui->comboUserClean->addItems(users);
int targetIndex = ui->comboUserClean->findText(currentUser);
if (targetIndex == -1 && ui->comboUserClean->count() > 0) {
targetIndex = 0;
}
if (targetIndex != -1) {
ui->comboUserClean->setCurrentIndex(targetIndex);
}
}
initializeSettingsForUser(ui->comboUserClean->currentText());
loadSettings();
ui->pushApply->setEnabled(!ui->comboUserClean->currentText().isEmpty());
loadSchedule(true);
suppressUserSwitch = false;
}
QString MainWindow::homeDirForUser(const QString &user) const
{
if (user.isEmpty()) {
return QString();
}
struct passwd *pwd = getpwnam(user.toUtf8().constData());
if (!pwd) {
return QString();
}
return QString::fromUtf8(pwd->pw_dir);
}
QString MainWindow::currentUserSuffix() const
{
const QString user = ui->comboUserClean->currentText();
return user.isEmpty() ? QString() : '.' + user;
}
QString MainWindow::settingsDirForUser(const QString &user) const
{
const QString homeDir = homeDirForUser(user);
if (homeDir.isEmpty()) {
return QString();
}
QString orgName = QApplication::organizationName();
if (orgName.isEmpty()) {
orgName = QStringLiteral("MX-Linux");
}
return homeDir + "/.config/" + orgName;
}
QString MainWindow::settingsFileForUser(const QString &user) const
{
const QString dir = settingsDirForUser(user);
if (dir.isEmpty()) {
return QString();
}
QString appName = QApplication::applicationName();
if (appName.isEmpty()) {
appName = QStringLiteral("mx-cleanup");
}
return dir + '/' + appName + ".conf";
}
void MainWindow::initializeSettingsForUser(const QString &user)
{
if (!shadowSettingsPath.isEmpty()) {
QFile::remove(shadowSettingsPath);
shadowSettingsPath.clear();
}
currentSettingsPath.clear();
settings.reset();
if (user.isEmpty()) {
settings = std::make_unique<QSettings>();
return;
}
const QString filePath = settingsFileForUser(user);
if (filePath.isEmpty()) {
settings = std::make_unique<QSettings>();
return;
}
const bool needsRoot = (getuid() != 0 && user != currentUser);
if (needsRoot) {
QTemporaryFile tempFile(QDir::tempPath() + "/mx-cleanup-shadowXXXXXX.conf");
tempFile.setAutoRemove(false);
if (tempFile.open()) {
shadowSettingsPath = tempFile.fileName();
QString content;
helperProc({"read-settings", user}, QuietMode::Yes, &content);
if (!content.isEmpty()) {
tempFile.write(content.toUtf8() + '\n');
}
tempFile.close();
settings = std::make_unique<QSettings>(shadowSettingsPath, QSettings::IniFormat);
settings->setFallbacksEnabled(false);
currentSettingsPath = filePath;
return;
}
qWarning().noquote() << "Failed to create temporary file for settings shadow";
settings = std::make_unique<QSettings>();
currentSettingsPath = filePath;
return;
}
settings = std::make_unique<QSettings>(filePath, QSettings::IniFormat);
settings->setFallbacksEnabled(false);
currentSettingsPath = filePath;
}
void MainWindow::ensureSettingsOwnership(const QString &user)
{
if (user.isEmpty()) {
return;
}
helperProc({"chown-settings", user}, QuietMode::Yes);
}
QString MainWindow::cronEntryBase(const QString &period) const
{
if (period == "@reboot") {
return "/etc/cron.d/mx-cleanup";
}
return "/etc/cron." + period + "/mx-cleanup";
}
QString MainWindow::cronEntryPath(const QString &period, bool forWrite) const
{
const QString base = cronEntryBase(period);
const QString suffix = currentUserSuffix();
if (suffix.isEmpty()) {
return base;
}
const QString candidate = base + suffix;
if (forWrite) {
return candidate;
}
if (QFile::exists(candidate)) {
return candidate;
}
const bool selectedIsCurrent = (ui->comboUserClean->currentText() == currentUser);
return selectedIsCurrent ? base : candidate;
}
QString MainWindow::scriptFileBase() const
{
return "/usr/bin/mx-cleanup-script";
}
QString MainWindow::scriptFilePath(bool forWrite) const
{
const QString base = scriptFileBase();
const QString suffix = currentUserSuffix();
if (suffix.isEmpty()) {
return base;
}
const QString candidate = base + suffix;
if (forWrite) {
return candidate;
}
if (QFile::exists(candidate)) {
return candidate;
}
const bool selectedIsCurrent = (ui->comboUserClean->currentText() == currentUser);
return selectedIsCurrent ? base : candidate;
}
QString MainWindow::systemScriptPath() const
{
return "/usr/bin/mx-cleanup-system-script";
}
// Check if the cleanup script exists in the cron directories.
void MainWindow::loadSchedule(bool settingsPreloaded)
{
auto periodActive = [this](const QString &period) {
const QString userPath = (period == "@reboot") ? scriptFilePath(false) : cronEntryPath(period, false);
return QFile::exists(userPath);
};
if (periodActive("daily")) {
ui->radioDaily->setChecked(true);
} else if (periodActive("weekly")) {
ui->radioWeekly->setChecked(true);
} else if (periodActive("monthly")) {
ui->radioMonthly->setChecked(true);
} else if (periodActive("@reboot")) {
ui->radioReboot->setChecked(true);
} else {
ui->radioNone->setChecked(true);
}
loadOptions(settingsPreloaded);
}
bool MainWindow::loadSystemScriptOptions(const QString &legacyFallbackContent)
{
QString content;
if (QFile::exists(systemScriptPath())) {
QFile file(systemScriptPath());
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
content = QString::fromUtf8(file.readAll());
}
} else {
// Upgrade path: no shared script yet, so any apt/purge/logs/trash-all
// commands still live inline in the pre-split user script. Parse them
// from there so they display checked and the next Apply migrates them
// into the shared script instead of silently dropping them.
content = legacyFallbackContent;
}
if (content.contains("apt-get autoclean")) {
ui->groupBoxApt->setChecked(true);
ui->radioAutoClean->setChecked(true);
} else if (content.contains("apt-get clean")) {
ui->groupBoxApt->setChecked(true);
ui->radioClean->setChecked(true);
} else {
ui->groupBoxApt->setChecked(false);
}
ui->checkPurge->setChecked(content.contains("apt-get purge"));
if (QRegularExpression(R"(\-exec truncate \-s 0)").match(content).hasMatch()) {
ui->groupBoxLogs->setChecked(true);
ui->radioAllLogs->setChecked(true);
} else if (QRegularExpression(R"(\-type f \-delete)").match(content).hasMatch()) {
ui->groupBoxLogs->setChecked(true);
ui->radioOldLogs->setChecked(true);
} else {
ui->groupBoxLogs->setChecked(false);
}
QRegularExpression logCtimeRe(R"(find /var/log.*-ctime \+([0-9]{1,3}))");
QRegularExpressionMatch logMatch = logCtimeRe.match(content);
ui->spinBoxLogs->setValue(logMatch.hasMatch() ? logMatch.captured(1).toInt() : 0);
const bool trashAllActive = content.contains("/home/*/.local/share/Trash");
if (trashAllActive) {
ui->groupBoxTrash->setChecked(true);
ui->radioAllUsers->setChecked(true);
QRegularExpression trashCtimeRe(R"(find /home/.*-ctime \+([0-9]{1,3}))");
QRegularExpressionMatch trashMatch = trashCtimeRe.match(content);
ui->spinBoxTrash->setValue(trashMatch.hasMatch() ? trashMatch.captured(1).toInt() : 0);
}
return trashAllActive;
}
void MainWindow::loadSettings()
{
auto value = [this](const QString &key, const QVariant &fallback) -> QVariant {
return settings ? settings->value(key, fallback) : fallback;
};
ui->checkThumbs->setChecked(value(keyThumbnails, true).toBool());
ui->checkCache->setChecked(value(keyCache, true).toBool());
ui->spinCache->setValue(value(keyCacheOlderThan, 2).toInt());
const bool cacheSafer = value(keyCacheSafer, true).toBool();
ui->radioSaferCache->setChecked(cacheSafer);
ui->radioAllCache->setChecked(!cacheSafer);
ui->checkFlatpak->setChecked(value(keyFlatpakUnused, false).toBool());
// apt/purge/logs/trash-all are shared, system-wide settings now (see
// pushApply_clicked()/helper.cpp) -- always read from the real shared
// script, never from this user's own saved preference. Otherwise a user
// with no schedule of their own could apply and silently overwrite the
// real shared script with their own stale/default preference.
const bool trashAllActive = loadSystemScriptOptions();
if (!trashAllActive) {
const bool trashCleanup = value(keyTrashCleanup, true).toBool();
ui->groupBoxTrash->setChecked(trashCleanup);
ui->spinBoxTrash->setValue(value(keyTrashOlderThan, 30).toInt());
if (trashCleanup) {
ui->radioSelectedUser->setChecked(true);
}
}
}
void MainWindow::removeKernelPackages(const QStringList &list)
{
if (list.isEmpty()) {
return;
}
setCursor(QCursor(Qt::BusyCursor));
QStringList headers;
headers.reserve(list.size());
QStringList headers_installed;
for (const auto &item : list) {
const QString version
= item.section(QRegularExpression("linux-image-"), 1).remove(QRegularExpression("-unsigned$"));
if (!version.isEmpty()) {
headers << "linux-headers-" + version;
}
}
for (const auto &item : std::as_const(headers)) {
QProcess proc;
proc.start("dpkg", {"-s", item});
proc.waitForFinished();
if (proc.exitCode() == 0 && proc.readAllStandardOutput().contains("Status: install ok installed")) {
headers_installed << item;
}
}
QStringList headers_depends;
QString headers_common;
QString image_pattern;
for (const auto &item : std::as_const(headers_installed)) {
{
QProcess proc;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("LC_ALL", "C.UTF-8");
proc.setProcessEnvironment(env);
proc.start("apt-cache", {"depends", item});
proc.waitForFinished();
QRegularExpression reDepends("Depends:\\s+(linux-headers-\\d\\S+)");
auto matches = reDepends.globalMatch(QString::fromUtf8(proc.readAllStandardOutput()));
QStringList found;
while (matches.hasNext()) {
found << matches.next().captured(1);
}
found.removeDuplicates();
found.sort();
headers_common = found.join('\n');
}
if (!headers_common.toUtf8().trimmed().isEmpty()) {
image_pattern = headers_common;
image_pattern.remove("-common");
image_pattern.replace("headers", "image");
QStringList escapedPkgs;
escapedPkgs.reserve(list.size());
for (const auto &pkg : list)
escapedPkgs << QRegularExpression::escape(pkg);
// Package/pattern data is passed as bash positional parameters
// ($1, $2) rather than interpolated into the script text, so
// none of it is ever parsed as shell syntax.
bool patternStillInstalled = false;
cmdOut("/bin/bash",
{"-c",
"dpkg -l 'linux-image-[0-9]*' | grep ^ii | cut -d ' ' -f3 | grep -v -E \"$1\" | grep -q -- \"$2\"",
"bash", escapedPkgs.join('|'), image_pattern},
QuietMode::No, &patternStillInstalled);
if (!patternStillInstalled) {
headers_depends << headers_common;
}
}
}
static const QRegularExpression pkgNameRe(R"(^[a-zA-Z0-9][a-zA-Z0-9.+-]*$)");
QString common;
if (!headers_depends.isEmpty()) {
QStringList escapedDepends;
escapedDepends.reserve(headers_depends.size());
for (const auto &dep : headers_depends)
escapedDepends << QRegularExpression::escape(dep);
// As above: the grep pattern and package list are passed as bash
// positional parameters, not interpolated into the script text.
QStringList commonArgs {
"-c", R"(pattern="$1"; shift; apt-get remove -s "$@" | grep '^ ' | grep -oE "$pattern" | tr '\n' ' ')",
"bash", escapedDepends.join('|')};
commonArgs += headers_installed;
common = cmdOut("/bin/bash", commonArgs);
}
QString helper {"/usr/lib/" + QApplication::applicationName() + "/helper-terminal-keep-open"};
QStringList packages;
for (const auto &pkg : headers_installed) {
if (pkgNameRe.match(pkg).hasMatch())
packages << pkg;
}
for (const auto &pkg : list) {
if (pkgNameRe.match(pkg).hasMatch())
packages << pkg;
}
if (!common.isEmpty()) {
for (const auto &pkg : common.split(' ', Qt::SkipEmptyParts)) {
if (pkgNameRe.match(pkg).hasMatch())
packages << pkg;
}
}
QStringList terminalArgs {"-e", "pkexec", helper, "purge-packages"};
terminalArgs += packages;
QProcess terminalProc;
terminalProc.start("x-terminal-emulator", terminalArgs);
terminalProc.waitForFinished(1800000); // 30-minute timeout for terminal to close
if (terminalProc.state() == QProcess::Running) {
terminalProc.kill();
terminalProc.waitForFinished();
}
setCursor(QCursor(Qt::ArrowCursor));
}
// Load saved options to GUI
void MainWindow::loadOptions(bool settingsPreloaded)
{
QString period;
if (ui->radioDaily->isChecked()) {
period = "daily";
} else if (ui->radioWeekly->isChecked()) {
period = "weekly";
} else if (ui->radioMonthly->isChecked()) {
period = "monthly";
} else if (ui->radioReboot->isChecked()) {
period = "@reboot";
} else {
loadSettings();
return;
}
const QString userFileName = (period == "@reboot") ? scriptFilePath(false) : cronEntryPath(period, false);
QString userContent;
if (QFile::exists(userFileName)) {
QFile file(userFileName);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
userContent = QString::fromUtf8(file.readAll());
}
}
// Cache/thumbs/trash-user/flatpak live in the selected user's own schedule
// file; apt/purge/logs/trash-all live in the separate shared system-wide
// script that file calls (see pushApply_clicked()/helper.cpp). The shared
// script is read unconditionally, regardless of whether this user has a
// schedule of their own at this (or any) period -- never falling back to
// this user's own saved preference, which could then overwrite the real
// shared script the next time they apply. The user script content is
// passed along for the pre-split upgrade path, where the global commands
// still live inline in it.
const bool trashAllActive = loadSystemScriptOptions(userContent);
if (userContent.isEmpty()) {
if (!settingsPreloaded) {
loadSettings();
}
return;
}
// Folders
bool hasThumbs = QRegularExpression(R"(find /home/[^/]+/\.cache/thumbnails)").match(userContent).hasMatch();
ui->checkThumbs->setChecked(hasThumbs);
bool hasCache = QRegularExpression(R"(find /home/[^/]+/\.cache(\s|/\*))").match(userContent).hasMatch();
ui->checkCache->setChecked(hasCache);
if (hasCache || hasThumbs) {
QRegularExpression atimeRe(R"(\.cache.*-atime \+([0-9]+))");
QRegularExpressionMatch match = atimeRe.match(userContent);
if (match.hasMatch()) {
ui->radioSaferCache->setChecked(true);
ui->radioAllCache->setChecked(false);
ui->spinCache->setValue(match.captured(1).toInt());
} else {
ui->radioSaferCache->setChecked(false);
ui->radioAllCache->setChecked(true);
}
}
// Flatpak: remove unused runtimes
ui->checkFlatpak->setChecked(userContent.contains("flatpak uninstall --unused"));
// Trash: "all users" (from the shared system script, via
// loadSystemScriptOptions() above) always takes priority for display --
// "selected user" is read here only when the shared script isn't already
// scheduling "all users".
if (!trashAllActive) {
if (userContent.contains("/.local/share/Trash")) {
ui->groupBoxTrash->setChecked(true);
ui->radioSelectedUser->setChecked(true);
QRegularExpression trashCtimeRe(R"(find /home/.*-ctime \+([0-9]{1,3}))");
QRegularExpressionMatch trashMatch = trashCtimeRe.match(userContent);
ui->spinBoxTrash->setValue(trashMatch.hasMatch() ? trashMatch.captured(1).toInt() : 0);
} else {
ui->groupBoxTrash->setChecked(false);
}
}
}
// Save cleanup commands to a /etc/cron.daily|weekly|monthly/mx-cleanup script.
// The helper composes and writes the script itself from the validated options.
bool MainWindow::saveSchedule(const QStringList &scheduleOpts, const QString &period)
{
QStringList args {"write-schedule", period};
const QString user = ui->comboUserClean->currentText();
if (!user.isEmpty()) {
args << "--user" << user;
}
args += scheduleOpts;
return helperProc(args, QuietMode::Yes);
}
bool MainWindow::saveSettings()
{
if (!settings) {
return true;
}
const QString user = ui->comboUserClean->currentText();
if (user.isEmpty()) {
return true;
}
const QString dirPath = settingsDirForUser(user);
const QString targetPath = settingsFileForUser(user);
if (dirPath.isEmpty() || targetPath.isEmpty()) {
qWarning().noquote() << "Missing settings path for user" << user;
return false;
}
const bool needsRoot = (getuid() != 0 && user != currentUser);
auto writeValues = [this](QSettings &store) {
store.setValue(keyThumbnails, ui->checkThumbs->isChecked());
store.setValue(keyCache, ui->checkCache->isChecked());
store.setValue(keyCacheOlderThan, ui->spinCache->value());
store.setValue(keyCacheSafer, ui->radioSaferCache->isChecked());
const bool aptCleanup = ui->groupBoxApt->isChecked();
store.setValue(keyAptCleanup, aptCleanup);
store.setValue(keyAptSelection, aptCleanup ? ui->buttonGroupApt->checkedId() : -1);
store.setValue(keyAptPurge, ui->checkPurge->isChecked());
const bool logsCleanup = ui->groupBoxLogs->isChecked();
store.setValue(keyLogsSelection, logsCleanup ? ui->buttonGroupLogs->checkedId() : -1);
store.setValue(keyLogsOlderThan, ui->spinBoxLogs->value());
store.setValue(keyLogsCleanup, logsCleanup);
const bool trashCleanup = ui->groupBoxTrash->isChecked();
store.setValue(keyTrashCleanup, trashCleanup);
store.setValue(keyTrashSelection, trashCleanup ? ui->buttonGroupTrash->checkedId() : -1);
store.setValue(keyTrashOlderThan, ui->spinBoxTrash->value());
store.setValue(keyFlatpakCleanup, ui->groupBoxFlatpak->isChecked());
store.setValue(keyFlatpakUnused, ui->checkFlatpak->isChecked());
};
auto writeWithHelper = [&]() {
QTemporaryFile tempFile;
if (!tempFile.open()) {
qWarning().noquote() << "Failed to open temporary settings file for user" << user;
return false;
}
QSettings tempSettings(tempFile.fileName(), QSettings::IniFormat);
tempSettings.setFallbacksEnabled(false);
writeValues(tempSettings);
tempSettings.sync();
if (tempSettings.status() != QSettings::NoError) {
qWarning().noquote() << "Failed to write temporary settings file for user" << user;
return false;
}
QFile contentFile(tempFile.fileName());
if (!contentFile.open(QIODevice::ReadOnly)) {
qWarning().noquote() << "Failed to read temporary settings file for user" << user;
return false;
}
const QByteArray content = contentFile.readAll();
contentFile.close();
if (!helperProc({"write-settings", user}, QuietMode::Yes, nullptr, content)) {
return false;
}
currentSettingsPath = targetPath;
initializeSettingsForUser(user);
return true;
};
if (needsRoot) {
return writeWithHelper();
}
QDir dir;
if (!dir.exists(dirPath)) {
qDebug().noquote() << "Creating settings directory:" << dirPath;
if (!dir.mkpath(dirPath)) {
qWarning().noquote() << "Failed to create settings directory:" << dirPath;
if (getuid() != 0) {
return writeWithHelper();
}
return false;
}
}
qDebug().noquote() << "Save settings to" << targetPath;
writeValues(*settings);
settings->sync();
qDebug().noquote() << "Settings sync status:" << settings->status();
auto rewriteFresh = [&]() {
settings = std::make_unique<QSettings>(targetPath, QSettings::IniFormat);
settings->setFallbacksEnabled(false);
writeValues(*settings);
settings->sync();
qDebug().noquote() << "Settings retry sync status:" << settings->status();
};
if (settings->status() == QSettings::FormatError) {
// QSettings cannot cleanly rewrite a file it failed to parse, so a
// corrupt file blocks every future save. Move it aside and start over.
const QString backupPath = targetPath + ".bak";
QFile::remove(backupPath);
if (QFile::rename(targetPath, backupPath)) {
qWarning().noquote() << "Corrupt settings file moved to" << backupPath;
rewriteFresh();
} else if (getuid() != 0) {
// Corrupt file in a directory we cannot write to (e.g. left owned
// by root): let the helper replace it.
return writeWithHelper();
}
} else if (settings->status() == QSettings::AccessError && getuid() != 0) {
// A past run as root can leave the file or directory owned by root.
// Privileges are already cached at this point in the apply flow, so
// use the helper to replace the file atomically with correct ownership.
return writeWithHelper();
}
if (getuid() == 0 && user != currentUser) {
ensureSettingsOwnership(user);
}
currentSettingsPath = targetPath;
return settings->status() == QSettings::NoError;
}
void MainWindow::selectRadioButton(QGroupBox *groupbox, const QButtonGroup *group, int id)
{
if (id != -1) {
if (groupbox) {
groupbox->setChecked(true);
}
auto *selectedButton = group->button(id);
if (selectedButton) {
selectedButton->setChecked(true);
}
}
}
void MainWindow::setConnections()
{
connect(ui->pushAbout, &QPushButton::clicked, this, &MainWindow::pushAbout_clicked);
connect(ui->pushApply, &QPushButton::clicked, this, &MainWindow::pushApply_clicked);
connect(ui->pushCancel, &QPushButton::clicked, this, &MainWindow::close);
connect(ui->pushHelp, &QPushButton::clicked, this, &MainWindow::pushHelp_clicked);
connect(ui->pushKernel, &QPushButton::clicked, this, &MainWindow::pushKernel_clicked);
connect(ui->pushRemoveManuals, &QPushButton::clicked, this, &MainWindow::removeManuals);
connect(ui->pushRTLremove, &QPushButton::clicked, this, &MainWindow::pushRTLremove_clicked);
connect(ui->pushUsageAnalyzer, &QPushButton::clicked, this, &MainWindow::pushUsageAnalyzer_clicked);
connect(ui->tabWidget, &QTabWidget::currentChanged, this,
[this](int index) { ui->pushApply->setDisabled(index == 1); });
connect(ui->comboUserClean, &QComboBox::currentTextChanged, this, [this](const QString &text) {
if (suppressUserSwitch) {
return;
}
ui->pushApply->setEnabled(!text.isEmpty());
initializeSettingsForUser(text);
loadSettings();
loadSchedule(true);
});
for (auto *spinBox : {ui->spinCache, ui->spinBoxLogs, ui->spinBoxTrash}) {
connect(spinBox, QOverload<int>::of(&QSpinBox::valueChanged), this,
[spinBox]() { spinBox->setSuffix(spinBox->value() > 1 ? tr(" days") : tr(" day")); });
}
}
void MainWindow::pushApply_clicked()
{
QApplication::setOverrideCursor(Qt::BusyCursor);
QApplication::processEvents();
setEnabled(false);
// Try to elevate privileges if needed
if (getuid() != 0) {
if (!helperProc({"check"}, QuietMode::Yes, nullptr, {}, nullptr, nullptr, kDiskScanTimeoutMs)) {
QMessageBox::critical(this, tr("Error"), tr("Failed to elevate privileges"));
QApplication::restoreOverrideCursor();
setEnabled(true);
return;
}
}
quint64 total {};
QStringList scheduleOpts;
const QString selectedUser = ui->comboUserClean->currentText();
const bool elevate = (selectedUser != currentUser);
auto addToTotal = [&](const QString &label, quint64 amount) {
if (amount == 0) {
return;
}
total += amount;
qDebug().noquote() << "Freed" << label << amount << "KiB";
};
QStringList failures;
auto runOp = [&](const QString &label, const QStringList &args, int timeoutMs = kDiskScanTimeoutMs) -> bool {
QString errorOutput;
if (helperProc(args, QuietMode::Yes, nullptr, {}, &errorOutput, nullptr, timeoutMs)) {
return true;
}
failures << (errorOutput.isEmpty() ? label : label + ": " + errorOutput);
return false;
};
if (ui->checkCache->isChecked()) {
const int cacheDays = ui->radioSaferCache->isChecked() ? ui->spinCache->value() : 0;
const QString cacheDaysArg = QString::number(cacheDays);
const QString cachePath = QString("/home/%1/.cache").arg(selectedUser);
QString period = cacheDays > 0 ? QString(" -atime +%1 -mtime +%1").arg(cacheDays) : QString();
QString findCmd = QString("find /home/%1/.cache -mindepth 1 ! -path '/home/%1/.cache/thumbnails*'%2 -type f "
"-exec du -c '{}' + | awk 'END{print $1}'")
.arg(selectedUser, period);
quint64 cacheKiB {};
if (elevate) {
cacheKiB = sumKiB(
helperOut({"clean-cache", "size", selectedUser, cacheDaysArg}, QuietMode::Yes, kDiskScanTimeoutMs));
} else {
cacheKiB = cmdOut(findCmd, QuietMode::No, nullptr, kDiskScanTimeoutMs).toULongLong();
}
scheduleOpts << "--cache" << cacheDaysArg;
bool cacheOk = true;
if (!ui->radioReboot->isChecked()) {
if (elevate) {
cacheOk = runOp(tr("Cache cleanup"), {"clean-cache", "delete", selectedUser, cacheDaysArg});
} else {
const QString output = cmdOut(QString("find /home/%1/.cache -mindepth 1 ! -path '/home/%1/.cache/thumbnails*'%2 -type f -delete")
.arg(selectedUser, period),
QuietMode::No, &cacheOk, kDiskScanTimeoutMs);
// Flatpak may leave a directory owned by its sandbox helper in
// the user's cache. It cannot be traversed by the user, but
// must not make unrelated cache cleanup appear to have failed.
if (!cacheOk && !output.isEmpty()) {
const QString ignoredPath = cachePath + "/.flatpak-helper";
bool onlyIgnoredErrors = true;
for (const QString &line : output.split('\n', Qt::SkipEmptyParts)) {
if (!line.contains(ignoredPath)) {
onlyIgnoredErrors = false;
break;
}
}
if (onlyIgnoredErrors) {
cacheOk = true;
}