forked from chkboom/mx-datetime
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdatetime.cpp
More file actions
922 lines (873 loc) · 33.9 KB
/
datetime.cpp
File metadata and controls
922 lines (873 loc) · 33.9 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
/**********************************************************************
* MX Date/Time application.
**********************************************************************
* Copyright (C) 2019 by AK-47
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mx-datetime.
**********************************************************************/
#include <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QLineEdit>
#include <QMessageBox>
#include <QProcess>
#include <QTemporaryFile>
#include <QTextCharFormat>
#include <QTimeZone>
#include "about.h"
#include "datetime.h"
#include <unistd.h>
using namespace Qt::StringLiterals;
MXDateTime::MXDateTime(QWidget *parent)
: QDialog(parent),
updater(this)
{
setupUi(this);
setClockLock(true);
setWindowFlags(Qt::Window); // for the close, min and max buttons
QTextCharFormat tcfmt;
tcfmt.setFontPointSize(calendar->font().pointSizeF() * 0.75);
calendar->setHeaderTextFormat(tcfmt);
connect(pushClose, &QPushButton::clicked, this, &MXDateTime::close);
connect(tabsDateTime, &QTabWidget::currentChanged, this, &MXDateTime::loadTab);
// This runs the slow startup tasks after the GUI is displayed.
QTimer::singleShot(0, this, &MXDateTime::startup);
}
void MXDateTime::startup()
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
timeEdit->setTimeZone(QTimeZone::systemTimeZone()); // TODO: Implement time zone differences properly.
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
timeEdit->setTimeSpec(Qt::LocalTime); // TODO: Implement time zone differences properly.
#pragma GCC diagnostic pop
#endif
timeEdit->setDateTime(QDateTime::currentDateTime()); // Curtail the sudden jump.
connect(pushReadHardware, &QPushButton::clicked, this, &MXDateTime::readHardwareClock);
// Make the NTP server table columns the right proportions.
int colSizes[3];
addServerRow(true, QString(), QString(), QString());
tableServers->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
for (int ixi = 0; ixi < 3; ++ixi) {
colSizes[ixi] = tableServers->columnWidth(ixi);
}
tableServers->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
for (int ixi = 0; ixi < 3; ++ixi) {
tableServers->setColumnWidth(ixi, colSizes[ixi]);
}
tableServers->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
tableServers->removeRow(0);
// Server page slots
connect(pushServerMoveUp, &QPushButton::clicked, pushServerMoveUp, [this]() { moveServerRow(-1); });
connect(pushServerMoveDown, &QPushButton::clicked, pushServerMoveDown, [this]() { moveServerRow(1); });
connect(tableServers, &QTableWidget::itemChanged, this, &MXDateTime::serverRowChanged);
// Used to decide the type of commands to run on this system.
if (QFile::exists(u"/run/openrc"_s)) {
sysInit = OpenRC;
} else {
QFile proc1comm(u"/proc/1/comm"_s);
if (proc1comm.open(QIODevice::ReadOnly)) {
if (proc1comm.readAll().contains("systemd")) {
sysInit = SystemD;
}
proc1comm.close();
}
}
static const char *sysInitNames[] = {"SystemV", "OpenRC", "SystemD"};
qDebug() << "Init system:" << sysInitNames[sysInit];
// Time zone areas.
QByteArray zoneOut;
execute(u"find"_s,
{u"-L"_s, u"/usr/share/zoneinfo"_s, u"-mindepth"_s, u"2"_s, u"!"_s,
u"-path"_s, u"*/posix/*"_s, u"!"_s, u"-path"_s, u"*/right/*"_s,
u"-type"_s, u"f"_s, u"-printf"_s, u"%P\n"_s},
&zoneOut);
zones = zoneOut.trimmed().split('\n');
comboTimeZone->blockSignals(true); // Keep blocked until loadSysTimeConfig().
comboTimeArea->clear();
for (const QByteArray &zone : std::as_const(zones)) {
const QString &area = QString(zone).section('/', 0, 0);
if (comboTimeArea->findData(area) < 0) {
QString text(area);
if (area == "Indian"_L1 || area == "Pacific"_L1 || area == "Atlantic"_L1 || area == "Arctic"_L1) {
text.append(" Ocean");
}
comboTimeArea->addItem(text, area);
}
}
comboTimeArea->model()->sort(0);
// Prepare the GUI.
connect(pushAbout, &QPushButton::clicked, this, &MXDateTime::aboutClicked);
connect(pushHelp, &QPushButton::clicked, this, &MXDateTime::helpClicked);
connect(pushApply, &QPushButton::clicked, this, &MXDateTime::applyClicked);
setClockLock(false);
// Setup the display update timer.
connect(&updater, &QTimer::timeout, this, QOverload<>::of(&MXDateTime::update));
updater.start(0);
}
void MXDateTime::setClockLock(bool locked)
{
if (clockLock != locked) {
clockLock = locked;
if (locked) {
qApp->setOverrideCursor(QCursor(Qt::BusyCursor));
} else {
loadTab(tabsDateTime->currentIndex());
}
tabsDateTime->blockSignals(locked);
tabDateTime->setDisabled(locked);
tabHardware->setDisabled(locked);
tabNetwork->setDisabled(locked);
pushApply->setDisabled(locked);
pushClose->setDisabled(locked);
if (!locked) {
qApp->restoreOverrideCursor();
}
}
}
bool MXDateTime::shell(const QString &cmd, QByteArray *output, bool elevate)
{
qDebug() << "Shell:" << cmd;
return execute(u"bash"_s, {u"-c"_s, cmd}, output, nullptr, elevate);
}
bool MXDateTime::execute(const QString &program, const QStringList &arguments, QByteArray *output, QByteArray *error,
bool elevate)
{
qDebug() << "Exec:" << program << arguments;
QProcess proc(this);
QEventLoop eloop;
connect(&proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), &eloop, &QEventLoop::quit);
if (elevate && getuid() != 0) {
QString runAsRoot = QFile::exists(u"/usr/bin/pkexec"_s) ? u"/usr/bin/pkexec"_s : u"/usr/bin/gksu"_s;
proc.start(runAsRoot, (QStringList() << u"/usr/lib/mx-datetime/helper"_s << program << arguments));
} else {
proc.start(program, arguments);
}
if (!output) {
proc.closeReadChannel(QProcess::StandardOutput);
}
proc.closeWriteChannel();
eloop.exec();
disconnect(&proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), nullptr, nullptr);
const QByteArray &sout = proc.readAllStandardOutput();
if (output) {
output->append(sout);
} else if (!sout.isEmpty()) {
qDebug() << "SOut:" << proc.readAllStandardOutput();
}
const QByteArray &serr = proc.readAllStandardError();
if (error) {
error->append(serr);
} else if (!serr.isEmpty()) {
qDebug() << "SErr:" << serr;
}
qDebug() << "Exit:" << proc.exitCode() << proc.exitStatus();
return (proc.exitStatus() == QProcess::NormalExit && proc.exitCode() == 0);
}
bool MXDateTime::executeAsRoot(const QString &program, const QStringList &arguments, QByteArray *output,
QByteArray *error)
{
return execute(program, arguments, output, error, true);
}
void MXDateTime::loadTab(int index)
{
const unsigned int loaded = 1 << index;
if ((loadedTabs & loaded) == 0) {
loadedTabs |= loaded;
setClockLock(true);
switch (index) {
case 0:
connect(comboTimeArea, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MXDateTime::timeAreaIndexChanged);
connect(comboTimeZone, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MXDateTime::timeZoneIndexChanged);
connect(calendar, &QCalendarWidget::selectionChanged, this, &MXDateTime::calendarSelectionChanged);
connect(timeEdit, &MTimeEdit::dateTimeChanged, this, &MXDateTime::timeEditDateTimeChanged);
loadDateTime();
break; // Date & Time.
case 1:
connect(pushHardwareAdjust, &QPushButton::clicked, this, &MXDateTime::hardwareAdjustClicked);
connect(pushSystemToHardware, &QPushButton::clicked, this, &MXDateTime::systemToHardwareClicked);
connect(pushHardwareToSystem, &QPushButton::clicked, this, &MXDateTime::hardwareToSystemClicked);
readHardwareClock();
break; // Hardware Clock.
case 2:
connect(pushSyncNow, &QPushButton::clicked, this, &MXDateTime::syncNowClicked);
connect(tableServers, &QTableWidget::itemSelectionChanged,
this, &MXDateTime::serversItemSelectionChanged);
connect(pushServerAdd, &QPushButton::clicked, this, &MXDateTime::serverAddClicked);
connect(pushServerRemove, &QPushButton::clicked, this, &MXDateTime::serverRemoveClicked);
loadNetworkTime();
break; // Network Time.
}
setClockLock(false);
}
}
// DATE & TIME
void MXDateTime::timeAreaIndexChanged(int index)
{
if (index < 0 || index >= comboTimeArea->count()) {
return;
}
const QByteArray &area = comboTimeArea->itemData(index).toByteArray();
comboTimeZone->clear();
for (const QByteArray &zone : std::as_const(zones)) {
if (zone.startsWith(area)) {
QString text(QString(zone).section('/', 1));
text.replace('_', ' ');
comboTimeZone->addItem(text, QVariant(zone));
}
}
comboTimeZone->model()->sort(0);
}
void MXDateTime::timeZoneIndexChanged(int index)
{
if (index < 0 || index >= comboTimeZone->count()) {
return;
}
// Calculate and store the difference between current and newly selected time zones.
const QDateTime ¤t = QDateTime::currentDateTime();
zoneDelta = QTimeZone(comboTimeZone->itemData(index).toByteArray()).offsetFromUtc(current)
- QTimeZone::systemTimeZone().offsetFromUtc(current); // Delta = new - old
// Check IANA-zone id differ
const QByteArray ¤tTimeZone = QTimeZone::systemTimeZoneId();
const QByteArray &selectedTimeZone = QTimeZone(comboTimeZone->itemData(index).toByteArray()).id();
zoneIdChanged = (currentTimeZone != selectedTimeZone);
// Make the change immediately visible
update();
}
void MXDateTime::calendarSelectionChanged()
{
dateDelta = static_cast<int>(timeEdit->date().daysTo(calendar->selectedDate()));
}
void MXDateTime::timeEditDateTimeChanged(const QDateTime &dateTime)
{
clock->setTime(dateTime.time());
if (!updating) {
timeDelta = QDateTime::currentDateTime().secsTo(dateTime) - zoneDelta;
if (abs(dateDelta * 86400 + timeDelta) == 316800) {
setWindowTitle(u"88 MILES PER HOUR"_s);
}
}
}
void MXDateTime::update()
{
updating = true;
timeEdit->updateDateTime(QDateTime::currentDateTime().addSecs(timeDelta + zoneDelta));
updater.setInterval(1000 - QTime::currentTime().msec());
if (timeEdit->date().daysTo(calendar->selectedDate()) != dateDelta) {
calendar->setSelectedDate(timeEdit->date().addDays(dateDelta));
}
updating = false;
}
void MXDateTime::loadDateTime()
{
// Time zone.
comboTimeZone->blockSignals(true);
const QByteArray &zone = QTimeZone::systemTimeZoneId();
int index = comboTimeArea->findData(QString(zone).section('/', 0, 0));
comboTimeArea->setCurrentIndex(index);
qApp->processEvents();
index = comboTimeZone->findData(QVariant(zone));
comboTimeZone->setCurrentIndex(index);
zoneDelta = 0;
zoneIdChanged = false;
comboTimeZone->blockSignals(false);
}
void MXDateTime::saveDateTime(const QDateTime &driftStart)
{
// Stop display updates while setting the system clock.
if (zoneDelta || dateDelta || timeDelta || zoneIdChanged) {
updater.stop();
}
// Set the time zone (if changed) before setting the time.
if (zoneDelta || zoneIdChanged) {
const QString newzone(comboTimeZone->currentData().toByteArray());
if (sysInit == SystemD) {
executeAsRoot(u"timedatectl"_s, {u"set-timezone"_s, newzone});
} else {
executeAsRoot(u"ln"_s, {u"-nfs"_s, "/usr/share/zoneinfo/"_L1 + newzone, u"/etc/localtime"_s});
}
shell("echo "_L1 + newzone + " >/etc/timezone"_L1, nullptr, true);
zoneDelta = 0;
zoneIdChanged = false;
}
// Set the date and time if their controls have been altered.
if (dateDelta || timeDelta) {
static const QString dtFormat(u"yyyy-MM-ddTHH:mm:ss.zzz"_s);
QDateTime newTime(calendar->selectedDate(), timeEdit->time());
updater.stop();
QString param;
if (timeDelta) {
const qint64 drift = driftStart.msecsTo(QDateTime::currentDateTimeUtc());
param = newTime.addMSecs(drift).toString(dtFormat);
} else {
newTime.setTime(QTime::currentTime());
param = newTime.toString(dtFormat);
}
if (sysInit != SystemD) {
executeAsRoot(u"date"_s, {u"-s"_s, param});
} else {
executeAsRoot(u"timedatectl"_s, {u"set-time"_s, param});
}
dateDelta = 0;
timeDelta = 0;
}
// Kick the display timer back in action.
if (!updater.isActive()) {
updater.start(0);
}
}
// HARDWARE CLOCK
void MXDateTime::readHardwareClock()
{
setClockLock(true);
const QString btext = pushReadHardware->text();
pushReadHardware->setText(tr("Reading..."));
QByteArray rtcout;
// For systemd, use timedatectl to check RTC setting consistently
if (sysInit == SystemD) {
QByteArray timedatectl_out;
execute(u"timedatectl"_s, {u"show"_s, u"--property=LocalRTC"_s}, &timedatectl_out);
// LocalRTC=no means UTC, LocalRTC=yes means local time
isHardwareUTC = timedatectl_out.contains("LocalRTC=no");
// Still show hwclock output for user reference
executeAsRoot(u"hwclock"_s, {u"--verbose"_s}, &rtcout);
} else {
// For non-systemd systems, use hwclock output
executeAsRoot(u"hwclock"_s, {u"--verbose"_s}, &rtcout);
isHardwareUTC = rtcout.contains("\nHardware clock is on UTC time\n");
}
if (isHardwareUTC) {
radioHardwareUTC->setChecked(true);
} else {
radioHardwareLocal->setChecked(true);
}
textHardwareClock->setPlainText(QString(rtcout.trimmed()));
pushReadHardware->setText(btext);
setClockLock(false);
}
void MXDateTime::hardwareAdjustClicked()
{
setClockLock(true);
const QString btext = pushHardwareAdjust->text();
pushHardwareAdjust->setText(tr("Adjusting..."));
QByteArray rtcout;
executeAsRoot(u"hwclock"_s, {u"--adjust"_s}, &rtcout);
textHardwareClock->setPlainText(QString(rtcout.trimmed()));
pushHardwareAdjust->setText(btext);
setClockLock(false);
}
void MXDateTime::systemToHardwareClicked()
{
setClockLock(true);
QStringList params("--systohc");
if (checkDriftUpdate->isChecked()) {
params.append(u"--update-drift"_s);
}
transferTime(params, tr("System Clock"), tr("Hardware Clock"));
checkDriftUpdate->setCheckState(Qt::Unchecked);
setClockLock(false);
}
void MXDateTime::hardwareToSystemClicked()
{
setClockLock(true);
transferTime({"--hctosys"}, tr("Hardware Clock"), tr("System Clock"));
setClockLock(false);
}
void MXDateTime::transferTime(const QStringList ¶ms, const QString &from, const QString &to)
{
if (executeAsRoot(u"hwclock"_s, params)) {
const QString &msg = tr("The %1 time was transferred to the %2.");
QMessageBox::information(this, windowTitle(), msg.arg(from, to));
} else {
const QString &msg = tr("The %1 time could not be transferred to the %2.");
QMessageBox::warning(this, windowTitle(), msg.arg(from, to));
}
}
void MXDateTime::saveHardwareClock()
{
const bool rtcUTC = radioHardwareUTC->isChecked();
if (rtcUTC != isHardwareUTC) {
if (sysInit == SystemD) {
executeAsRoot(u"timedatectl"_s, {u"set-local-rtc"_s, rtcUTC ? u"0"_s : u"1"_s});
} else {
if (sysInit == OpenRC && QFile::exists(u"/etc/conf.d/hwclock"_s)) {
executeAsRoot(u"sed"_s, {u"-i"_s,
rtcUTC ? u"(s/clock=.*/clock=\"UTC\"/)"_s : u"(s/clock=.*/clock=\"local\"/)"_s,
u"/etc/conf.d/hwclock"_s});
}
executeAsRoot(u"hwclock"_s, {u"--systohc"_s, rtcUTC ? u"--utc"_s : u"--localtime"_s});
}
}
}
// NETWORK TIME
void MXDateTime::syncNowClicked()
{
if (!validateServerList()) {
return;
}
setClockLock(true);
saveNetworkTime();
QByteArray output;
bool rexit = false;
if (enabledNTP) {
// All commands can be passed via stdin, but chronyc may return 0 even if one command fails.
rexit = executeAsRoot(u"chronyc"_s, {u"burst 4/4"_s}, &output);
if (rexit) {
rexit = execute(u"chronyc"_s, {u"waitsync 10"_s}, &output);
}
if (rexit) {
rexit = executeAsRoot(u"chronyc"_s, {u"makestep"_s}, &output);
}
} else {
rexit = executeAsRoot(u"chronyd"_s, {u"-q"_s}, nullptr, &output);
}
setClockLock(false);
dateDelta = 0;
timeDelta = 0;
updater.setInterval(0);
QMessageBox msgbox(this);
if (rexit) {
msgbox.setIcon(QMessageBox::Information);
msgbox.setText(tr("The system clock was updated successfully."));
} else {
msgbox.setIcon(QMessageBox::Critical);
msgbox.setText(tr("The system clock could not be updated."));
}
msgbox.setDetailedText(output.trimmed());
msgbox.exec();
}
void MXDateTime::serversItemSelectionChanged()
{
const QList<QTableWidgetSelectionRange> &ranges = tableServers->selectedRanges();
bool remove = false;
bool up = false;
bool down = false;
if (ranges.count() == 1) {
const QTableWidgetSelectionRange &range = ranges.at(0);
remove = true;
if (range.topRow() > 0) {
up = true;
}
if (range.bottomRow() < (tableServers->rowCount() - 1)) {
down = true;
}
}
pushServerRemove->setEnabled(remove);
pushServerMoveUp->setEnabled(up);
pushServerMoveDown->setEnabled(down);
}
void MXDateTime::serverAddClicked()
{
QTableWidgetItem *item = addServerRow(true, u"server"_s, QString(), QString());
tableServers->setCurrentItem(item);
tableServers->editItem(item);
}
void MXDateTime::serverRemoveClicked()
{
const QList<QTableWidgetSelectionRange> &ranges = tableServers->selectedRanges();
for (int ixi = ranges.count() - 1; ixi >= 0; --ixi) {
const int top = ranges.at(ixi).topRow();
for (int row = ranges.at(ixi).bottomRow(); row >= top; --row) {
tableServers->removeRow(row);
}
}
changedServers = true;
}
QTableWidgetItem *MXDateTime::addServerRow(bool enabled, const QString &type, const QString &address,
const QString &options)
{
auto *itemComboType = new QComboBox(tableServers);
auto *item = new QTableWidgetItem(address);
auto *itemOptions = new QTableWidgetItem(options);
itemComboType->addItem(u"Pool"_s, QVariant("pool"));
itemComboType->addItem(u"Server"_s, QVariant("server"));
itemComboType->addItem(u"Peer"_s, QVariant("peer"));
itemComboType->setCurrentIndex(itemComboType->findData(QVariant(type)));
connect(itemComboType, &QComboBox::currentTextChanged, this, &MXDateTime::serverRowChanged);
item->setFlags(item->flags() | Qt::ItemIsEditable | Qt::ItemIsUserCheckable);
item->setCheckState(enabled ? Qt::Checked : Qt::Unchecked);
const int newRow = tableServers->rowCount();
tableServers->insertRow(newRow);
tableServers->setCellWidget(newRow, 0, itemComboType);
tableServers->setItem(newRow, 1, item);
tableServers->setItem(newRow, 2, itemOptions);
return item;
}
void MXDateTime::moveServerRow(int movement)
{
const QList<QTableWidgetSelectionRange> &ranges = tableServers->selectedRanges();
if (ranges.count() == 1) {
const QTableWidgetSelectionRange &range = ranges.at(0);
int end;
int row;
if (movement < 0) {
row = range.topRow();
end = range.bottomRow();
} else {
row = range.bottomRow();
end = range.topRow();
}
row += movement;
// Save the original row contents.
int targetType = qobject_cast<QComboBox *>(tableServers->cellWidget(row, 0))->currentIndex();
QTableWidgetItem *targetItemAddress = tableServers->takeItem(row, 1);
QTableWidgetItem *targetItemOptions = tableServers->takeItem(row, 2);
// Update the list selection.
const QTableWidgetSelectionRange targetRange(row, range.leftColumn(), end + movement, range.rightColumn());
tableServers->setCurrentItem(nullptr);
tableServers->setRangeSelected(targetRange, true);
// Move items one by one.
do {
row -= movement;
int type = qobject_cast<QComboBox *>(tableServers->cellWidget(row, 0))->currentIndex();
QTableWidgetItem *itemAddress = tableServers->takeItem(row, 1);
QTableWidgetItem *itemOptions = tableServers->takeItem(row, 2);
const int step = row + movement;
qobject_cast<QComboBox *>(tableServers->cellWidget(step, 0))->setCurrentIndex(type);
tableServers->setItem(step, 1, itemAddress);
tableServers->setItem(step, 2, itemOptions);
} while (row != end);
// Move the target where the range originally finished.
qobject_cast<QComboBox *>(tableServers->cellWidget(end, 0))->setCurrentIndex(targetType);
tableServers->setItem(end, 1, targetItemAddress);
tableServers->setItem(end, 2, targetItemOptions);
}
}
bool MXDateTime::validateServerList()
{
bool allValid = true;
const int serverCount = tableServers->rowCount();
for (int ixi = 0; ixi < serverCount; ++ixi) {
QTableWidgetItem *item = tableServers->item(ixi, 1);
const QString &address = item->text().trimmed();
if (address.isEmpty()) {
allValid = false;
}
}
const char *msg = nullptr;
if (serverCount <= 0) {
msg = QT_TR_NOOP("There are no NTP servers on the list.");
} else if (!allValid) {
msg = QT_TR_NOOP("There are invalid entries on the NTP server list.");
}
if (msg) {
QMessageBox::critical(this, windowTitle(), tr(msg));
return false;
}
return true;
}
QString MXDateTime::systemdChronyUnit()
{
const QStringList candidates {u"chronyd.service"_s, u"chrony.service"_s};
for (const QString &unit : candidates) {
QByteArray output;
execute(u"systemctl"_s, {u"show"_s, u"-p"_s, u"LoadState"_s, u"--value"_s, unit}, &output, nullptr);
if (QString::fromUtf8(output).trimmed() == u"loaded"_s) {
return unit;
}
}
return {};
}
QString MXDateTime::chronyConfigFile()
{
if (QFile::exists(u"/etc/chrony/chrony.conf"_s)) {
return u"/etc/chrony/chrony.conf"_s;
}
if (QFile::exists(u"/etc/chrony.conf"_s)) {
return u"/etc/chrony.conf"_s;
}
return u"/etc/chrony/chrony.conf"_s;
}
QString MXDateTime::chronySourcesFile()
{
const QString configFile = chronyConfigFile();
QFile file(configFile);
if (file.open(QFile::ReadOnly | QFile::Text)) {
while (!file.atEnd()) {
QString line = QString::fromUtf8(file.readLine()).trimmed();
line = line.section('#', 0, 0).trimmed();
if (line.startsWith(u"sourcedir "_s)) {
const QStringList parts = line.split(' ', Qt::SkipEmptyParts);
if (parts.size() >= 2) {
const QString dirPath = parts.at(1);
return QDir(dirPath).filePath(u"mx-datetime.sources"_s);
}
}
}
}
if (QFileInfo(u"/etc/chrony/sources.d"_s).isDir()) {
return u"/etc/chrony/sources.d/mx-datetime.sources"_s;
}
if (QFileInfo(u"/etc/chrony.d"_s).isDir()) {
return u"/etc/chrony.d/mx-datetime.sources"_s;
}
return u"/etc/chrony/sources.d/mx-datetime.sources"_s;
}
void MXDateTime::loadNetworkTime()
{
while (tableServers->rowCount() > 0) {
tableServers->removeRow(0);
}
const QString sourcesFile = chronySourcesFile();
const QString configFile = chronyConfigFile();
loadSources(sourcesFile);
const bool move = loadSources(configFile);
// Stray change signals may have caused changedServers to be set.
QApplication::processEvents();
changedServers = move;
if (sysInit != SystemD) {
enabledNTP = shell(u"ls /etc/rc*.d | grep chrony | grep '^S'"_s);
} else {
const QString unit = systemdChronyUnit();
if (unit.isEmpty()) {
enabledNTP = false;
} else {
QByteArray output;
execute(u"systemctl"_s, {u"show"_s, u"-p"_s, u"UnitFileState"_s, u"--value"_s, unit}, &output, nullptr);
const QString state = QString::fromUtf8(output).trimmed();
enabledNTP = (state == u"enabled"_s || state == u"enabled-runtime"_s);
}
}
checkAutoSync->setChecked(enabledNTP);
}
void MXDateTime::saveNetworkTime()
{
// Enable/disable NTP
const bool ntp = checkAutoSync->isChecked();
if (ntp != enabledNTP) {
const QString enable_disable(ntp ? u"enable"_s : u"disable"_s);
const QString start_stop(ntp ? u"start"_s : u"stop"_s);
if (sysInit == SystemD) {
const QString unit = systemdChronyUnit();
if (!unit.isEmpty()) {
executeAsRoot(u"systemctl"_s, {enable_disable, unit});
executeAsRoot(u"systemctl"_s, {start_stop, unit});
}
} else if (sysInit == OpenRC) {
if (QFile::exists(u"/etc/init.d/chronyd"_s)) {
executeAsRoot(u"rc-update"_s, {ntp ? u"add"_s : u"del"_s, u"chronyd"_s});
}
} else {
executeAsRoot(u"update-rc.d"_s, {u"chrony"_s, enable_disable});
executeAsRoot(u"service"_s, {u"chrony"_s, start_stop});
}
enabledNTP = ntp;
}
// Generate chrony sources file.
if (changedServers) {
const QString sourcesFile = chronySourcesFile();
const QString configFile = chronyConfigFile();
QTemporaryFile file;
if (file.open()) {
file.write("# Generated by MX Date & Time - ");
file.write(QDateTime::currentDateTime().toString(u"yyyy-MM-dd H:mm:ss t"_s).toUtf8());
file.write("\n");
for (int ixi = 0; ixi < tableServers->rowCount(); ++ixi) {
auto *comboType = qobject_cast<QComboBox *>(tableServers->cellWidget(ixi, 0));
QTableWidgetItem *item = tableServers->item(ixi, 1);
if (item->checkState() != Qt::Checked) {
file.write("#");
}
file.write(comboType->currentData().toByteArray());
file.write(" ");
file.write(item->text().trimmed().toUtf8());
const QString &options = tableServers->item(ixi, 2)->text().simplified();
if (!options.isEmpty()) {
file.write(" ");
file.write(options.toUtf8());
}
file.write("\n");
}
file.close();
const QDir sourcesDir = QFileInfo(sourcesFile).dir();
if (!sourcesDir.exists()) {
executeAsRoot(u"mkdir"_s, {u"-p"_s, sourcesDir.absolutePath()});
}
executeAsRoot(u"mv"_s, {file.fileName(), sourcesFile});
executeAsRoot(u"chown"_s, {u"root:"_s, sourcesFile});
executeAsRoot(u"chmod"_s, {u"+r"_s, sourcesFile});
}
if (ntp) {
if (!clearSources(configFile)) {
executeAsRoot(u"chronyc"_s, {u"reload"_s, u"sources"_s});
} else {
if (sysInit == SystemD) {
const QString unit = systemdChronyUnit();
if (!unit.isEmpty()) {
executeAsRoot(u"systemctl"_s, {u"restart"_s, unit});
}
} else {
executeAsRoot(u"service"_s, {u"chrony"_s, u"restart"_s});
}
}
}
}
}
bool MXDateTime::loadSources(const QString &filename)
{
QFile file(filename);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
return false;
}
const auto isDuplicate = [this](const QString &type, const QString &address, const QString &options) {
const int serverCount = tableServers->rowCount();
for (int ixi = 0; ixi < serverCount; ++ixi) {
auto *comboType = qobject_cast<QComboBox *>(tableServers->cellWidget(ixi, 0));
if (!comboType) {
continue;
}
const QString rowType = comboType->currentData().toString();
const QString rowAddress = tableServers->item(ixi, 1)->text().trimmed();
const QString rowOptions = tableServers->item(ixi, 2)->text().simplified();
if (rowType == type && rowAddress == address && rowOptions == options) {
return true;
}
}
return false;
};
bool hassrc = false;
while (!file.atEnd()) {
const QByteArray &bline = file.readLine();
const QString line(bline.simplified());
static const QRegularExpression tregex(u"^#?(pool|server|peer)\\s"_s);
if (line.contains(tregex)) {
QStringList args = line.split(' ', Qt::SkipEmptyParts);
QString curarg = args.at(0);
bool enabled = true;
if (curarg.startsWith('#')) {
enabled = false;
curarg = curarg.remove(0, 1);
}
QString options;
for (int ixi = 2; ixi < args.count(); ++ixi) {
options.append(' ');
options.append(args.at(ixi));
}
const QString address = args.at(1);
const QString trimmedOptions = options.trimmed();
if (!isDuplicate(curarg, address, trimmedOptions)) {
addServerRow(enabled, curarg, address, trimmedOptions);
}
hassrc = true;
}
}
return hassrc;
}
// Remove all source NTP lines from a file. Make a backup before writing.
// Return the number of sources removed on success, -1 on failure.
bool MXDateTime::clearSources(const QString &filename)
{
bool changed = false;
QFile file(filename);
QByteArray confdata;
// Read config and skip sources.
if (!file.open(QFile::ReadOnly | QFile::Text)) {
return false;
}
while (!file.atEnd()) {
const QByteArray &bline = file.readLine();
static const QRegularExpression tregex(u"^\\s*(pool|server|peer)\\s"_s);
if (QString::fromUtf8(bline).contains(tregex)) {
confdata.append("##");
changed = true;
}
confdata.append(bline);
}
file.close();
// Write cleared config.
if (changed) {
QTemporaryFile tmpFile;
if (!tmpFile.open()) {
return false;
}
tmpFile.write(confdata);
tmpFile.close();
executeAsRoot(u"mv"_s, {tmpFile.fileName(), file.fileName()});
executeAsRoot(u"chown"_s, {u"root:"_s, file.fileName()});
executeAsRoot(u"chmod"_s, {u"+r"_s, file.fileName()});
}
return changed;
}
void MXDateTime::serverRowChanged()
{
changedServers = true;
}
// ACTION BUTTONS
void MXDateTime::applyClicked()
{
// Compensation for the execution time of this section.
QDateTime driftStart = QDateTime::currentDateTimeUtc();
setClockLock(true);
// Validate all data before trying to save settings.
if ((loadedTabs & 4) && !validateServerList()) {
setClockLock(false);
return;
}
// Save the settings.
saveDateTime(driftStart);
if (loadedTabs & 2) {
saveHardwareClock();
}
if (loadedTabs & 4) {
saveNetworkTime();
}
// Refresh the UI (especially the current tab) with newly set values.
loadedTabs = 0;
setClockLock(false);
}
// MX Standard User Interface
void MXDateTime::aboutClicked()
{
displayAboutMsgBox(tr("About MX Date & Time"),
"<p align=\"center\"><b><h2>"_L1 + tr("MX Date & Time") + "</h2></b></p><p align=\"center\">"_L1
+ tr("Version: ") + qApp->applicationVersion() + "</p><p align=\"center\"><h3>"_L1
+ tr("GUI program for setting the time and date in MX Linux")
+ "</h3></p><p align=\"center\"><a href=\"http://mxlinux.org\">http://mxlinux.org</a><br/>"_L1
"</p><p align=\"center\">"_L1
+ tr("Copyright (c) MX Linux") + "<br /><br /></p>"_L1,
u"/usr/share/doc/mx-datetime/license.html"_s, tr("%1 License").arg(this->windowTitle()));
}
void MXDateTime::helpClicked()
{
displayDoc(u"/usr/share/doc/mx-datetime/mx-datetime.html"_s, tr("MX Date & Time Help"));
}
// SUBCLASSING FOR QTimeEdit THAT FIXES CURSOR AND SELECTION JUMPING EVERY SECOND
void MTimeEdit::updateDateTime(const QDateTime &dateTime)
{
QLineEdit *ledit = lineEdit();
// Original cursor position and selections
int select = ledit->selectionStart();
int cursor = ledit->cursorPosition();
// Calculation for backward selections.
if (select >= 0 && select >= cursor) {
const int cslength = ledit->selectedText().length();
if (cslength > 0) {
select = cursor + cslength;
}
}
// Set the date/time as normal.
setDateTime(dateTime);
// Restore cursor and selection.
if (select >= 0) {
ledit->setSelection(select, cursor - select);
} else {
ledit->setCursorPosition(cursor);
}
}