Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
572 lines (516 loc) · 25.4 KB
/
Copy pathmain.cpp
File metadata and controls
572 lines (516 loc) · 25.4 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
#include <QApplication>
#include <QCheckBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QFileInfo>
#include <QFormLayout>
#include <QGroupBox>
#include <QHeaderView>
#include <QLabel>
#include <QMessageBox>
#include <QProcess>
#include <QPushButton>
#include <QTemporaryFile>
#include <QScrollArea>
#include <QSet>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDateTime>
#include <algorithm>
#include <utility>
namespace {
struct WakeDevice {
QString wakeFile;
QString sysfsPath;
QString name;
QString kind;
bool enabled = false;
bool pending = false;
};
QString readText(const QString &path)
{
QFile file(path);
if (!file.open(QIODevice::ReadOnly))
return {};
return QString::fromLocal8Bit(file.readAll()).trimmed();
}
QString attributeOrEmpty(const QString &path, const QString &attribute)
{
return readText(path + QLatin1Char('/') + attribute);
}
QString friendlyName(const QString &path)
{
const QString product = attributeOrEmpty(path, QStringLiteral("product"));
const QString name = attributeOrEmpty(path, QStringLiteral("name"));
const QString modalias = attributeOrEmpty(path, QStringLiteral("modalias"));
const QString fileName = QFileInfo(path).fileName();
// Common laptop wake sources deserve stable, human-readable names.
if (path.contains(QStringLiteral("/serio")))
return QStringLiteral("Built-in keyboard");
if (path.contains(QStringLiteral("gpio-keys")))
return QStringLiteral("Power button (GPIO)");
if (modalias.contains(QStringLiteral("PNP0C0D")))
return QStringLiteral("Lid switch");
if (modalias.contains(QStringLiteral("ELAN")) || path.contains(QStringLiteral("i2c-ELAN")))
return QStringLiteral("ELAN touchpad");
if (modalias.contains(QStringLiteral("PNP0B00")))
return QStringLiteral("RTC clock");
if (path.contains(QStringLiteral("alarmtimer")))
return QStringLiteral("RTC alarm timer");
if (path.contains(QStringLiteral("power_supply")))
return product.isEmpty() ? QStringLiteral("Power supply (%1)").arg(fileName)
: QStringLiteral("Power supply: %1").arg(product);
if (path.contains(QStringLiteral("/usb"))) {
const QString manufacturer = attributeOrEmpty(path, QStringLiteral("manufacturer"));
if (!product.isEmpty() && !manufacturer.isEmpty())
return QStringLiteral("%1 %2").arg(manufacturer, product);
if (!product.isEmpty())
return product;
if (!manufacturer.isEmpty())
return manufacturer + QStringLiteral(" USB device");
return QStringLiteral("USB device (%1)").arg(fileName);
}
if (modalias.startsWith(QStringLiteral("pci:"))) {
if (path.contains(QStringLiteral("pcieport")))
return QStringLiteral("PCIe root port");
if (modalias.contains(QStringLiteral("bc0Csc03")))
return QStringLiteral("USB controller");
if (modalias.contains(QStringLiteral("bc04")))
return QStringLiteral("Audio controller");
return QStringLiteral("PCI device (%1)").arg(fileName);
}
if (!product.isEmpty())
return product;
if (!name.isEmpty())
return name;
if (modalias.startsWith(QStringLiteral("acpi:")))
return QStringLiteral("ACPI device (%1)").arg(fileName);
if (modalias.startsWith(QStringLiteral("platform:")))
return QStringLiteral("Platform device (%1)").arg(fileName);
if (modalias.startsWith(QStringLiteral("serio:")))
return QStringLiteral("Keyboard controller");
return fileName.isEmpty() ? QStringLiteral("Unnamed device")
: QStringLiteral("Device (%1)").arg(fileName);
}
QString deviceKind(const QString &path)
{
if (path.contains("/usb"))
return QStringLiteral("USB");
if (path.contains("/pci"))
return QStringLiteral("PCI");
if (path.contains("/i2c"))
return QStringLiteral("I²C");
if (path.contains("/serio"))
return QStringLiteral("Input");
if (path.contains("/platform"))
return QStringLiteral("Platform");
return QStringLiteral("Other");
}
QList<WakeDevice> scanDevices()
{
QList<WakeDevice> result;
QDirIterator it(QStringLiteral("/sys/devices"),
{QStringLiteral("wakeup")},
QDir::Files,
QDirIterator::Subdirectories);
while (it.hasNext()) {
const QString wakeFile = it.next();
// wakeFile is .../<device>/power/wakeup. The device is two levels up
// from the file, not the immediate parent named "power".
QDir deviceDir(QFileInfo(wakeFile).absolutePath());
if (!deviceDir.cdUp())
continue;
const QString path = deviceDir.absolutePath();
const QString state = readText(wakeFile);
if (state != "enabled" && state != "disabled")
continue;
WakeDevice device;
device.wakeFile = wakeFile;
device.sysfsPath = path;
device.name = friendlyName(path);
device.kind = deviceKind(path);
device.enabled = state == "enabled";
result.append(device);
}
std::sort(result.begin(), result.end(), [](const WakeDevice &a, const WakeDevice &b) {
if (a.enabled != b.enabled)
return a.enabled > b.enabled;
return QString::localeAwareCompare(a.name, b.name) < 0;
});
return result;
}
class WakeControlWindow final : public QWidget
{
public:
WakeControlWindow()
{
setWindowTitle(QStringLiteral("Wake Control"));
resize(1050, 650);
auto *root = new QVBoxLayout(this);
auto *intro = new QLabel(
QStringLiteral("Current wake permissions exposed by Linux. Changes are applied only when you choose an action."),
this);
intro->setWordWrap(true);
root->addWidget(intro);
auto *actions = new QHBoxLayout;
refreshButton = new QPushButton(QStringLiteral("Refresh"), this);
toggleAllButton = new QPushButton(QStringLiteral("Toggle all"), this);
enableAllButton = new QPushButton(QStringLiteral("Enable all"), this);
disableAllButton = new QPushButton(QStringLiteral("Disable all"), this);
actions->addWidget(refreshButton);
actions->addStretch();
actions->addWidget(toggleAllButton);
actions->addWidget(enableAllButton);
actions->addWidget(disableAllButton);
root->addLayout(actions);
table = new QTableWidget(this);
table->setColumnCount(5);
table->setHorizontalHeaderLabels({QStringLiteral("Device"), QStringLiteral("Type"),
QStringLiteral("Current state"), QStringLiteral("Pending"),
QStringLiteral("Action")});
table->setSelectionMode(QAbstractItemView::NoSelection);
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
table->verticalHeader()->setVisible(false);
table->horizontalHeader()->setStretchLastSection(true);
table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSortIndicatorShown(true);
root->addWidget(table, 1);
status = new QLabel(this);
status->setStyleSheet(QStringLiteral("color: palette(mid);"));
root->addWidget(status);
auto *bottomActions = new QHBoxLayout;
bottomActions->addStretch();
cancelButton = new QPushButton(QStringLiteral("Cancel"), this);
applyButton = new QPushButton(QStringLiteral("Apply"), this);
savePermanentlyButton = new QPushButton(QStringLiteral("Save Permanently"), this);
bottomActions->addWidget(cancelButton);
bottomActions->addWidget(applyButton);
bottomActions->addWidget(savePermanentlyButton);
root->addLayout(bottomActions);
connect(refreshButton, &QPushButton::clicked, this, [this] { reload(true); });
connect(toggleAllButton, &QPushButton::clicked, this, [this] {
const bool allEnabled = !devices.isEmpty() && std::all_of(
devices.cbegin(), devices.cend(), [](const WakeDevice &d) { return d.pending; });
stageAll(!allEnabled);
});
connect(enableAllButton, &QPushButton::clicked, this, [this] { stageAll(true); });
connect(disableAllButton, &QPushButton::clicked, this, [this] { stageAll(false); });
connect(cancelButton, &QPushButton::clicked, this, [this] { reload(false); });
connect(applyButton, &QPushButton::clicked, this, [this] { apply(); });
connect(savePermanentlyButton, &QPushButton::clicked, this, [this] { savePermanently(); });
connect(table->horizontalHeader(), &QHeaderView::sectionClicked, this, [this](int column) {
if (sortColumn == column)
sortAscending = !sortAscending;
else {
sortColumn = column;
sortAscending = true;
}
sortDevices();
render();
});
reload(false);
}
private:
bool hasPendingChanges() const
{
return std::any_of(devices.cbegin(), devices.cend(), [](const WakeDevice &device) {
return device.enabled != device.pending;
});
}
void reload(bool askBeforeDiscarding)
{
if (askBeforeDiscarding && hasPendingChanges()) {
const auto answer = QMessageBox::question(
this, QStringLiteral("Discard unsaved changes?"),
QStringLiteral("Refresh will discard the wake-permission changes that have not been saved."),
QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
if (answer != QMessageBox::Discard)
return;
}
devices = scanDevices();
for (WakeDevice &device : devices)
device.pending = device.enabled;
sortDevices();
render();
}
void sortDevices()
{
std::stable_sort(devices.begin(), devices.end(), [this](const WakeDevice &left,
const WakeDevice &right) {
const auto value = [this](const WakeDevice &device) {
switch (sortColumn) {
case 0:
return device.name;
case 1:
return device.kind;
case 2:
return device.enabled ? QStringLiteral("Enabled") : QStringLiteral("Disabled");
case 3:
return device.pending ? QStringLiteral("Enabled") : QStringLiteral("Disabled");
case 4:
return device.pending ? QStringLiteral("Disable") : QStringLiteral("Enable");
default:
return QString();
}
};
const int comparison = QString::localeAwareCompare(value(left), value(right));
if (comparison == 0)
return false;
return sortAscending ? comparison < 0 : comparison > 0;
});
}
void render()
{
table->horizontalHeader()->setSortIndicator(
sortColumn, sortAscending ? Qt::AscendingOrder : Qt::DescendingOrder);
table->setRowCount(0);
table->setRowCount(devices.size());
for (int row = 0; row < devices.size(); ++row) {
const WakeDevice &device = devices.at(row);
auto *name = new QTableWidgetItem(device.name);
name->setToolTip(device.sysfsPath);
table->setItem(row, 0, name);
table->setItem(row, 1, new QTableWidgetItem(device.kind));
auto *state = new QTableWidgetItem(device.enabled ? QStringLiteral("Enabled")
: QStringLiteral("Disabled"));
state->setTextAlignment(Qt::AlignCenter);
table->setItem(row, 2, state);
auto *pending = new QTableWidgetItem(device.pending ? QStringLiteral("Enabled")
: QStringLiteral("Disabled"));
pending->setTextAlignment(Qt::AlignCenter);
if (device.pending != device.enabled)
pending->setText(pending->text() + QStringLiteral(" *"));
table->setItem(row, 3, pending);
auto *button = new QPushButton(device.pending ? QStringLiteral("Disable")
: QStringLiteral("Enable"), table);
connect(button, &QPushButton::clicked, this, [this, row] {
if (row >= 0 && row < devices.size())
stageOne(row, !devices.at(row).pending);
});
table->setCellWidget(row, 4, button);
}
const int enabled = std::count_if(devices.cbegin(), devices.cend(), [](const WakeDevice &d) {
return d.enabled;
});
const int pendingChanges = std::count_if(devices.cbegin(), devices.cend(), [](const WakeDevice &d) {
return d.enabled != d.pending;
});
status->setText(QStringLiteral("%1 devices found · %2 currently enabled · %3 unsaved change(s)")
.arg(devices.size()).arg(enabled).arg(pendingChanges));
applyButton->setEnabled(pendingChanges > 0);
cancelButton->setEnabled(pendingChanges > 0);
savePermanentlyButton->setEnabled(!devices.isEmpty());
}
bool runPrivileged(const QString &program, const QStringList &arguments,
const QByteArray &input = {}, QString *error = nullptr)
{
QProcess process;
process.setProgram(QStringLiteral("pkexec"));
QStringList pkexecArguments;
pkexecArguments.append(program);
pkexecArguments.append(arguments);
process.setArguments(pkexecArguments);
process.start();
if (!process.waitForStarted(3000)) {
if (error)
*error = process.errorString();
return false;
}
if (!input.isEmpty())
process.write(input);
process.closeWriteChannel();
if (!process.waitForFinished(15000)) {
process.kill();
if (error)
*error = QStringLiteral("Timed out");
return false;
}
const bool succeeded = process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0;
if (!succeeded && error) {
*error = QString::fromLocal8Bit(process.readAllStandardError()).trimmed();
if (error->isEmpty())
*error = QStringLiteral("The administrator action was cancelled or failed.");
}
return succeeded;
}
bool writeState(const QString &path, bool enabled)
{
// pkexec invokes the desktop polkit agent, which provides the administrator prompt.
return runPrivileged(QStringLiteral("/usr/bin/tee"), {path},
enabled ? QByteArrayLiteral("enabled\n")
: QByteArrayLiteral("disabled\n"));
}
void stageOne(int row, bool enabled)
{
devices[row].pending = enabled;
render();
}
void stageAll(bool enabled)
{
for (WakeDevice &device : devices)
device.pending = enabled;
render();
}
QString udevQuoted(const QString &value) const
{
QString escaped = value;
escaped.replace(QStringLiteral("\\"), QStringLiteral("\\\\"));
escaped.replace(QStringLiteral("\""), QStringLiteral("\\\""));
return escaped;
}
QString persistentRules() const
{
QString rules;
rules += QStringLiteral("# Generated by Wake Control.\n");
rules += QStringLiteral("# These rules preserve the current choices for the devices shown by the app.\n");
rules += QStringLiteral("# They do not impose a default policy on unrelated future devices.\n\n");
for (const WakeDevice &device : devices) {
QString devPath = device.sysfsPath;
if (devPath.startsWith(QStringLiteral("/sys")))
devPath = devPath.mid(4);
if (devPath.isEmpty() || !devPath.startsWith(QLatin1Char('/')))
continue;
rules += QStringLiteral("ACTION==\"add|change|bind\", DEVPATH==\"%1\", "
"TEST==\"power/wakeup\", ATTR{power/wakeup}=\"%2\"\n")
.arg(udevQuoted(devPath), device.pending ? QStringLiteral("enabled")
: QStringLiteral("disabled"));
}
return rules;
}
bool applyPendingStates(QStringList *failed)
{
for (const WakeDevice &device : std::as_const(devices)) {
if (device.enabled == device.pending)
continue;
if (!writeState(device.wakeFile, device.pending) && failed)
failed->append(device.sysfsPath);
}
return !failed || failed->isEmpty();
}
void apply()
{
if (!hasPendingChanges())
return;
const int changes = std::count_if(devices.cbegin(), devices.cend(), [](const WakeDevice &device) {
return device.enabled != device.pending;
});
const auto answer = QMessageBox::question(
this, QStringLiteral("Apply wake-permission changes?"),
QStringLiteral("Apply %1 change(s) to the running kernel?\n\n"
"These changes are temporary and may be reset by a reboot or device reconnect.")
.arg(changes),
QMessageBox::Apply | QMessageBox::Cancel, QMessageBox::Apply);
if (answer != QMessageBox::Apply)
return;
QStringList failed;
applyPendingStates(&failed);
reload(false);
if (!failed.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("Some changes could not be applied"),
QStringLiteral("%1 device(s) could not be changed.\n\n%2")
.arg(failed.size())
.arg(failed.join(QLatin1Char('\n'))));
}
}
void savePermanently()
{
const int pendingChanges = std::count_if(devices.cbegin(), devices.cend(), [](const WakeDevice &device) {
return device.enabled != device.pending;
});
const auto answer = QMessageBox::question(
this, QStringLiteral("Save wake permissions permanently?"),
QStringLiteral("Persist the current pending state for all %1 devices?\n\n"
"This will open an administrator authentication window and write a udev rule. "
"The settings will also be applied to the running kernel%2.")
.arg(devices.size())
.arg(pendingChanges > 0 ? QStringLiteral(".") : QStringLiteral(" (there are no pending changes)")),
QMessageBox::Save | QMessageBox::Cancel, QMessageBox::Save);
if (answer != QMessageBox::Save)
return;
QTemporaryFile temporaryFile(QDir::tempPath() + QStringLiteral("/wake-control-XXXXXX.rules"));
temporaryFile.setAutoRemove(false);
if (!temporaryFile.open()) {
QMessageBox::critical(this, QStringLiteral("Cannot save permanent policy"),
QStringLiteral("Could not create a temporary rules file."));
return;
}
const QByteArray rules = persistentRules().toUtf8();
if (temporaryFile.write(rules) != rules.size() || !temporaryFile.flush()) {
const QString path = temporaryFile.fileName();
temporaryFile.remove();
QMessageBox::critical(this, QStringLiteral("Cannot save permanent policy"),
QStringLiteral("Could not write the temporary rules file:\n%1").arg(path));
return;
}
const QString temporaryPath = temporaryFile.fileName();
temporaryFile.close();
QString error;
const bool installed = runPrivileged(
QStringLiteral("/usr/bin/install"),
{QStringLiteral("-o"), QStringLiteral("root"), QStringLiteral("-g"), QStringLiteral("root"),
QStringLiteral("-m"), QStringLiteral("0644"), temporaryPath,
QStringLiteral("/etc/udev/rules.d/99-wakeup-control.rules")}, {}, &error);
QFile::remove(temporaryPath);
if (!installed) {
QMessageBox::warning(this, QStringLiteral("Permanent save cancelled"),
QStringLiteral("The administrator action did not install the udev rule.\n\n%1")
.arg(error));
return;
}
// Reload rules so the next device event uses the new policy. Current devices
// are applied explicitly below because udev rules do not retroactively run.
QString reloadError;
const bool reloaded = runPrivileged(QStringLiteral("/usr/bin/udevadm"), {QStringLiteral("control"),
QStringLiteral("--reload-rules")},
{}, &reloadError);
QStringList failed;
applyPendingStates(&failed);
reload(false);
if (!failed.isEmpty()) {
QMessageBox::warning(this, QStringLiteral("Permanent policy saved; some runtime changes failed"),
QStringLiteral("The persistent udev rule was installed, but %1 current device(s) "
"could not be changed:\n\n%2")
.arg(failed.size())
.arg(failed.join(QLatin1Char('\n'))));
} else if (!reloaded) {
QMessageBox::warning(this, QStringLiteral("Permanent policy saved; udev reload failed"),
QStringLiteral("The persistent rule was installed and current settings were applied, "
"but udev could not be reloaded immediately. It will take effect "
"after the next udev reload or reboot.\n\n%1")
.arg(reloadError));
} else {
QMessageBox::information(this, QStringLiteral("Wake policy saved"),
QStringLiteral("The wake-permission policy was saved permanently and applied now."));
}
}
QList<WakeDevice> devices;
QTableWidget *table = nullptr;
QLabel *status = nullptr;
QPushButton *refreshButton = nullptr;
QPushButton *toggleAllButton = nullptr;
QPushButton *enableAllButton = nullptr;
QPushButton *disableAllButton = nullptr;
QPushButton *cancelButton = nullptr;
QPushButton *applyButton = nullptr;
QPushButton *savePermanentlyButton = nullptr;
int sortColumn = 0;
bool sortAscending = true;
};
} // namespace
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QApplication::setApplicationName(QStringLiteral("Wake Control"));
QApplication::setApplicationVersion(QStringLiteral("0.1.0"));
WakeControlWindow window;
window.show();
return app.exec();
}