forked from AdrianTM/mx-tools
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
784 lines (680 loc) · 26.2 KB
/
mainwindow.cpp
File metadata and controls
784 lines (680 loc) · 26.2 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
/**********************************************************************
* Copyright (C) 2014 MX Authors
*
* Authors: Adrian
* MX Linux <http://mxlinux.org>
*
* This file is part of MX Tools.
*
* MX Tools 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.
*
* MX Tools 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 MX Tools. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************/
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <QFontMetrics>
#include <QHash>
#include <QLatin1String>
#include <QProcess>
#include <QRegularExpression>
#include <QResizeEvent>
#include <QScreen>
#include <QSpacerItem>
#include <QTextStream>
#include "about.h"
#include "flatbutton.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#ifndef VERSION
#define VERSION "?.?.?.?"
#endif
namespace
{
QString rootFileSystemType()
{
QFile mountsFile(QStringLiteral("/proc/mounts"));
if (!mountsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
return {};
}
QTextStream stream(&mountsFile);
while (!stream.atEnd()) {
const QString line = stream.readLine();
const QStringList fields = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);
if (fields.size() < 3) {
continue;
}
if (fields.at(1) == QLatin1String("/")) {
return fields.at(2);
}
}
return {};
}
}
MainWindow::MainWindow(QWidget *parent)
: QDialog(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setConnections();
setWindowFlags(Qt::Window); // Enables the close, min, and max buttons
checkHideToolsInMenu();
initializeCategoryLists();
filterLiveEnvironmentItems();
filterDesktopEnvironmentItems();
populateCategoryMap();
readInfo(category_map);
iconSize = settings.value("icon_size", iconSize).toInt();
addButtons(info_map);
ui->textSearch->setFocus();
restoreWindowGeometry();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setConnections()
{
connect(ui->checkHide, &QCheckBox::clicked, this, &MainWindow::checkHide_clicked);
connect(ui->pushAbout, &QPushButton::clicked, this, &MainWindow::pushAbout_clicked);
connect(ui->pushCancel, &QPushButton::clicked, this, &MainWindow::close);
connect(ui->pushHelp, &QPushButton::clicked, this, &MainWindow::pushHelp_clicked);
connect(ui->textSearch, &QLineEdit::textChanged, this, &MainWindow::textSearch_textChanged);
}
void MainWindow::checkHideToolsInMenu()
{
const QDir userApplicationsDir(QDir::homePath() + USER_APPLICATIONS_PATH);
const QString userDesktopFilePath = userApplicationsDir.filePath("mx-user.desktop");
QFile userDesktopFile(userDesktopFilePath);
if (!userDesktopFile.exists()) {
ui->checkHide->setChecked(false);
return;
}
if (userDesktopFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
ui->checkHide->setChecked(userDesktopFile.readAll().contains("NoDisplay=true"));
userDesktopFile.close();
} else {
ui->checkHide->setChecked(false);
}
}
void MainWindow::initializeCategoryLists()
{
for (auto it = categories.cbegin(); it != categories.cend(); ++it) {
*(it.value()) = listDesktopFiles(it.key(), APPLICATIONS_PATH);
}
}
void MainWindow::filterLiveEnvironmentItems()
{
const QString partitionType = rootFileSystemType();
const bool live = partitionType == QLatin1String("aufs") || partitionType == QLatin1String("overlay");
if (!live) {
QStringList itemsToRemove {"mx-remastercc.desktop", "live-kernel-updater.desktop"};
live_list.erase(std::remove_if(live_list.begin(), live_list.end(),
[&itemsToRemove](const QString &item) {
return item.contains(itemsToRemove.at(0))
|| item.contains(itemsToRemove.at(1));
}),
live_list.end());
}
}
void MainWindow::filterDesktopEnvironmentItems()
{
QStringList termsToRemove {qgetenv("XDG_CURRENT_DESKTOP") == "live" ? "MX-OnlyInstalled" : "MX-OnlyLive"};
const QMap<QString, QString> desktopTerms {
{"XFCE", "OnlyShowIn=XFCE"}, {"Fluxbox", "OnlyShowIn=FLUXBOX"}, {"KDE", "OnlyShowIn=KDE"}};
for (const auto &[desktop, term] : desktopTerms.asKeyValueRange()) {
if (qgetenv("XDG_CURRENT_DESKTOP") != desktop) {
termsToRemove << term;
}
}
for (auto it = categories.begin(); it != categories.end(); ++it) {
removeEnvExclusive(it.value(), termsToRemove);
}
}
void MainWindow::populateCategoryMap()
{
for (auto it = categories.cbegin(); it != categories.cend(); ++it) {
category_map.insert(it.key(), *(it.value()));
}
}
void MainWindow::restoreWindowGeometry()
{
auto size = this->size();
restoreGeometry(settings.value("geometry").toByteArray());
if (isMaximized()) { // if started maximized give option to resize to normal window size
resize(size);
auto screenGeometry = QApplication::primaryScreen()->geometry();
move((screenGeometry.width() - width()) / 2, (screenGeometry.height() - height()) / 2);
}
}
// List .desktop files that contain a specific string
QStringList MainWindow::listDesktopFiles(const QString &searchString, const QString &location)
{
QDirIterator it(location, {"*.desktop"}, QDir::Files, QDirIterator::Subdirectories);
QStringList matchingFiles;
while (it.hasNext()) {
const QString filePath = it.next();
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
continue;
}
QTextStream stream(&file);
while (!stream.atEnd()) {
if (stream.readLine().contains(searchString)) {
matchingFiles << filePath;
break;
}
}
}
return matchingFiles;
}
int MainWindow::calculateMaxElements(const CategoryToolsMap &infoMap)
{
maxElements = 0;
// Find maximum number of elements across all categories
for (const auto &categoryTools : infoMap) {
maxElements = std::max(maxElements, static_cast<int>(categoryTools.size()));
}
// Only recalculate button width if not cached (expensive operation)
if (cachedMaxButtonWidth == 0) {
const QFontMetrics fm(QApplication::font());
constexpr int buttonPadding = 16; // Left/right padding inside button
// Check ALL categories for the widest button text
for (const auto &categoryTools : infoMap) {
for (const auto &toolInfo : categoryTools) {
const int textWidth = fm.horizontalAdvance(toolInfo.name);
cachedMaxButtonWidth = std::max(cachedMaxButtonWidth, textWidth);
}
}
// Add icon size, spacing between icon and text, and button padding
cachedMaxButtonWidth += iconSize + 8 + buttonPadding;
}
// Calculate maximum columns that fit in window width
return std::max(1, width() / cachedMaxButtonWidth);
}
// Load info (name, comment, exec, iconName, category, terminal) to the info_map
void MainWindow::readInfo(const CategoryFileMap &categoryMap)
{
const QString lang = QLocale().name().split(QStringLiteral("_")).first();
const QString langRegion = QLocale().name();
// Pre-allocate strings for common keys
const QString nameKey = QStringLiteral("Name");
const QString commentKey = QStringLiteral("Comment");
const QString execKey = QStringLiteral("Exec");
const QString iconKey = QStringLiteral("Icon");
const QString terminalKey = QStringLiteral("Terminal");
const QString enLang = QStringLiteral("en");
for (auto it = categoryMap.cbegin(); it != categoryMap.cend(); ++it) {
const QString category = it.key();
const QStringList &fileList = it.value();
QVector<ToolInfo> categoryTools;
categoryTools.reserve(fileList.size());
for (const QString &fileName : fileList) {
QFile file(fileName);
if (!file.open(QFile::Text | QFile::ReadOnly)) {
continue;
}
QTextStream stream(&file);
QString text = stream.readAll();
file.close();
QString name = lang != enLang ? getTranslation(text, nameKey, langRegion, lang) : QString();
QString comment = lang != enLang ? getTranslation(text, commentKey, langRegion, lang) : QString();
name = name.isEmpty() ? getValueFromText(text, nameKey)
.remove(QRegularExpression(QStringLiteral("^MX ")))
.replace(QStringLiteral("&"), QStringLiteral("&&"))
: name;
comment = comment.isEmpty() ? getValueFromText(text, commentKey) : comment;
QString exec = getValueFromText(text, execKey);
fixExecItem(&exec);
ToolInfo toolInfo;
toolInfo.fileName = fileName;
toolInfo.name = name;
toolInfo.comment = comment;
toolInfo.iconName = getValueFromText(text, iconKey);
toolInfo.exec = exec;
toolInfo.category = category;
toolInfo.runInTerminal = getValueFromText(text, terminalKey).compare("true", Qt::CaseInsensitive) == 0;
categoryTools.append(toolInfo);
}
info_map.insert(category, categoryTools);
}
}
QString MainWindow::getTranslation(const QString &text, const QString &key, const QString &langRegion,
const QString &lang)
{
static QHash<QString, QRegularExpression> regexCache;
// First try to find translation for specific region (e.g., en_US)
const QString regionPattern = key + QStringLiteral("[") + langRegion + QStringLiteral("]");
auto it = regexCache.find(regionPattern);
if (it == regexCache.end()) {
QString pattern = QStringLiteral("^") + key + QStringLiteral("\\[") + langRegion + QStringLiteral("\\]=(.*)$");
QRegularExpression re(pattern);
re.setPatternOptions(QRegularExpression::MultilineOption);
it = regexCache.insert(regionPattern, re);
}
QRegularExpressionMatch match = it->match(text);
if (match.hasMatch()) {
QString translation = match.captured(1).trimmed();
if (!translation.isEmpty()) {
return translation;
}
}
// Fall back to general language (e.g., en)
const QString langPattern = key + QStringLiteral("[") + lang + QStringLiteral("]");
it = regexCache.find(langPattern);
if (it == regexCache.end()) {
QString pattern = QStringLiteral("^") + key + QStringLiteral("\\[") + lang + QStringLiteral("\\]=(.*)$");
QRegularExpression re(pattern);
re.setPatternOptions(QRegularExpression::MultilineOption);
it = regexCache.insert(langPattern, re);
}
match = it->match(text);
return match.hasMatch() ? match.captured(1).trimmed() : QString();
}
QString MainWindow::getValueFromText(const QString &text, const QString &key)
{
static QHash<QString, QRegularExpression> regexCache;
auto it = regexCache.find(key);
if (it == regexCache.end()) {
QString pattern = QStringLiteral("^") + key + QStringLiteral("=(.*)$");
QRegularExpression re(pattern);
re.setPatternOptions(QRegularExpression::MultilineOption);
it = regexCache.insert(key, re);
}
return it->match(text).captured(1).trimmed();
}
// Read the info_map and add the buttons to the UI
void MainWindow::addButtons(const CategoryToolsMap &infoMap)
{
clearGrid();
const int max_columns = calculateMaxElements(infoMap);
int row = 0;
int actualMaxCol = 0;
bool addedWidgets = false;
// Add buttons for each category
for (auto it = infoMap.cbegin(); it != infoMap.cend(); ++it) {
const QString &category = it.key();
const auto &categoryTools = it.value();
if (categoryTools.isEmpty()) {
continue;
}
if (row > 0) {
addCategorySeparator(row, max_columns);
}
addCategoryHeader(category, row, max_columns);
addedWidgets = true;
// Add buttons for this category
int col = 0;
for (const auto &toolInfo : categoryTools) {
auto *btn = createButton(toolInfo);
ui->gridLayout_btn->addWidget(btn, row, col);
actualMaxCol = std::max(actualMaxCol, col + 1);
addedWidgets = true;
// Move to the next row if more items than max columns
if (++col >= max_columns) {
col = 0;
++row;
}
}
}
colCount = actualMaxCol;
if (addedWidgets) {
auto *spacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
ui->gridLayout_btn->addItem(spacer, row + 1, 0, 1, std::max(1, max_columns));
}
}
void MainWindow::addCategorySeparator(int &row, int max_columns)
{
auto *line = new QFrame(this);
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
ui->gridLayout_btn->addWidget(line, ++row, 0, 1, max_columns);
}
void MainWindow::addCategoryHeader(const QString &category, int &row, int max_columns)
{
auto *label = new QLabel(category, this);
static const QRegularExpression mxPrefixRegex(QStringLiteral("^MX-"));
label->setText(label->text().remove(mxPrefixRegex));
QFont font;
font.setBold(true);
font.setUnderline(true);
label->setFont(font);
ui->gridLayout_btn->addWidget(label, ++row, 0, 1, max_columns);
++row;
}
FlatButton *MainWindow::createButton(const ToolInfo &toolInfo)
{
auto *btn = new FlatButton(toolInfo.name);
btn->setToolTip(toolInfo.comment);
btn->setAutoDefault(false);
const QIcon icon = findIcon(toolInfo.iconName);
btn->setIcon(icon);
btn->setIconSize({iconSize, iconSize});
// Configure button command
const QString &exec = toolInfo.exec;
const bool runInTerminal = toolInfo.runInTerminal;
btn->setProperty("command", runInTerminal ? "x-terminal-emulator -e " + exec : exec);
connect(btn, &FlatButton::clicked, this, &MainWindow::btn_clicked);
return btn;
}
QIcon MainWindow::findIcon(const QString &iconName)
{
static QHash<QString, QIcon> iconCache;
static QIcon defaultIcon;
static bool defaultIconLoaded = false;
static bool resolvingDefault = false;
if (iconName.isEmpty()) {
if (!defaultIconLoaded) {
resolvingDefault = true;
defaultIcon = findIcon(DEFAULT_ICON_NAME);
defaultIconLoaded = true;
resolvingDefault = false;
}
return defaultIcon;
}
// Check cache first
auto cacheIt = iconCache.find(iconName);
if (cacheIt != iconCache.end()) {
return *cacheIt;
}
// Check if the icon name is an absolute path and exists
if (QFileInfo(iconName).isAbsolute() && QFile::exists(iconName)) {
QIcon icon(iconName);
iconCache.insert(iconName, icon);
return icon;
}
// Prepare regular expression to strip extension
static const QRegularExpression re(R"(\.(png|svg|xpm)$)");
QString nameNoExt = iconName;
nameNoExt.remove(re);
// Return the themed icon if available
if (QIcon::hasThemeIcon(nameNoExt)) {
QIcon icon = QIcon::fromTheme(nameNoExt);
iconCache.insert(iconName, icon);
return icon;
}
// Define common search paths for icons
QStringList searchPaths {QDir::homePath() + HOME_SHARE_ICONS_PATH,
PIXMAPS_PATH,
LOCAL_SHARE_ICONS_PATH,
SHARE_ICONS_PATH,
HICOLOR_SCALABLE_PATH,
HICOLOR_48_PATH,
ADWAITA_PATH};
// Optimization: search first for the full iconName with the specified extension
auto it = std::ranges::find_if(searchPaths, [&](const QString &path) {
return QFile::exists(path + iconName);
});
if (it != searchPaths.cend()) {
QIcon icon(*it + iconName);
iconCache.insert(iconName, icon);
return icon;
}
// Search for the icon without extension in the specified paths
for (const QString &path : searchPaths) {
if (!QFile::exists(path)) {
continue;
}
for (const auto &ext : {QStringLiteral(".png"), QStringLiteral(".svg"), QStringLiteral(".xpm")}) {
const QString file = path + nameNoExt + ext;
if (QFile::exists(file)) {
QIcon icon(file);
iconCache.insert(iconName, icon);
return icon;
}
}
}
// If the icon is "utilities-terminal" and not found, return the default icon if it's already loaded
if (iconName == DEFAULT_ICON_NAME) {
if (!defaultIconLoaded) {
defaultIcon = QIcon();
defaultIconLoaded = true;
}
iconCache.insert(iconName, defaultIcon);
return defaultIcon;
}
// If the icon is not "utilities-terminal", try to load the default icon
if (!defaultIconLoaded) {
if (!resolvingDefault) {
resolvingDefault = true;
defaultIcon = findIcon(DEFAULT_ICON_NAME);
defaultIconLoaded = true;
resolvingDefault = false;
} else {
defaultIcon = QIcon();
defaultIconLoaded = true;
}
}
iconCache.insert(iconName, defaultIcon);
return defaultIcon;
}
void MainWindow::btn_clicked()
{
hide();
// Get sender and check for null pointer
auto *senderObj = sender();
if (!senderObj) {
qWarning() << "btn_clicked called with null sender";
show();
return;
}
const QString commandString = senderObj->property("command").toString();
QStringList cmdList = QProcess::splitCommand(commandString);
if (cmdList.isEmpty()) {
qWarning() << "Empty command list";
show();
return;
}
QString command = cmdList.takeFirst();
// Check if list has elements before accessing last()
if (!cmdList.isEmpty() && cmdList.last() == "&") {
cmdList.removeLast();
if (!QProcess::startDetached(command, cmdList)) {
qWarning() << "Failed to start detached process:" << command << cmdList;
}
} else {
int exitCode = QProcess::execute(command, cmdList);
if (exitCode != 0) {
qWarning() << "Process failed with exit code:" << exitCode << "Command:" << command << cmdList;
// Show error message to user and ensure window is shown again
QMessageBox::critical(this, tr("Error"),
tr("Failed to execute command") + "\n" +
tr("Command: %1").arg(command + " " + cmdList.join(" ")) + "\n" +
tr("Exit code: %1").arg(exitCode));
}
}
show();
}
void MainWindow::closeEvent(QCloseEvent * /*unused*/)
{
settings.setValue("geometry", saveGeometry());
}
void MainWindow::resizeEvent(QResizeEvent *event)
{
if (event->oldSize().width() == event->size().width()) {
return;
}
// Fast column calculation using cached button width (avoids full recalculation)
const int effectiveWidth = cachedMaxButtonWidth > 0 ? cachedMaxButtonWidth : 200;
const int newColCount = std::max(1, width() / effectiveWidth);
// Early exit: column count unchanged or already at max elements
if (newColCount == colCount || (newColCount >= maxElements && colCount == maxElements)) {
return;
}
// Full recalculation to get exact column count (updates maxElements too)
const int exactColCount = calculateMaxElements(info_map);
if (colCount == exactColCount) {
return;
}
colCount = exactColCount;
if (ui->textSearch->text().isEmpty()) {
addButtons(info_map);
} else {
textSearch_textChanged(ui->textSearch->text());
}
}
// Hide icons in menu checkbox
void MainWindow::checkHide_clicked(bool checked)
{
for (const QStringList &list : std::as_const(category_map)) {
for (const QString &fileName : std::as_const(list)) {
hideShowIcon(fileName, checked);
}
}
QProcess process;
process.start("pgrep", {"xfce4-panel"});
process.waitForFinished();
if (process.exitCode() == 0) {
QProcess::execute("xfce4-panel", {"--restart"});
}
}
// Hide or show icon for .desktop file
void MainWindow::hideShowIcon(const QString &fileName, bool hide)
{
QFileInfo fileInfo(fileName);
const QDir userApplicationsDir(QDir::homePath() + USER_APPLICATIONS_PATH);
if (!userApplicationsDir.exists() && !QDir().mkpath(userApplicationsDir.absolutePath())) {
qWarning() << "Failed to create directory:" << userApplicationsDir.absolutePath();
return;
}
const QString fileNameLocal = userApplicationsDir.filePath(fileInfo.fileName());
if (!hide) {
QFile::remove(fileNameLocal);
} else {
QFile::copy(fileName, fileNameLocal);
// Read and modify the file content using Qt APIs
QFile localFile(fileNameLocal);
if (!localFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qWarning() << "Failed to open file for reading:" << fileNameLocal;
return;
}
QTextStream in(&localFile);
QStringList lines;
// Process each line
while (!in.atEnd()) {
QString line = in.readLine();
// Skip NoDisplay and Hidden lines
if (line.startsWith(QLatin1String("NoDisplay=")) || line.startsWith(QLatin1String("Hidden="))) {
continue;
}
lines << line;
// Add NoDisplay=true immediately after Exec line
if (line.startsWith(QLatin1String("Exec="))) {
lines << QLatin1String("NoDisplay=true");
}
}
localFile.close();
// Write the modified content back
if (!localFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
qWarning() << "Failed to open file for writing:" << fileNameLocal;
return;
}
QTextStream out(&localFile);
for (const QString &line : lines) {
out << line << Qt::endl;
}
}
}
void MainWindow::pushAbout_clicked()
{
hide();
displayAboutMsgBox(
tr("About MX Tools"),
"<p align=\"center\"><b><h2>" + tr("MX Tools") + "</h2></b></p><p align=\"center\">" + tr("Version: ") + VERSION
+ "</p><p align=\"center\"><h3>" + tr("Configuration Tools for MX Linux")
+ "</h3></p><p align=\"center\"><a href=\"http://mxlinux.org\">http://mxlinux.org</a><br /></p>"
"<p align=\"center\">"
+ tr("Copyright (c) MX Linux") + "<br /><br /></p>",
LICENSE_PATH, tr("%1 License").arg(windowTitle()));
show();
}
void MainWindow::pushHelp_clicked()
{
if (QFile::exists(MX_MANUAL_PATH)) {
if (!QProcess::startDetached(MX_MANUAL_PATH, {})) {
qWarning() << "Failed to start mx-manual";
return;
}
} else { // for MX19?
if (!QProcess::startDetached("xdg-open", {QStringLiteral("file://") + FALLBACK_DOC_PATH})) {
qWarning() << "Failed to open fallback documentation";
return;
}
}
}
void MainWindow::textSearch_textChanged(const QString &searchTerm)
{
if (searchTerm.isEmpty()) {
addButtons(info_map);
return;
}
CategoryToolsMap filteredMap;
// Iterate over categories in info_map
for (auto it = info_map.constBegin(); it != info_map.constEnd(); ++it) {
const auto &category = it.key();
const auto &categoryTools = it.value();
QVector<ToolInfo> filteredCategoryTools;
for (const auto &toolInfo : categoryTools) {
if (toolInfo.name.contains(searchTerm, Qt::CaseInsensitive)
|| toolInfo.comment.contains(searchTerm, Qt::CaseInsensitive)
|| category.contains(searchTerm, Qt::CaseInsensitive)) {
filteredCategoryTools.append(toolInfo);
}
}
if (!filteredCategoryTools.isEmpty()) {
filteredMap.insert(category, filteredCategoryTools);
}
}
addButtons(filteredMap);
}
// Strip %f, %F, %U, etc. if exec expects a file name since it's called without an argument from this launcher.
void MainWindow::fixExecItem(QString *item)
{
item->remove(QRegularExpression(R"( %[a-zA-Z])"));
}
// When running live remove programs meant only for installed environments and the other way round
// Remove XfceOnly and FluxboxOnly when not running in that environment
void MainWindow::removeEnvExclusive(QStringList *list, const QStringList &termsToRemove)
{
for (auto it = list->begin(); it != list->end();) {
const QString &filePath = *it;
QFile file(filePath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QString fileContent = QString::fromUtf8(file.readAll());
file.close();
bool containsTerm = std::ranges::any_of(termsToRemove, [&fileContent](const QString &term) {
return fileContent.contains(term, Qt::CaseInsensitive);
});
containsTerm ? it = list->erase(it) : ++it;
} else {
qWarning() << "Could not open file:" << filePath;
++it;
}
}
}
// Remove all items from the layout
void MainWindow::clearGrid()
{
for (int row = 0; row < ui->gridLayout_btn->rowCount(); ++row) {
ui->gridLayout_btn->setRowStretch(row, 0);
}
for (int col = 0; col < ui->gridLayout_btn->columnCount(); ++col) {
ui->gridLayout_btn->setColumnStretch(col, 0);
}
QLayoutItem *child;
while ((child = ui->gridLayout_btn->takeAt(0)) != nullptr) {
if (child->widget()) {
child->widget()->deleteLater();
}
delete child;
}
}