-
Notifications
You must be signed in to change notification settings - Fork 39
/
creator.cpp
1520 lines (1240 loc) · 48.3 KB
/
creator.cpp
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
////////////////////////////////////////////////////////////////////////////////
// This file is part of LibreELEC - http://www.libreelec.tv
// Copyright (C) 2013-2015 RasPlex project
// Copyright (C) 2016-Present Team LibreELEC
//
// LibreELEC 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 2 of the License, or
// (at your option) any later version.
//
// LibreELEC 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 LibreELEC. If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#include "creator.h"
#include "ui_creator.h"
#include <QRegularExpression>
#include <QDebug>
#include <QString>
#include <QFile>
#include <QFileDialog>
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QMessageBox>
#include <QThread>
#include <QTimer>
#include <QPlainTextEdit>
#include <QStyleFactory>
#include <QDesktopServices>
#include <QMimeData>
#include <QProcess>
#include <QVersionNumber>
#include <QSignalBlocker>
#include <QApplication>
#if defined(Q_OS_WIN)
#include "diskwriter_windows.h"
#include "deviceenumerator_windows.h"
#elif defined(Q_OS_LINUX)
#include <unistd.h>
#include "diskwriter_udisks2.h"
#include "deviceenumerator_udisks2.h"
#elif defined(Q_OS_UNIX)
#include <unistd.h>
#include "diskwriter_unix.h"
#include "deviceenumerator_unix.h"
#endif
// force update notification dialog
//#define FORCE_UPDATE_NOTIFICATION "1.3"
const QString Creator::releasesUrl = "http://releases.libreelec.tv/";
const QString Creator::versionUrl = releasesUrl + "creator_version";
const QString Creator::helpUrl = "https://wiki.libreelec.tv/installation/create-media";
const int Creator::timerValue = 1500; // msec
Creator::Creator(Privileges &privilegesArg, QWidget *parent) :
QDialog(parent),
ui(new Ui::Creator),
manager(new DownloadManager(this)),
state(STATE_IDLE),
imageHash(QCryptographicHash::Sha256),
settings(QSettings::IniFormat, QSettings::UserScope, "LibreELEC", "LibreELEC.USB-SD.Creator"),
privileges(privilegesArg),
deviceEjected("")
{
restoreGeometry(settings.value("window/geometry").toByteArray());
ui->setupUi(this);
#ifdef Q_OS_MACOS
auto fontAbout = ui->labelAbout->font();
fontAbout.setPointSize(fontAbout.pointSize() + 2);
ui->labelAbout->setFont(fontAbout);
#endif
#if defined(Q_OS_WIN)
diskWriter = new DiskWriter_windows();
devEnumerator = new DeviceEnumerator_windows();
#elif defined(Q_OS_LINUX)
diskWriter = new DiskWriter_udisks2();
devEnumerator = new DeviceEnumerator_udisks2();
#elif defined(Q_OS_UNIX)
diskWriter = new DiskWriter_unix();
devEnumerator = new DeviceEnumerator_unix();
#endif
diskWriterThread = new QThread(this);
diskWriter->moveToThread(diskWriterThread);
// must set before signals
if (settings.value("preferred/imageshowall") == Qt::Checked)
ui->imagesShowAll->setChecked(true); // default unchecked
// hide ? button
this->setWindowFlags(this->windowFlags() & ~(Qt::WindowContextHelpButtonHint));
// add minimize button on Windows
this->setWindowFlags(windowFlags() | Qt::WindowMinimizeButtonHint);
connect(diskWriterThread, SIGNAL(finished()),
diskWriter, SLOT(deleteLater()));
connect(this, SIGNAL(proceedToWriteImageToDevice(QString,QString,QString)),
diskWriter, SLOT(writeImageToRemovableDevice(QString,QString,QString)));
connect(diskWriter, SIGNAL(bytesWritten(int)),this, SLOT(handleWriteProgress(int)));
connect(diskWriter, SIGNAL(syncing()), this, SLOT(writingSyncing()));
connect(diskWriter, SIGNAL(finished()), this, SLOT(writingFinished()));
connect(diskWriter, SIGNAL(error(QString)), this, SLOT(writingError(QString)));
diskWriterThread->start();
connect(ui->refreshRemovablesButton,SIGNAL(clicked()),
this,SLOT(refreshRemovablesList()));
connect(manager, SIGNAL(downloadProgress(qint64, qint64)),
this, SLOT(handleDownloadProgress(qint64, qint64)));
connect(manager, SIGNAL(downloadComplete(QByteArray)),
this, SLOT(handleFinishedDownload(QByteArray)));
connect(manager, SIGNAL(partialData(QByteArray,qlonglong)),
this, SLOT(handlePartialData(QByteArray,qlonglong)));
connect(manager, SIGNAL(downloadError(QString)),
this, SLOT(handleDownloadError(QString)));
connect(ui->downloadButton, SIGNAL(clicked()),
this, SLOT(downloadButtonClicked()));
connect(ui->loadButton, SIGNAL(clicked()),
this, SLOT(getImageFileNameFromUser()));
connect(ui->writeFlashButton, SIGNAL(clicked()),
this, SLOT(writeFlashButtonClicked()));
connect(ui->imagesShowAll, SIGNAL(stateChanged(int)),
this, SLOT(projectImagesShowAllChanged(int)));
connect(ui->projectSelectBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(setProjectImages()));
connect(ui->imageSelectBox, SIGNAL(currentTextChanged(QString)),
this, SLOT(projectImagesChanged(QString)));
connect(ui->removableDevicesComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(savePreferredRemovableDevice(int)));
connect(ui->ejectUSB, SIGNAL(clicked()), this, SLOT(ejectUSB()));
connect(ui->loadUSB, SIGNAL(clicked()), this, SLOT(loadUSB()));
connect(ui->removeUSB, SIGNAL(clicked()), this, SLOT(removeUSB()));
connect(ui->helpButton, SIGNAL(clicked()), this, SLOT(showHelp()));
connect(ui->showAboutButton, SIGNAL(clicked()), this, SLOT(showAbout()));
connect(ui->closeAboutButton, SIGNAL(clicked()), this, SLOT(closeAbout()));
connect(ui->closeAppButton, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->langButton,SIGNAL(clicked()), this, SLOT(languageChange()));
refreshRemovablesList();
// create a timer that refreshes the device list every 1.5 second
// if there is any change then list is changed and current device removed
timerId = startTimer(timerValue);
// set Fusion style
QApplication::setStyle(QStyleFactory::create("Fusion"));
// and apply some changes to styles
#ifdef Q_OS_MACOS
QFile fileStyle(":/qss/stylesheet_osx.qss");
#else
QFile fileStyle(":/qss/stylesheet.qss");
#endif
if (fileStyle.open(QIODevice::ReadOnly | QIODevice::Text)) {
this->setStyleSheet(QLatin1String(fileStyle.readAll()));
this->ensurePolished();
fileStyle.close();
}
setImageFileName("");
ui->writeFlashButton->setEnabled(false);
showLoadEject = false; // disabled by default
#ifdef Q_OS_WIN
// this option is only for me on Windows
// disabled on Linux and OS X
showLoadEject = settings.value("preferred/showloadeject", false).toBool();
settings.setValue("preferred/showloadeject", showLoadEject);
if (showLoadEject == false)
#endif
{
ui->labelEjectLoad->setVisible(false);
ui->ejectUSB->setEnabled(false);
ui->ejectUSB->setVisible(false);
ui->loadUSB->setEnabled(false);
ui->loadUSB->setVisible(false);
ui->removeUSB->setEnabled(false);
ui->removeUSB->setVisible(false);
}
setAcceptDrops(true); // allow droping files on a window
// singleShot fixes broken focus behavior if the message is shown on macOS
QTimer::singleShot(0, this, &Creator::showRootMessageBox);
// call web browser through our wrapper for Linux
QDesktopServices::setUrlHandler("http", this, "httpsUrlHandler");
QDesktopServices::setUrlHandler("https", this, "httpsUrlHandler");
translator = new Translator(this, &settings); // pass parent
translator->fillLanguages(ui->menuLanguage, ui->langButton);
retranslateUi(); // retranslate dynamic texts
downloadVersionCheck();
}
bool Creator::showRootMessageBox()
{
#ifdef Q_OS_MACOS
if (getuid() == 0) // root == 0, real user != 0
return false;
QMessageBox msgBox(this);
msgBox.setText(tr("Root privileges required to write image.\nRun application with sudo."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
return true;
#else
return false;
#endif
}
Creator::~Creator()
{
if (imageFile.isOpen() && state == STATE_DOWNLOADING_IMAGE) {
qDebug() << "Removing file" << imageFile.fileName();
imageFile.remove();
} else if (state == STATE_WRITING_IMAGE) {
privileges.SetUser(); // back to user
}
delete ui;
diskWriter->cancelWrite();
diskWriterThread->quit();
diskWriterThread->wait();
delete diskWriterThread;
delete devEnumerator;
delete parserData;
}
void Creator::httpsUrlHandler(const QUrl &url)
{
// on windows open web browser directly
// for linux use a wrapper to set uid/gid correctly
#if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
QDesktopServices::openUrl(url);
#else
qDebug() << "httpsUrlHandler called" << url;
pid_t pid = fork();
if (pid == 0) {
// child process, set both real and effective uid/gid
// because GTK+ applications check this and doesn't run
setenv("DBUS_SESSION_BUS_ADDRESS", privileges.GetUserEnvDbusSession().toLatin1().data(), 1);
setenv("LOGNAME", privileges.GetUserEnvLogname().toLatin1().data(), 1);
privileges.SetRoot(); // no need to switch back
privileges.SetRealUser(); // no need to switch back
QDesktopServices::openUrl(QUrl(url));
_exit(0);
}
#if 0
QString program = QCoreApplication::applicationFilePath();
QStringList arguments = QStringList("--browser");
// root is needed to start the process which
// will be dropped back to user (both real and effective uid/gid)
privileges.SetRoot();
setenv("DBUS_SESSION_BUS_ADDRESS", privileges.GetUserEnvDbusSession().toLatin1().data(), 1);
setenv("LOGNAME", privileges.GetUserEnvLogname().toLatin1().data(), 1);
setenv("LE_URL_ADDRESS", url.toString().toLatin1().data(), 1);
QProcess myProcess;
myProcess.startDetached(program, arguments);
myProcess.waitForStarted();
myProcess.waitForFinished();
privileges.SetUser(); // back to user
#endif
qDebug() << "httpsUrlHandler done";
#endif
}
void Creator::setArgFile(QString file)
{
if (file.isEmpty())
return;
QFileInfo checkFile(file);
if (!checkFile.exists() || !checkFile.isFile())
return;
QFileInfo infoFile(file);
file = infoFile.absoluteFilePath();
setImageFileName(file);
}
void Creator::retranslateUi()
{
// retranslate dynamic texts
ui->labelVersion->setText(tr("Version: %1\nBuild date: %2").arg(QLatin1String{BUILD_VERSION}, QLatin1String{BUILD_DATE}));
ui->labelAbout->setText(QString("<html><head/><body><p align=\"center\"><span style=\" font-size:16pt; font-weight:600;\"><h2>© LibreELEC %8</h2></span></p><p align=\"center\">%1<br/>%2</p><p align=\"center\">%3<br/><a href=\"https://github.com/LibreELEC/usb-sd-creator\"><span style=\" text-decoration: underline; color:#0000ff;\">https://github.com/LibreELEC/usb-sd-creator</span></a><br/></p><p align=\"center\">%4<br/>%5</p><p align=\"center\">%6<br/>%7 <br/><br/><a href=\"https://opencollective.com/libreelec/donate\"><img src=\":/icons/opencollective.png\"></a></p></body></html>") \
.arg(tr("This software was created with love and released"))
.arg(tr("under GPLv2, using earlier work from RasPlex."))
.arg(tr("For license, credits and history, please read:"))
.arg(tr("If you enjoy using LibreELEC please consider a"))
.arg(tr("donation to support the project."))
.arg(tr("Click the logo below to donate"))
.arg(tr("using OpenCollective"))
.arg(QLatin1String{COPYRIGHT_YEARS})
);
// orientation of the widget is reversed
if (QApplication::isLeftToRight())
ui->imagesShowAll->setLayoutDirection(Qt::RightToLeft);
else
ui->imagesShowAll->setLayoutDirection(Qt::LeftToRight);
}
void Creator::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape)
return; // ignore Esc key for close
}
void Creator::closeEvent(QCloseEvent* event)
{
Q_UNUSED(event);
settings.setValue("window/geometry", saveGeometry());
}
void Creator::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void Creator::dropEvent(QDropEvent *event)
{
foreach (const QUrl &url, event->mimeData()->urls()) {
QString file = url.toLocalFile();
QFileInfo infoFile(file);
file = infoFile.absoluteFilePath();
setImageFileName(file);
reset();
// hide selected project and image name
ui->projectSelectBox->blockSignals(true);
ui->imageSelectBox->blockSignals(true);
ui->projectSelectBox->setCurrentIndex(-1);
ui->imageSelectBox->setCurrentIndex(-1);
ui->projectSelectBox->blockSignals(false);
ui->imageSelectBox->blockSignals(false);
// and disable download button
ui->downloadButton->setEnabled(false);
break; // only first file
}
}
void Creator::timerEvent(QTimerEvent *event)
{
Q_UNUSED(event);
refreshRemovablesList();
}
void Creator::changeEvent(QEvent *e) {
switch (e->type()) {
case QEvent::ActivationChange:
if (this->isActiveWindow()) {
// got focus
if (timerId == 0)
timerId = startTimer(timerValue);
} else {
// lost focus
if (timerId > 0) {
killTimer(timerId);
timerId = 0;
}
}
break;
case QEvent::LanguageChange:
ui->retranslateUi(this); // retranslate texts from .ui file
retranslateUi(); // retranslate dynamic texts
break;
default:
break;
}
}
void Creator::ejectUSB()
{
int idx = ui->removableDevicesComboBox->currentIndex();
deviceEjected = ui->removableDevicesComboBox->itemData(idx).toString();
if (deviceEjected.isNull())
return;
qDebug() << "ejectUSB" << deviceEjected;
int rv = devEnumerator->loadEjectDrive(deviceEjected, DeviceEnumerator::LOADEJECT_EJECT);
Q_UNUSED(rv);
}
void Creator::loadUSB()
{
if (deviceEjected.isNull())
return;
qDebug() << "loadUSB" << deviceEjected;
int rv = devEnumerator->loadEjectDrive(deviceEjected, DeviceEnumerator::LOADEJECT_LOAD);
deviceEjected = ""; // init
Q_UNUSED(rv);
}
void Creator::removeUSB()
{
int idx = ui->removableDevicesComboBox->currentIndex();
deviceEjected = ui->removableDevicesComboBox->itemData(idx).toString();
if (deviceEjected.isNull())
return;
qDebug() << "removeUSB" << deviceEjected;
int rv = devEnumerator->removeDrive(deviceEjected);
Q_UNUSED(rv);
}
void Creator::showHelp()
{
QDesktopServices::openUrl(QUrl(helpUrl));
}
void Creator::showAbout()
{
ui->stackedWidget->setCurrentIndex(STACK_WIDGET_ABOUT);
}
void Creator::closeAbout()
{
ui->stackedWidget->setCurrentIndex(STACK_WIDGET_MAIN);
}
void Creator::downloadProgressBarText(const QString &text = "")
{
ui->downloadProgressBar->setFormat(" " + text);
ui->downloadProgressBar->repaint();
ui->downloadProgressBar->update();
//qApp->processEvents(); // don't use this (signals lost and boooom)
}
void Creator::flashProgressBarText(const QString &text = "")
{
ui->flashProgressBar->setFormat(" " + text);
ui->flashProgressBar->repaint();
ui->flashProgressBar->update();
//qApp->processEvents();
}
void Creator::parseJsonAndSet(const QByteArray &data)
{
//qDebug() << "JSON data:" << data;
parserData = new JsonParser(data);
// parse local file if exist
QFile fileLocalReleases("releases-user.json");
if (fileLocalReleases.open(QIODevice::ReadOnly | QIODevice::Text)) {
parserData->addExtra(fileLocalReleases.readAll(), "User");
fileLocalReleases.close();
}
ui->projectSelectBox->clear();
QList<ProjectData> projectList = parserData->getProjectData();
for (auto& project : projectList) {
QString projectName = project.name;
QString projectId = project.id;
QString projectUrl = project.url;
QVariantMap projectData;
projectData.insert("id", projectId);
projectData.insert("url", projectUrl);
ui->projectSelectBox->insertItem(0, projectName, projectData);
ui->projectSelectBox->setItemData(0, projectId, Qt::ToolTipRole);
}
QString previouslySelectedProject;
previouslySelectedProject = settings.value("preferred/project").toString();
// RPi2/3 is default project
if (previouslySelectedProject.isEmpty())
previouslySelectedProject = "Raspberry Pi 2 and 3";
int idx = ui->projectSelectBox->findText(previouslySelectedProject,
Qt::MatchFixedString);
if (idx >= 0)
ui->projectSelectBox->setCurrentIndex(idx);
settings.setValue("preferred/project", ui->projectSelectBox->currentText());
setProjectImages();
resetProgressBars(); // it is affected with all downloads
}
void Creator::setProjectImages()
{
downloadProgressBarText();
//ui->fileNameLabel->setText("");
// last selected is preferred
settings.setValue("preferred/project", ui->projectSelectBox->currentText());
QString previouslySelectedImage;
if (ui->imageSelectBox->count() == 0)
previouslySelectedImage = settings.value("preferred/image").toString();
else
previouslySelectedImage = ui->imageSelectBox->currentText();
{
const QSignalBlocker blocker{ui->imageSelectBox};
ui->imageSelectBox->clear();
}
QList<ProjectData> projectList = parserData->getProjectData();
for (auto& project : projectList) {
QString projectName = project.name;
// show images only for selected project
if (projectName != ui->projectSelectBox->currentText())
continue;
QString lastVersionNum;
QList<QVariantMap> releases = project.images;
for (QList<QVariantMap>::const_iterator it = releases.constBegin();
it != releases.constEnd();
it++)
{
QString imageName = (*it)["name"].toString();
QString imageChecksum = (*it)["sha256"].toString();
QString imageSize = (*it)["size"].toString();
QString versionNum;
QRegularExpression versionNumRegExp = QRegularExpression("-([0-9]+\\.[0-9]+\\.[0-9]+).*\\.img\\.gz");
QRegularExpressionMatch versionNumMatch = versionNumRegExp.match(imageName);
if (versionNumMatch.hasMatch())
versionNum = versionNumMatch.captured(1);
// if we don't show all images, break after the version number changes
// note that multiple latest image numbers are possible with hardware variations
// e.g LibreELEC-A64.arm-9.95.4-orangepi-win.img.gz or LibreELEC-A64.arm-9.95.4-pine64-lts.img.g
if (!ui->imagesShowAll->isChecked() && !lastVersionNum.isEmpty() && lastVersionNum != versionNum)
break;
int size = imageSize.toInt();
if (size < 1024) {
imageSize = QString::number(size) + " B";
} else if (size < 1024*1024) {
size /= 1024;
imageSize = QString::number(size) + " kB";
} else {
size /= 1024*1024;
imageSize = QString::number(size) + " MB";
}
// LibreELEC-RPi2.arm-7.90.002.img.gz
// LibreELEC-TinkerBoard.arm-8.90.015-rk3288.img.gz
QRegularExpression regExp = QRegularExpression(".+-[0-9]+\\.(9[05])\\.[0-9]+.*\\.img\\.gz");
QRegularExpressionMatch match = regExp.match(imageName);
QStringList regExpVal = match.capturedTexts();
QString alphaBetaNumber;
alphaBetaNumber = tr("[Stable]");
if (regExpVal.count() == 2) {
if (regExpVal.at(1) == "90")
alphaBetaNumber = tr("[Alpha]");
else if (regExpVal.at(1) == "95")
alphaBetaNumber = tr("[Beta]");
}
if (! ui->imagesShowAll->isChecked()) {
// check value (number 90 or 95)
if (alphaBetaNumber != tr("[Stable]"))
continue; // skip testing images
}
checksumMap[imageName] = imageChecksum;
ui->imageSelectBox->insertItem(0, imageName + ", " + imageSize, imageName);
ui->imageSelectBox->setItemData(0, alphaBetaNumber + " " + releasesUrl + imageName, Qt::ToolTipRole);
lastVersionNum = versionNum;
}
}
int idx = ui->imageSelectBox->findText(previouslySelectedImage,
Qt::MatchFixedString);
if (idx >= 0)
ui->imageSelectBox->setCurrentIndex(idx);
savePreferredImage(ui->imageSelectBox->currentText());
reset();
downloadProgressBarText();
}
void Creator::projectImagesShowAllChanged(int state)
{
settings.setValue("preferred/imageshowall", state);
setProjectImages();
}
void Creator::projectImagesChanged(const QString& version)
{
downloadProgressBarText();
ui->fileNameLabel->setText("");
savePreferredImage(version);
// in case user file was selected then both project and image was empty
// try setting project
QString previouslySelectedProject;
previouslySelectedProject = settings.value("preferred/project").toString();
int idx = ui->projectSelectBox->findText(previouslySelectedProject,
Qt::MatchFixedString);
if (idx >= 0)
ui->projectSelectBox->setCurrentIndex(idx);
}
void Creator::reset(const QString& message)
{
bytesDownloaded = 0;
bytesLast = 0;
if (imageFile.isOpen())
imageFile.close();
ui->imagesShowAll->setEnabled(true);
ui->projectSelectBox->blockSignals(false);
ui->projectSelectBox->setEnabled(true);
ui->imageSelectBox->blockSignals(false);
ui->imageSelectBox->setEnabled(true);
ui->downloadButton->setEnabled(true);
ui->downloadButton->setText(tr("&Download"));
ui->loadButton->setEnabled(true);
ui->refreshRemovablesButton->setEnabled(true);
ui->removableDevicesComboBox->setEnabled(true);
int idx = ui->removableDevicesComboBox->currentIndex();
QString destination = ui->removableDevicesComboBox->itemData(idx).toString();
QString file = ui->fileNameLabel->text();
if (file.isFilled()) {
QFileInfo checkFile(file);
if (!checkFile.exists() || !checkFile.isFile())
file = "";
else {
QFileInfo infoFile(file);
file = infoFile.absoluteFilePath();
ui->fileNameLabel->setText(file);
setImageFileName(file);
}
}
if (destination.isNull() == false && file.isFilled())
ui->writeFlashButton->setEnabled(true);
else
ui->writeFlashButton->setEnabled(false);
ui->writeFlashButton->setText(tr("&Write"));
if (message.isNull() == false) {
if (state == STATE_DOWNLOADING_IMAGE) {
;
} else if (state == STATE_WRITING_IMAGE) {
flashProgressBarText(message);
}
}
state = STATE_IDLE;
// TBD - USB eject/load/remove
}
void Creator::resetProgressBars()
{
ui->downloadProgressBar->setValue(0);
ui->flashProgressBar->setValue(0);
downloadProgressBarText();
flashProgressBarText();
}
void Creator::savePreferredImage(const QString& version)
{
settings.setValue("preferred/image", version);
}
void Creator::savePreferredRemovableDevice(int idx)
{
if (idx < 0 )
return;
settings.setValue("preferred/removableDevice", ui->removableDevicesComboBox->itemData(idx).toString());
flashProgressBarText("");
}
void Creator::languageChange()
{
// menu has padding around
ui->menuLanguage->exec(ui->langButton->mapToGlobal(QPoint(0, 0)));
}
void Creator::disableControls(const int which)
{
ui->imagesShowAll->setEnabled(false);
ui->projectSelectBox->setEnabled(false);
ui->projectSelectBox->blockSignals(true);
ui->imageSelectBox->setEnabled(false);
ui->imageSelectBox->blockSignals(true);
ui->refreshRemovablesButton->setEnabled(false);
ui->removableDevicesComboBox->setEnabled(false);
if (which == DISABLE_CONTROL_DOWNLOAD) {
ui->writeFlashButton->setEnabled(false);
} else {
ui->downloadButton->setEnabled(false);
ui->loadButton->setEnabled(false);
}
// TBD - USB eject/load/remove
}
bool Creator::isChecksumValid(const QString checksumSha256)
{
checksum = checksumMap[selectedImage];
if (checksumSha256.isFilled() && checksumSha256 == checksum)
return true; // checksum calculated at download stage
QByteArray referenceSum, downloadSum;
QCryptographicHash c(QCryptographicHash::Sha256);
// calculate the sha256 sum of the downloaded file
imageFile.open(QFile::ReadOnly);
while (!imageFile.atEnd())
c.addData(imageFile.read(4096));
downloadSum = c.result().toHex();
imageFile.close();
qDebug() << selectedImage << checksum;
if (checksum.isEmpty() || downloadSum != checksum.toUtf8())
return false;
return true;
}
// From http://www.gamedev.net/topic/591402-gzip-uncompressed-file-size/
// Might not be portable!
unsigned int Creator::getUncompressedImageSize()
{
FILE *file;
unsigned int len;
unsigned char bufSize[4];
unsigned int fileSize;
#if defined(_WIN32)
// toStdString internally converts filename to utf8, which
// windows does not support for fileaccess
// so use unchanged 16 Bit unicode here (QChar is 16 Bit)
file = _wfopen((const wchar_t *)imageFile.fileName().utf16(), L"rb");
#else
file = fopen(imageFile.fileName().toStdString().c_str(), "rb");
#endif
if (file == NULL)
{
emit error("Couldn't open " + imageFile.fileName());
return 0;
}
if (imageFile.fileName().endsWith(".gz")) {
if (fseek(file, -4, SEEK_END) != 0)
return 0;
len = fread(&bufSize[0], sizeof(unsigned char), 4, file);
if (len != 4) {
fclose(file);
return 0;
}
fileSize = (unsigned int) ((bufSize[3] << 24) | (bufSize[2] << 16) | (bufSize[1] << 8) | bufSize[0]);
qDebug() << "Uncompressed gz file size:" << fileSize;
} else if (imageFile.fileName().endsWith(".zip")) {
// first check uncompressed size from header
if (fseek(file, 22, SEEK_SET) != 0)
return 0;
len = fread(&bufSize[0], sizeof(unsigned char), 4, file);
if (len != 4) {
fclose(file);
return 0;
}
fileSize = (unsigned int) ((bufSize[3] << 24) | (bufSize[2] << 16) | (bufSize[1] << 8) | bufSize[0]);
// check general-purpose flags
if (fseek(file, 6, SEEK_SET) != 0)
return 0;
len = fread(&bufSize[0], sizeof(unsigned char), 2, file);
if (len != 2) {
fclose(file);
return 0;
}
qDebug() << "fileSize" << fileSize << "general-purpose flag" << (bufSize[0] & 0x08);
if (fileSize == 0 && (bufSize[0] & 0x08) != 0) {
// get size from structure immediately after the
// compressed data (at the end of the file)
// get End of central directory record (EOCD)
long off;
for (off = 0;; off++) {
qDebug() << "off:" << off;
if (fseek(file, -22 - off, SEEK_END) == -1)
break; // error
len = fread(&bufSize[0], sizeof(unsigned char), 4, file);
if (len != 4) {
fclose(file);
return 0;
}
// check End of central directory signature = 0x06054b50
if (bufSize[3] == 0x06 && bufSize[2] == 0x05 && \
bufSize[1] == 0x4b && bufSize[0] == 0x50)
{
qDebug() << "found End of central directory signature = 0x06054b50";
break; // exit loop
}
} // for
off = 16 - 4; // 4 B already read
// Offset of start of central directory, relative to start of archive
if (fseek(file, off, SEEK_CUR) == -1) {
fclose(file);
return 0;
}
len = fread(&bufSize[0], sizeof(unsigned char), 4, file);
if (len != 4) {
fclose(file);
return 0;
}
// calculate offset
off = (long) ((bufSize[3] << 24) | (bufSize[2] << 16) | (bufSize[1] << 8) | bufSize[0]);
if (fseek(file, off, SEEK_SET) == -1) {
fclose(file);
return 0;
}
len = fread(&bufSize[0], sizeof(unsigned char), 4, file);
if (len != 4) {
fclose(file);
return 0;
}
// check Central directory file header signature = 0x02014b50
if (bufSize[3] == 0x02 && bufSize[2] == 0x01 && bufSize[1] == 0x4b && bufSize[0] == 0x50) {
qDebug() << "found Central directory file header signature = 0x02014b50";
off = 24 - 4; // 4 B already read
}
if (fseek(file, off, SEEK_CUR) == -1) {
fclose(file);
return 0;
}
len = fread(&bufSize[0], sizeof(unsigned char), 4, file);
if (len != 4) {
fclose(file);
return 0;
}
// Uncompressed size
fileSize = (unsigned int) ((bufSize[3] << 24) | (bufSize[2] << 16) | (bufSize[1] << 8) | bufSize[0]);
if (fileSize == 0) {
qDebug() << "fileSize unknown - set 512 MB";
fileSize = 512 * 1024 * 1024; // test
}
} // fileSize == 0
qDebug() << "Uncompressed zip file size:" << fileSize;
} else {
fseek(file, 0L, SEEK_END);
fileSize = ftell(file);
qDebug() << "Regular file size:" << fileSize;
}
fclose(file);
return fileSize;
}
void Creator::setImageFileName(QString filename)
{
if (imageFile.isOpen()) {
qDebug() << "Tried to change filename while imageFile was open!";
return;
}
imageFile.setFileName(filename);
if (filename.endsWith(".temp"))
filename = filename.left(filename.lastIndexOf("."));
ui->fileNameLabel->setText(filename);
}
QString Creator::getDefaultSaveDir()
{
static QString defaultDir;
if (defaultDir.isEmpty()) {
defaultDir = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
if (defaultDir.isEmpty())
defaultDir = QDir::homePath();
}
return defaultDir;
}
void Creator::handleDownloadError(const QString message)
{
qDebug() << "Something went wrong with download:" << message;
downloadProgressBarText(message);
if (state == STATE_GET_VERSION)
downloadReleases();
}
void Creator::handleFinishedDownload(const QByteArray &data)
{
switch (state) {
case STATE_GET_VERSION:
state = STATE_IDLE;
#ifdef FORCE_UPDATE_NOTIFICATION
checkNewVersion(FORCE_UPDATE_NOTIFICATION);
#else
checkNewVersion(data);
#endif
downloadReleases();
break;
case STATE_GET_RELEASES:
parseJsonAndSet(data);
ui->downloadButton->setEnabled(true);
state = STATE_IDLE;
break;
case STATE_DOWNLOADING_IMAGE:
// whole data at once (no partial)
if (bytesDownloaded == 0) {
downloadProgressBarText(tr("Download complete, syncing file..."));
qApp->processEvents(); // fix this
handlePartialData(data, data.size());
}
resetProgressBars();
imageFile.close();
downloadProgressBarText(tr("Download complete, verifying checksum..."));
if (isChecksumValid(imageHash.result().toHex()))
downloadProgressBarText(tr("Download complete, checksum ok."));
else
downloadProgressBarText(tr("Download complete, checksum not ok."));